Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- testbed/Aider-AI__aider/.github/workflows/release.yml +31 -0
- testbed/Aider-AI__aider/.github/workflows/ubuntu-tests.yml +39 -0
- testbed/Aider-AI__aider/.github/workflows/windows-tests.yml +38 -0
- testbed/Aider-AI__aider/_layouts/default.html +50 -0
- testbed/Aider-AI__aider/aider/__init__.py +1 -0
- testbed/Aider-AI__aider/aider/coders/__init__.py +15 -0
- testbed/Aider-AI__aider/aider/coders/base_coder.py +904 -0
- testbed/Aider-AI__aider/aider/coders/base_prompts.py +8 -0
- testbed/Aider-AI__aider/aider/coders/editblock_coder.py +406 -0
- testbed/Aider-AI__aider/aider/coders/editblock_func_coder.py +140 -0
- testbed/Aider-AI__aider/aider/coders/editblock_func_prompts.py +27 -0
- testbed/Aider-AI__aider/aider/coders/editblock_prompts.py +61 -0
- testbed/Aider-AI__aider/aider/coders/single_wholefile_func_coder.py +111 -0
- testbed/Aider-AI__aider/aider/coders/single_wholefile_func_prompts.py +27 -0
- testbed/Aider-AI__aider/aider/coders/wholefile_coder.py +137 -0
- testbed/Aider-AI__aider/aider/coders/wholefile_func_coder.py +132 -0
- testbed/Aider-AI__aider/aider/coders/wholefile_func_prompts.py +27 -0
- testbed/Aider-AI__aider/aider/coders/wholefile_prompts.py +43 -0
- testbed/Aider-AI__aider/aider/commands.py +486 -0
- testbed/Aider-AI__aider/aider/diffs.py +129 -0
- testbed/Aider-AI__aider/aider/dump.py +29 -0
- testbed/Aider-AI__aider/aider/history.py +132 -0
- testbed/Aider-AI__aider/aider/io.py +338 -0
- testbed/Aider-AI__aider/aider/main.py +536 -0
- testbed/Aider-AI__aider/aider/models.py +76 -0
- testbed/Aider-AI__aider/aider/prompts.py +44 -0
- testbed/Aider-AI__aider/aider/repo.py +194 -0
- testbed/Aider-AI__aider/aider/repomap.py +471 -0
- testbed/Aider-AI__aider/aider/sendchat.py +79 -0
- testbed/Aider-AI__aider/aider/utils.py +27 -0
- testbed/Aider-AI__aider/aider/versioncheck.py +27 -0
- testbed/Aider-AI__aider/aider/voice.py +90 -0
- testbed/Aider-AI__aider/assets/benchmarks.svg +2198 -0
- testbed/Aider-AI__aider/assets/css/style.scss +67 -0
- testbed/Aider-AI__aider/assets/screencast.svg +0 -0
- testbed/Aider-AI__aider/benchmark/__init__.py +0 -0
- testbed/Aider-AI__aider/benchmark/benchmark.py +696 -0
- testbed/Aider-AI__aider/benchmark/docker.sh +12 -0
- testbed/Aider-AI__aider/benchmark/docker_build.sh +8 -0
- testbed/Aider-AI__aider/benchmark/plot.sh +29 -0
- testbed/Aider-AI__aider/benchmark/prompts.py +16 -0
- testbed/Aider-AI__aider/benchmark/rungrid.py +60 -0
- testbed/Aider-AI__aider/benchmark/test_benchmark.py +47 -0
- testbed/Aider-AI__aider/docs/install.md +147 -0
- testbed/Aider-AI__aider/examples/pong.md +304 -0
- testbed/Aider-AI__aider/tests/test_coder.py +366 -0
- testbed/Aider-AI__aider/tests/test_editblock.py +350 -0
- testbed/Aider-AI__aider/tests/test_io.py +24 -0
- testbed/Aider-AI__aider/tests/test_main.py +180 -0
- testbed/Aider-AI__aider/tests/test_repo.py +196 -0
testbed/Aider-AI__aider/.github/workflows/release.yml
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Release
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
tags:
|
| 6 |
+
- 'v*'
|
| 7 |
+
|
| 8 |
+
jobs:
|
| 9 |
+
build_and_publish:
|
| 10 |
+
runs-on: ubuntu-latest
|
| 11 |
+
steps:
|
| 12 |
+
- name: Checkout code
|
| 13 |
+
uses: actions/checkout@v3
|
| 14 |
+
|
| 15 |
+
- name: Set up Python
|
| 16 |
+
uses: actions/setup-python@v4
|
| 17 |
+
with:
|
| 18 |
+
python-version: 3.x
|
| 19 |
+
|
| 20 |
+
- name: Install dependencies
|
| 21 |
+
run: |
|
| 22 |
+
python -m pip install --upgrade pip
|
| 23 |
+
pip install setuptools wheel twine
|
| 24 |
+
|
| 25 |
+
- name: Build and publish
|
| 26 |
+
env:
|
| 27 |
+
TWINE_USERNAME: __token__
|
| 28 |
+
TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
|
| 29 |
+
run: |
|
| 30 |
+
python setup.py sdist bdist_wheel
|
| 31 |
+
twine upload dist/*
|
testbed/Aider-AI__aider/.github/workflows/ubuntu-tests.yml
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Ubuntu Python Tests
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches:
|
| 6 |
+
- main
|
| 7 |
+
pull_request:
|
| 8 |
+
branches:
|
| 9 |
+
- main
|
| 10 |
+
|
| 11 |
+
jobs:
|
| 12 |
+
build:
|
| 13 |
+
runs-on: ubuntu-latest
|
| 14 |
+
strategy:
|
| 15 |
+
matrix:
|
| 16 |
+
python-version: ["3.9", "3.10", "3.11"]
|
| 17 |
+
|
| 18 |
+
steps:
|
| 19 |
+
- name: Check out repository
|
| 20 |
+
uses: actions/checkout@v3
|
| 21 |
+
|
| 22 |
+
- name: Set up Python ${{ matrix.python-version }}
|
| 23 |
+
uses: actions/setup-python@v4
|
| 24 |
+
with:
|
| 25 |
+
python-version: ${{ matrix.python-version }}
|
| 26 |
+
|
| 27 |
+
- name: Install universal ctags
|
| 28 |
+
run: |
|
| 29 |
+
sudo apt-get update
|
| 30 |
+
sudo apt-get install -y universal-ctags
|
| 31 |
+
|
| 32 |
+
- name: Install dependencies
|
| 33 |
+
run: |
|
| 34 |
+
python -m pip install --upgrade pip
|
| 35 |
+
pip install -r requirements.txt
|
| 36 |
+
|
| 37 |
+
- name: Run tests
|
| 38 |
+
run: |
|
| 39 |
+
python -m unittest discover -s tests
|
testbed/Aider-AI__aider/.github/workflows/windows-tests.yml
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Windows Python Tests
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches:
|
| 6 |
+
- main
|
| 7 |
+
pull_request:
|
| 8 |
+
branches:
|
| 9 |
+
- main
|
| 10 |
+
|
| 11 |
+
jobs:
|
| 12 |
+
build:
|
| 13 |
+
runs-on: windows-latest
|
| 14 |
+
strategy:
|
| 15 |
+
matrix:
|
| 16 |
+
python-version: ["3.9", "3.10", "3.11"]
|
| 17 |
+
|
| 18 |
+
steps:
|
| 19 |
+
- name: Check out repository
|
| 20 |
+
uses: actions/checkout@v3
|
| 21 |
+
|
| 22 |
+
- name: Set up Python ${{ matrix.python-version }}
|
| 23 |
+
uses: actions/setup-python@v4
|
| 24 |
+
with:
|
| 25 |
+
python-version: ${{ matrix.python-version }}
|
| 26 |
+
|
| 27 |
+
- name: Install universal ctags
|
| 28 |
+
run: |
|
| 29 |
+
choco install universal-ctags
|
| 30 |
+
|
| 31 |
+
- name: Install dependencies
|
| 32 |
+
run: |
|
| 33 |
+
python -m pip install --upgrade pip
|
| 34 |
+
pip install -r requirements.txt
|
| 35 |
+
|
| 36 |
+
- name: Run tests
|
| 37 |
+
run: |
|
| 38 |
+
python -m unittest discover -s tests
|
testbed/Aider-AI__aider/_layouts/default.html
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="{{ site.lang | default: "en-US" }}">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
|
| 6 |
+
{% seo %}
|
| 7 |
+
<meta property="og:image" content="{{ site.url }}/assets/screenshot.png">
|
| 8 |
+
<meta property="twitter:image" content="{{ site.url }}/assets/screenshot.png">
|
| 9 |
+
<link rel="preconnect" href="https://fonts.gstatic.com">
|
| 10 |
+
<link rel="preload" href="https://fonts.googleapis.com/css?family=Open+Sans:400,700&display=swap" as="style" type="text/css" crossorigin>
|
| 11 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 12 |
+
<meta name="theme-color" content="#157878">
|
| 13 |
+
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
| 14 |
+
<link rel="stylesheet" href="{{ '/assets/css/style.css?v=' | append: site.github.build_revision | relative_url }}">
|
| 15 |
+
{% include head-custom.html %}
|
| 16 |
+
</head>
|
| 17 |
+
<body>
|
| 18 |
+
<a id="skip-to-content" href="#content">Skip to the content.</a>
|
| 19 |
+
|
| 20 |
+
<header class="page-header" role="banner">
|
| 21 |
+
{% if page.url == "/" %}
|
| 22 |
+
<h1 class="project-name">aider</h1>
|
| 23 |
+
<h2 class="project-tagline">AI pair programming in your terminal</h2>
|
| 24 |
+
{% else %}
|
| 25 |
+
<h1 class="project-name">{{ page.title | default: site.title | default: site.github.repository_name }}</h1>
|
| 26 |
+
<h2 class="project-tagline">{{ page.description | default: site.description | default: site.github.project_tagline }}</h2>
|
| 27 |
+
{% endif %}
|
| 28 |
+
<a href="{{ site.baseurl }}/" class="btn">Home</a>
|
| 29 |
+
<a href="{{ site.baseurl }}/examples/" class="btn">Examples</a>
|
| 30 |
+
{% if site.github.is_project_page %}
|
| 31 |
+
<a href="{{ site.github.repository_url }}" class="btn">GitHub</a>
|
| 32 |
+
{% endif %}
|
| 33 |
+
{% if site.show_downloads %}
|
| 34 |
+
<a href="{{ site.github.zip_url }}" class="btn">Download .zip</a>
|
| 35 |
+
<a href="{{ site.github.tar_url }}" class="btn">Download .tar.gz</a>
|
| 36 |
+
{% endif %}
|
| 37 |
+
</header>
|
| 38 |
+
|
| 39 |
+
<main id="content" class="main-content" role="main">
|
| 40 |
+
{{ content }}
|
| 41 |
+
|
| 42 |
+
<footer class="site-footer">
|
| 43 |
+
{% if site.github.is_project_page %}
|
| 44 |
+
<span class="site-footer-owner"><a href="{{ site.github.repository_url }}">{{ site.github.repository_name }}</a> is maintained by <a href="{{ site.github.owner_url }}">{{ site.github.owner_name }}</a>.</span>
|
| 45 |
+
{% endif %}
|
| 46 |
+
<span class="site-footer-credits">This page was generated by <a href="https://pages.github.com">GitHub Pages</a>.</span>
|
| 47 |
+
</footer>
|
| 48 |
+
</main>
|
| 49 |
+
</body>
|
| 50 |
+
</html>
|
testbed/Aider-AI__aider/aider/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
__version__ = "0.12.1-dev"
|
testbed/Aider-AI__aider/aider/coders/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .base_coder import Coder
|
| 2 |
+
from .editblock_coder import EditBlockCoder
|
| 3 |
+
from .editblock_func_coder import EditBlockFunctionCoder
|
| 4 |
+
from .single_wholefile_func_coder import SingleWholeFileFunctionCoder
|
| 5 |
+
from .wholefile_coder import WholeFileCoder
|
| 6 |
+
from .wholefile_func_coder import WholeFileFunctionCoder
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
Coder,
|
| 10 |
+
EditBlockCoder,
|
| 11 |
+
WholeFileCoder,
|
| 12 |
+
WholeFileFunctionCoder,
|
| 13 |
+
EditBlockFunctionCoder,
|
| 14 |
+
SingleWholeFileFunctionCoder,
|
| 15 |
+
]
|
testbed/Aider-AI__aider/aider/coders/base_coder.py
ADDED
|
@@ -0,0 +1,904 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 6 |
+
import sys
|
| 7 |
+
import threading
|
| 8 |
+
import time
|
| 9 |
+
import traceback
|
| 10 |
+
from json.decoder import JSONDecodeError
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import openai
|
| 14 |
+
from jsonschema import Draft7Validator
|
| 15 |
+
from rich.console import Console, Text
|
| 16 |
+
from rich.live import Live
|
| 17 |
+
from rich.markdown import Markdown
|
| 18 |
+
|
| 19 |
+
from aider import models, prompts, utils
|
| 20 |
+
from aider.commands import Commands
|
| 21 |
+
from aider.history import ChatSummary
|
| 22 |
+
from aider.repo import GitRepo
|
| 23 |
+
from aider.repomap import RepoMap
|
| 24 |
+
from aider.sendchat import send_with_retries
|
| 25 |
+
|
| 26 |
+
from ..dump import dump # noqa: F401
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class MissingAPIKeyError(ValueError):
|
| 30 |
+
pass
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ExhaustedContextWindow(Exception):
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def wrap_fence(name):
|
| 38 |
+
return f"<{name}>", f"</{name}>"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Coder:
|
| 42 |
+
abs_fnames = None
|
| 43 |
+
repo = None
|
| 44 |
+
last_aider_commit_hash = None
|
| 45 |
+
last_asked_for_commit_time = 0
|
| 46 |
+
repo_map = None
|
| 47 |
+
functions = None
|
| 48 |
+
total_cost = 0.0
|
| 49 |
+
num_exhausted_context_windows = 0
|
| 50 |
+
last_keyboard_interrupt = None
|
| 51 |
+
|
| 52 |
+
@classmethod
|
| 53 |
+
def create(
|
| 54 |
+
self,
|
| 55 |
+
main_model,
|
| 56 |
+
edit_format,
|
| 57 |
+
io,
|
| 58 |
+
**kwargs,
|
| 59 |
+
):
|
| 60 |
+
from . import (
|
| 61 |
+
EditBlockCoder,
|
| 62 |
+
EditBlockFunctionCoder,
|
| 63 |
+
SingleWholeFileFunctionCoder,
|
| 64 |
+
WholeFileCoder,
|
| 65 |
+
WholeFileFunctionCoder,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
if not main_model:
|
| 69 |
+
main_model = models.GPT35_16k
|
| 70 |
+
|
| 71 |
+
if not main_model.always_available:
|
| 72 |
+
if not check_model_availability(main_model):
|
| 73 |
+
if main_model != models.GPT4:
|
| 74 |
+
io.tool_error(
|
| 75 |
+
f"API key does not support {main_model.name}, falling back to"
|
| 76 |
+
f" {models.GPT35_16k.name}"
|
| 77 |
+
)
|
| 78 |
+
main_model = models.GPT35_16k
|
| 79 |
+
|
| 80 |
+
if edit_format is None:
|
| 81 |
+
edit_format = main_model.edit_format
|
| 82 |
+
|
| 83 |
+
if edit_format == "diff":
|
| 84 |
+
return EditBlockCoder(main_model, io, **kwargs)
|
| 85 |
+
elif edit_format == "whole":
|
| 86 |
+
return WholeFileCoder(main_model, io, **kwargs)
|
| 87 |
+
elif edit_format == "whole-func":
|
| 88 |
+
return WholeFileFunctionCoder(main_model, io, **kwargs)
|
| 89 |
+
elif edit_format == "single-whole-func":
|
| 90 |
+
return SingleWholeFileFunctionCoder(main_model, io, **kwargs)
|
| 91 |
+
elif edit_format == "diff-func-list":
|
| 92 |
+
return EditBlockFunctionCoder("list", main_model, io, **kwargs)
|
| 93 |
+
elif edit_format in ("diff-func", "diff-func-string"):
|
| 94 |
+
return EditBlockFunctionCoder("string", main_model, io, **kwargs)
|
| 95 |
+
else:
|
| 96 |
+
raise ValueError(f"Unknown edit format {edit_format}")
|
| 97 |
+
|
| 98 |
+
def __init__(
|
| 99 |
+
self,
|
| 100 |
+
main_model,
|
| 101 |
+
io,
|
| 102 |
+
fnames=None,
|
| 103 |
+
git_dname=None,
|
| 104 |
+
pretty=True,
|
| 105 |
+
show_diffs=False,
|
| 106 |
+
auto_commits=True,
|
| 107 |
+
dirty_commits=True,
|
| 108 |
+
dry_run=False,
|
| 109 |
+
map_tokens=1024,
|
| 110 |
+
verbose=False,
|
| 111 |
+
assistant_output_color="blue",
|
| 112 |
+
code_theme="default",
|
| 113 |
+
stream=True,
|
| 114 |
+
use_git=True,
|
| 115 |
+
voice_language=None,
|
| 116 |
+
):
|
| 117 |
+
if not fnames:
|
| 118 |
+
fnames = []
|
| 119 |
+
|
| 120 |
+
self.chat_completion_call_hashes = []
|
| 121 |
+
self.chat_completion_response_hashes = []
|
| 122 |
+
|
| 123 |
+
self.verbose = verbose
|
| 124 |
+
self.abs_fnames = set()
|
| 125 |
+
self.cur_messages = []
|
| 126 |
+
self.done_messages = []
|
| 127 |
+
|
| 128 |
+
self.io = io
|
| 129 |
+
self.stream = stream
|
| 130 |
+
|
| 131 |
+
if not auto_commits:
|
| 132 |
+
dirty_commits = False
|
| 133 |
+
|
| 134 |
+
self.auto_commits = auto_commits
|
| 135 |
+
self.dirty_commits = dirty_commits
|
| 136 |
+
self.assistant_output_color = assistant_output_color
|
| 137 |
+
self.code_theme = code_theme
|
| 138 |
+
|
| 139 |
+
self.dry_run = dry_run
|
| 140 |
+
self.pretty = pretty
|
| 141 |
+
|
| 142 |
+
if pretty:
|
| 143 |
+
self.console = Console()
|
| 144 |
+
else:
|
| 145 |
+
self.console = Console(force_terminal=False, no_color=True)
|
| 146 |
+
|
| 147 |
+
self.main_model = main_model
|
| 148 |
+
|
| 149 |
+
self.io.tool_output(f"Model: {main_model.name}")
|
| 150 |
+
|
| 151 |
+
self.show_diffs = show_diffs
|
| 152 |
+
|
| 153 |
+
self.commands = Commands(self.io, self, voice_language)
|
| 154 |
+
|
| 155 |
+
for fname in fnames:
|
| 156 |
+
fname = Path(fname)
|
| 157 |
+
if not fname.exists():
|
| 158 |
+
self.io.tool_output(f"Creating empty file {fname}")
|
| 159 |
+
fname.parent.mkdir(parents=True, exist_ok=True)
|
| 160 |
+
fname.touch()
|
| 161 |
+
|
| 162 |
+
if not fname.is_file():
|
| 163 |
+
raise ValueError(f"{fname} is not a file")
|
| 164 |
+
|
| 165 |
+
self.abs_fnames.add(str(fname.resolve()))
|
| 166 |
+
|
| 167 |
+
if use_git:
|
| 168 |
+
try:
|
| 169 |
+
self.repo = GitRepo(self.io, fnames, git_dname)
|
| 170 |
+
self.root = self.repo.root
|
| 171 |
+
except FileNotFoundError:
|
| 172 |
+
self.repo = None
|
| 173 |
+
|
| 174 |
+
if self.repo:
|
| 175 |
+
rel_repo_dir = self.repo.get_rel_repo_dir()
|
| 176 |
+
self.io.tool_output(f"Git repo: {rel_repo_dir}")
|
| 177 |
+
else:
|
| 178 |
+
self.io.tool_output("Git repo: none")
|
| 179 |
+
self.find_common_root()
|
| 180 |
+
|
| 181 |
+
if main_model.use_repo_map and self.repo and self.gpt_prompts.repo_content_prefix:
|
| 182 |
+
self.repo_map = RepoMap(
|
| 183 |
+
map_tokens,
|
| 184 |
+
self.root,
|
| 185 |
+
self.main_model,
|
| 186 |
+
io,
|
| 187 |
+
self.gpt_prompts.repo_content_prefix,
|
| 188 |
+
self.verbose,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
if self.repo_map.use_ctags:
|
| 192 |
+
self.io.tool_output(f"Repo-map: universal-ctags using {map_tokens} tokens")
|
| 193 |
+
elif not self.repo_map.has_ctags and map_tokens > 0:
|
| 194 |
+
self.io.tool_output(
|
| 195 |
+
f"Repo-map: basic using {map_tokens} tokens"
|
| 196 |
+
f" ({self.repo_map.ctags_disabled_reason})"
|
| 197 |
+
)
|
| 198 |
+
else:
|
| 199 |
+
self.io.tool_output("Repo-map: disabled because map_tokens == 0")
|
| 200 |
+
else:
|
| 201 |
+
self.io.tool_output("Repo-map: disabled")
|
| 202 |
+
|
| 203 |
+
for fname in self.get_inchat_relative_files():
|
| 204 |
+
self.io.tool_output(f"Added {fname} to the chat.")
|
| 205 |
+
|
| 206 |
+
if self.repo:
|
| 207 |
+
self.repo.add_new_files(fname for fname in fnames if not Path(fname).is_dir())
|
| 208 |
+
|
| 209 |
+
self.summarizer = ChatSummary()
|
| 210 |
+
self.summarizer_thread = None
|
| 211 |
+
self.summarized_done_messages = None
|
| 212 |
+
|
| 213 |
+
# validate the functions jsonschema
|
| 214 |
+
if self.functions:
|
| 215 |
+
for function in self.functions:
|
| 216 |
+
Draft7Validator.check_schema(function)
|
| 217 |
+
|
| 218 |
+
if self.verbose:
|
| 219 |
+
self.io.tool_output("JSON Schema:")
|
| 220 |
+
self.io.tool_output(json.dumps(self.functions, indent=4))
|
| 221 |
+
|
| 222 |
+
def find_common_root(self):
|
| 223 |
+
if len(self.abs_fnames) == 1:
|
| 224 |
+
self.root = os.path.dirname(list(self.abs_fnames)[0])
|
| 225 |
+
elif self.abs_fnames:
|
| 226 |
+
self.root = os.path.commonpath(list(self.abs_fnames))
|
| 227 |
+
else:
|
| 228 |
+
self.root = os.getcwd()
|
| 229 |
+
|
| 230 |
+
self.root = utils.safe_abs_path(self.root)
|
| 231 |
+
|
| 232 |
+
def add_rel_fname(self, rel_fname):
|
| 233 |
+
self.abs_fnames.add(self.abs_root_path(rel_fname))
|
| 234 |
+
|
| 235 |
+
def abs_root_path(self, path):
|
| 236 |
+
res = Path(self.root) / path
|
| 237 |
+
return utils.safe_abs_path(res)
|
| 238 |
+
|
| 239 |
+
fences = [
|
| 240 |
+
("``" + "`", "``" + "`"),
|
| 241 |
+
wrap_fence("source"),
|
| 242 |
+
wrap_fence("code"),
|
| 243 |
+
wrap_fence("pre"),
|
| 244 |
+
wrap_fence("codeblock"),
|
| 245 |
+
wrap_fence("sourcecode"),
|
| 246 |
+
]
|
| 247 |
+
fence = fences[0]
|
| 248 |
+
|
| 249 |
+
def get_abs_fnames_content(self):
|
| 250 |
+
for fname in list(self.abs_fnames):
|
| 251 |
+
content = self.io.read_text(fname)
|
| 252 |
+
|
| 253 |
+
if content is None:
|
| 254 |
+
relative_fname = self.get_rel_fname(fname)
|
| 255 |
+
self.io.tool_error(f"Dropping {relative_fname} from the chat.")
|
| 256 |
+
self.abs_fnames.remove(fname)
|
| 257 |
+
else:
|
| 258 |
+
yield fname, content
|
| 259 |
+
|
| 260 |
+
def choose_fence(self):
|
| 261 |
+
all_content = ""
|
| 262 |
+
for _fname, content in self.get_abs_fnames_content():
|
| 263 |
+
all_content += content + "\n"
|
| 264 |
+
|
| 265 |
+
good = False
|
| 266 |
+
for fence_open, fence_close in self.fences:
|
| 267 |
+
if fence_open in all_content or fence_close in all_content:
|
| 268 |
+
continue
|
| 269 |
+
good = True
|
| 270 |
+
break
|
| 271 |
+
|
| 272 |
+
if good:
|
| 273 |
+
self.fence = (fence_open, fence_close)
|
| 274 |
+
else:
|
| 275 |
+
self.fence = self.fences[0]
|
| 276 |
+
self.io.tool_error(
|
| 277 |
+
"Unable to find a fencing strategy! Falling back to:"
|
| 278 |
+
" {self.fence[0]}...{self.fence[1]}"
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
return
|
| 282 |
+
|
| 283 |
+
def get_files_content(self, fnames=None):
|
| 284 |
+
if not fnames:
|
| 285 |
+
fnames = self.abs_fnames
|
| 286 |
+
|
| 287 |
+
prompt = ""
|
| 288 |
+
for fname, content in self.get_abs_fnames_content():
|
| 289 |
+
relative_fname = self.get_rel_fname(fname)
|
| 290 |
+
prompt += "\n"
|
| 291 |
+
prompt += relative_fname
|
| 292 |
+
prompt += f"\n{self.fence[0]}\n"
|
| 293 |
+
prompt += content
|
| 294 |
+
prompt += f"{self.fence[1]}\n"
|
| 295 |
+
|
| 296 |
+
return prompt
|
| 297 |
+
|
| 298 |
+
def get_repo_map(self):
|
| 299 |
+
if not self.repo_map:
|
| 300 |
+
return
|
| 301 |
+
|
| 302 |
+
other_files = set(self.get_all_abs_files()) - set(self.abs_fnames)
|
| 303 |
+
repo_content = self.repo_map.get_repo_map(self.abs_fnames, other_files)
|
| 304 |
+
return repo_content
|
| 305 |
+
|
| 306 |
+
def get_files_messages(self):
|
| 307 |
+
all_content = ""
|
| 308 |
+
if self.abs_fnames:
|
| 309 |
+
files_content = self.gpt_prompts.files_content_prefix
|
| 310 |
+
files_content += self.get_files_content()
|
| 311 |
+
else:
|
| 312 |
+
files_content = self.gpt_prompts.files_no_full_files
|
| 313 |
+
|
| 314 |
+
all_content += files_content
|
| 315 |
+
|
| 316 |
+
repo_content = self.get_repo_map()
|
| 317 |
+
if repo_content:
|
| 318 |
+
if all_content:
|
| 319 |
+
all_content += "\n"
|
| 320 |
+
all_content += repo_content
|
| 321 |
+
|
| 322 |
+
files_messages = [
|
| 323 |
+
dict(role="user", content=all_content),
|
| 324 |
+
dict(role="assistant", content="Ok."),
|
| 325 |
+
]
|
| 326 |
+
if self.abs_fnames:
|
| 327 |
+
files_messages += [
|
| 328 |
+
dict(role="system", content=self.fmt_system_reminder()),
|
| 329 |
+
]
|
| 330 |
+
|
| 331 |
+
return files_messages
|
| 332 |
+
|
| 333 |
+
def run(self, with_message=None):
|
| 334 |
+
while True:
|
| 335 |
+
try:
|
| 336 |
+
if with_message:
|
| 337 |
+
new_user_message = with_message
|
| 338 |
+
self.io.user_input(with_message)
|
| 339 |
+
else:
|
| 340 |
+
new_user_message = self.run_loop()
|
| 341 |
+
|
| 342 |
+
while new_user_message:
|
| 343 |
+
new_user_message = self.send_new_user_message(new_user_message)
|
| 344 |
+
|
| 345 |
+
if with_message:
|
| 346 |
+
return
|
| 347 |
+
|
| 348 |
+
except KeyboardInterrupt:
|
| 349 |
+
self.keyboard_interrupt()
|
| 350 |
+
except EOFError:
|
| 351 |
+
return
|
| 352 |
+
|
| 353 |
+
def keyboard_interrupt(self):
|
| 354 |
+
now = time.time()
|
| 355 |
+
|
| 356 |
+
thresh = 2 # seconds
|
| 357 |
+
if self.last_keyboard_interrupt and now - self.last_keyboard_interrupt < thresh:
|
| 358 |
+
self.io.tool_error("\n\n^C KeyboardInterrupt")
|
| 359 |
+
sys.exit()
|
| 360 |
+
|
| 361 |
+
self.io.tool_error("\n\n^C again to exit")
|
| 362 |
+
|
| 363 |
+
self.last_keyboard_interrupt = now
|
| 364 |
+
|
| 365 |
+
def summarize_start(self):
|
| 366 |
+
if not self.summarizer.too_big(self.done_messages):
|
| 367 |
+
return
|
| 368 |
+
|
| 369 |
+
self.summarize_end()
|
| 370 |
+
|
| 371 |
+
if self.verbose:
|
| 372 |
+
self.io.tool_output("Starting to summarize chat history.")
|
| 373 |
+
|
| 374 |
+
self.summarizer_thread = threading.Thread(target=self.summarize_worker)
|
| 375 |
+
self.summarizer_thread.start()
|
| 376 |
+
|
| 377 |
+
def summarize_worker(self):
|
| 378 |
+
self.summarized_done_messages = self.summarizer.summarize(self.done_messages)
|
| 379 |
+
if self.verbose:
|
| 380 |
+
self.io.tool_output("Finished summarizing chat history.")
|
| 381 |
+
|
| 382 |
+
def summarize_end(self):
|
| 383 |
+
if self.summarizer_thread is None:
|
| 384 |
+
return
|
| 385 |
+
|
| 386 |
+
self.summarizer_thread.join()
|
| 387 |
+
self.summarizer_thread = None
|
| 388 |
+
|
| 389 |
+
self.done_messages = self.summarized_done_messages
|
| 390 |
+
self.summarized_done_messages = None
|
| 391 |
+
|
| 392 |
+
def move_back_cur_messages(self, message):
|
| 393 |
+
self.done_messages += self.cur_messages
|
| 394 |
+
self.summarize_start()
|
| 395 |
+
|
| 396 |
+
if message:
|
| 397 |
+
self.done_messages += [
|
| 398 |
+
dict(role="user", content=message),
|
| 399 |
+
dict(role="assistant", content="Ok."),
|
| 400 |
+
]
|
| 401 |
+
self.cur_messages = []
|
| 402 |
+
|
| 403 |
+
def run_loop(self):
|
| 404 |
+
inp = self.io.get_input(
|
| 405 |
+
self.root,
|
| 406 |
+
self.get_inchat_relative_files(),
|
| 407 |
+
self.get_addable_relative_files(),
|
| 408 |
+
self.commands,
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
if self.should_dirty_commit(inp) and self.dirty_commit():
|
| 412 |
+
if inp.strip():
|
| 413 |
+
self.io.tool_output("Use up-arrow to retry previous command:", inp)
|
| 414 |
+
return
|
| 415 |
+
|
| 416 |
+
if not inp:
|
| 417 |
+
return
|
| 418 |
+
|
| 419 |
+
if self.commands.is_command(inp):
|
| 420 |
+
return self.commands.run(inp)
|
| 421 |
+
|
| 422 |
+
self.check_for_file_mentions(inp)
|
| 423 |
+
|
| 424 |
+
return self.send_new_user_message(inp)
|
| 425 |
+
|
| 426 |
+
def fmt_system_reminder(self):
|
| 427 |
+
prompt = self.gpt_prompts.system_reminder
|
| 428 |
+
prompt = prompt.format(fence=self.fence)
|
| 429 |
+
return prompt
|
| 430 |
+
|
| 431 |
+
def send_new_user_message(self, inp):
|
| 432 |
+
self.choose_fence()
|
| 433 |
+
|
| 434 |
+
self.cur_messages += [
|
| 435 |
+
dict(role="user", content=inp),
|
| 436 |
+
]
|
| 437 |
+
|
| 438 |
+
main_sys = self.gpt_prompts.main_system
|
| 439 |
+
# if self.main_model.max_context_tokens > 4 * 1024:
|
| 440 |
+
main_sys += "\n" + self.fmt_system_reminder()
|
| 441 |
+
|
| 442 |
+
messages = [
|
| 443 |
+
dict(role="system", content=main_sys),
|
| 444 |
+
]
|
| 445 |
+
|
| 446 |
+
self.summarize_end()
|
| 447 |
+
messages += self.done_messages
|
| 448 |
+
messages += self.get_files_messages()
|
| 449 |
+
messages += self.cur_messages
|
| 450 |
+
|
| 451 |
+
if self.verbose:
|
| 452 |
+
utils.show_messages(messages, functions=self.functions)
|
| 453 |
+
|
| 454 |
+
exhausted = False
|
| 455 |
+
interrupted = False
|
| 456 |
+
try:
|
| 457 |
+
interrupted = self.send(messages, functions=self.functions)
|
| 458 |
+
except ExhaustedContextWindow:
|
| 459 |
+
exhausted = True
|
| 460 |
+
except openai.error.InvalidRequestError as err:
|
| 461 |
+
if "maximum context length" in str(err):
|
| 462 |
+
exhausted = True
|
| 463 |
+
else:
|
| 464 |
+
raise err
|
| 465 |
+
|
| 466 |
+
if exhausted:
|
| 467 |
+
self.num_exhausted_context_windows += 1
|
| 468 |
+
self.io.tool_error("The chat session is larger than the context window!\n")
|
| 469 |
+
self.commands.cmd_tokens("")
|
| 470 |
+
self.io.tool_error("\nTo reduce token usage:")
|
| 471 |
+
self.io.tool_error(" - Use /drop to remove unneeded files from the chat session.")
|
| 472 |
+
self.io.tool_error(" - Use /clear to clear chat history.")
|
| 473 |
+
return
|
| 474 |
+
|
| 475 |
+
if self.partial_response_function_call:
|
| 476 |
+
args = self.parse_partial_args()
|
| 477 |
+
if args:
|
| 478 |
+
content = args["explanation"]
|
| 479 |
+
else:
|
| 480 |
+
content = ""
|
| 481 |
+
elif self.partial_response_content:
|
| 482 |
+
content = self.partial_response_content
|
| 483 |
+
else:
|
| 484 |
+
content = ""
|
| 485 |
+
|
| 486 |
+
if interrupted:
|
| 487 |
+
content += "\n^C KeyboardInterrupt"
|
| 488 |
+
|
| 489 |
+
self.io.tool_output()
|
| 490 |
+
if interrupted:
|
| 491 |
+
self.cur_messages += [dict(role="assistant", content=content)]
|
| 492 |
+
return
|
| 493 |
+
|
| 494 |
+
edited, edit_error = self.apply_updates()
|
| 495 |
+
if edit_error:
|
| 496 |
+
self.update_cur_messages(set())
|
| 497 |
+
return edit_error
|
| 498 |
+
|
| 499 |
+
self.update_cur_messages(edited)
|
| 500 |
+
|
| 501 |
+
if edited:
|
| 502 |
+
if self.repo and self.auto_commits and not self.dry_run:
|
| 503 |
+
saved_message = self.auto_commit()
|
| 504 |
+
elif hasattr(self.gpt_prompts, "files_content_gpt_edits_no_repo"):
|
| 505 |
+
saved_message = self.gpt_prompts.files_content_gpt_edits_no_repo
|
| 506 |
+
else:
|
| 507 |
+
saved_message = None
|
| 508 |
+
|
| 509 |
+
self.move_back_cur_messages(saved_message)
|
| 510 |
+
|
| 511 |
+
add_rel_files_message = self.check_for_file_mentions(content)
|
| 512 |
+
if add_rel_files_message:
|
| 513 |
+
return add_rel_files_message
|
| 514 |
+
|
| 515 |
+
def update_cur_messages(self, edited):
|
| 516 |
+
if self.partial_response_content:
|
| 517 |
+
self.cur_messages += [dict(role="assistant", content=self.partial_response_content)]
|
| 518 |
+
if self.partial_response_function_call:
|
| 519 |
+
self.cur_messages += [
|
| 520 |
+
dict(
|
| 521 |
+
role="assistant",
|
| 522 |
+
content=None,
|
| 523 |
+
function_call=self.partial_response_function_call,
|
| 524 |
+
)
|
| 525 |
+
]
|
| 526 |
+
|
| 527 |
+
def check_for_file_mentions(self, content):
|
| 528 |
+
words = set(word for word in content.split())
|
| 529 |
+
|
| 530 |
+
# drop sentence punctuation from the end
|
| 531 |
+
words = set(word.rstrip(",.!;") for word in words)
|
| 532 |
+
|
| 533 |
+
# strip away all kinds of quotes
|
| 534 |
+
quotes = "".join(['"', "'", "`"])
|
| 535 |
+
words = set(word.strip(quotes) for word in words)
|
| 536 |
+
|
| 537 |
+
addable_rel_fnames = self.get_addable_relative_files()
|
| 538 |
+
|
| 539 |
+
mentioned_rel_fnames = set()
|
| 540 |
+
fname_to_rel_fnames = {}
|
| 541 |
+
for rel_fname in addable_rel_fnames:
|
| 542 |
+
if rel_fname in words:
|
| 543 |
+
mentioned_rel_fnames.add(str(rel_fname))
|
| 544 |
+
|
| 545 |
+
fname = os.path.basename(rel_fname)
|
| 546 |
+
if fname not in fname_to_rel_fnames:
|
| 547 |
+
fname_to_rel_fnames[fname] = []
|
| 548 |
+
fname_to_rel_fnames[fname].append(rel_fname)
|
| 549 |
+
|
| 550 |
+
for fname, rel_fnames in fname_to_rel_fnames.items():
|
| 551 |
+
if len(rel_fnames) == 1 and fname in words:
|
| 552 |
+
mentioned_rel_fnames.add(rel_fnames[0])
|
| 553 |
+
|
| 554 |
+
if not mentioned_rel_fnames:
|
| 555 |
+
return
|
| 556 |
+
|
| 557 |
+
for rel_fname in mentioned_rel_fnames:
|
| 558 |
+
self.io.tool_output(rel_fname)
|
| 559 |
+
|
| 560 |
+
if not self.io.confirm_ask("Add these files to the chat?"):
|
| 561 |
+
return
|
| 562 |
+
|
| 563 |
+
for rel_fname in mentioned_rel_fnames:
|
| 564 |
+
self.add_rel_fname(rel_fname)
|
| 565 |
+
|
| 566 |
+
return prompts.added_files.format(fnames=", ".join(mentioned_rel_fnames))
|
| 567 |
+
|
| 568 |
+
def send(self, messages, model=None, functions=None):
|
| 569 |
+
if not model:
|
| 570 |
+
model = self.main_model.name
|
| 571 |
+
|
| 572 |
+
self.partial_response_content = ""
|
| 573 |
+
self.partial_response_function_call = dict()
|
| 574 |
+
|
| 575 |
+
interrupted = False
|
| 576 |
+
try:
|
| 577 |
+
hash_object, completion = send_with_retries(model, messages, functions, self.stream)
|
| 578 |
+
self.chat_completion_call_hashes.append(hash_object.hexdigest())
|
| 579 |
+
|
| 580 |
+
if self.stream:
|
| 581 |
+
self.show_send_output_stream(completion)
|
| 582 |
+
else:
|
| 583 |
+
self.show_send_output(completion)
|
| 584 |
+
except KeyboardInterrupt:
|
| 585 |
+
self.keyboard_interrupt()
|
| 586 |
+
interrupted = True
|
| 587 |
+
|
| 588 |
+
if self.partial_response_content:
|
| 589 |
+
self.io.ai_output(self.partial_response_content)
|
| 590 |
+
elif self.partial_response_function_call:
|
| 591 |
+
# TODO: push this into subclasses
|
| 592 |
+
args = self.parse_partial_args()
|
| 593 |
+
if args:
|
| 594 |
+
self.io.ai_output(json.dumps(args, indent=4))
|
| 595 |
+
|
| 596 |
+
return interrupted
|
| 597 |
+
|
| 598 |
+
def show_send_output(self, completion):
|
| 599 |
+
if self.verbose:
|
| 600 |
+
print(completion)
|
| 601 |
+
|
| 602 |
+
show_func_err = None
|
| 603 |
+
show_content_err = None
|
| 604 |
+
try:
|
| 605 |
+
self.partial_response_function_call = completion.choices[0].message.function_call
|
| 606 |
+
except AttributeError as func_err:
|
| 607 |
+
show_func_err = func_err
|
| 608 |
+
|
| 609 |
+
try:
|
| 610 |
+
self.partial_response_content = completion.choices[0].message.content
|
| 611 |
+
except AttributeError as content_err:
|
| 612 |
+
show_content_err = content_err
|
| 613 |
+
|
| 614 |
+
resp_hash = dict(
|
| 615 |
+
function_call=self.partial_response_function_call,
|
| 616 |
+
content=self.partial_response_content,
|
| 617 |
+
)
|
| 618 |
+
resp_hash = hashlib.sha1(json.dumps(resp_hash, sort_keys=True).encode())
|
| 619 |
+
self.chat_completion_response_hashes.append(resp_hash.hexdigest())
|
| 620 |
+
|
| 621 |
+
if show_func_err and show_content_err:
|
| 622 |
+
self.io.tool_error(show_func_err)
|
| 623 |
+
self.io.tool_error(show_content_err)
|
| 624 |
+
raise Exception("No data found in openai response!")
|
| 625 |
+
|
| 626 |
+
prompt_tokens = completion.usage.prompt_tokens
|
| 627 |
+
completion_tokens = completion.usage.completion_tokens
|
| 628 |
+
|
| 629 |
+
tokens = f"{prompt_tokens} prompt tokens, {completion_tokens} completion tokens"
|
| 630 |
+
if self.main_model.prompt_price:
|
| 631 |
+
cost = prompt_tokens * self.main_model.prompt_price / 1000
|
| 632 |
+
cost += completion_tokens * self.main_model.completion_price / 1000
|
| 633 |
+
tokens += f", ${cost:.6f} cost"
|
| 634 |
+
self.total_cost += cost
|
| 635 |
+
|
| 636 |
+
show_resp = self.render_incremental_response(True)
|
| 637 |
+
if self.pretty:
|
| 638 |
+
show_resp = Markdown(
|
| 639 |
+
show_resp, style=self.assistant_output_color, code_theme=self.code_theme
|
| 640 |
+
)
|
| 641 |
+
else:
|
| 642 |
+
show_resp = Text(show_resp or "<no response>")
|
| 643 |
+
|
| 644 |
+
self.io.console.print(show_resp)
|
| 645 |
+
self.io.tool_output(tokens)
|
| 646 |
+
|
| 647 |
+
def show_send_output_stream(self, completion):
|
| 648 |
+
live = None
|
| 649 |
+
if self.pretty:
|
| 650 |
+
live = Live(vertical_overflow="scroll")
|
| 651 |
+
|
| 652 |
+
try:
|
| 653 |
+
if live:
|
| 654 |
+
live.start()
|
| 655 |
+
|
| 656 |
+
for chunk in completion:
|
| 657 |
+
if len(chunk.choices) == 0:
|
| 658 |
+
continue
|
| 659 |
+
|
| 660 |
+
if chunk.choices[0].finish_reason == "length":
|
| 661 |
+
raise ExhaustedContextWindow()
|
| 662 |
+
|
| 663 |
+
try:
|
| 664 |
+
func = chunk.choices[0].delta.function_call
|
| 665 |
+
# dump(func)
|
| 666 |
+
for k, v in func.items():
|
| 667 |
+
if k in self.partial_response_function_call:
|
| 668 |
+
self.partial_response_function_call[k] += v
|
| 669 |
+
else:
|
| 670 |
+
self.partial_response_function_call[k] = v
|
| 671 |
+
except AttributeError:
|
| 672 |
+
pass
|
| 673 |
+
|
| 674 |
+
try:
|
| 675 |
+
text = chunk.choices[0].delta.content
|
| 676 |
+
if text:
|
| 677 |
+
self.partial_response_content += text
|
| 678 |
+
except AttributeError:
|
| 679 |
+
text = None
|
| 680 |
+
|
| 681 |
+
if self.pretty:
|
| 682 |
+
self.live_incremental_response(live, False)
|
| 683 |
+
elif text:
|
| 684 |
+
sys.stdout.write(text)
|
| 685 |
+
sys.stdout.flush()
|
| 686 |
+
finally:
|
| 687 |
+
if live:
|
| 688 |
+
self.live_incremental_response(live, True)
|
| 689 |
+
live.stop()
|
| 690 |
+
|
| 691 |
+
def live_incremental_response(self, live, final):
|
| 692 |
+
show_resp = self.render_incremental_response(final)
|
| 693 |
+
if not show_resp:
|
| 694 |
+
return
|
| 695 |
+
|
| 696 |
+
md = Markdown(show_resp, style=self.assistant_output_color, code_theme=self.code_theme)
|
| 697 |
+
live.update(md)
|
| 698 |
+
|
| 699 |
+
def render_incremental_response(self, final):
|
| 700 |
+
return self.partial_response_content
|
| 701 |
+
|
| 702 |
+
def get_rel_fname(self, fname):
|
| 703 |
+
return os.path.relpath(fname, self.root)
|
| 704 |
+
|
| 705 |
+
def get_inchat_relative_files(self):
|
| 706 |
+
files = [self.get_rel_fname(fname) for fname in self.abs_fnames]
|
| 707 |
+
return sorted(set(files))
|
| 708 |
+
|
| 709 |
+
def get_all_relative_files(self):
|
| 710 |
+
if self.repo:
|
| 711 |
+
files = self.repo.get_tracked_files()
|
| 712 |
+
else:
|
| 713 |
+
files = self.get_inchat_relative_files()
|
| 714 |
+
|
| 715 |
+
return sorted(set(files))
|
| 716 |
+
|
| 717 |
+
def get_all_abs_files(self):
|
| 718 |
+
files = self.get_all_relative_files()
|
| 719 |
+
files = [self.abs_root_path(path) for path in files]
|
| 720 |
+
return files
|
| 721 |
+
|
| 722 |
+
def get_last_modified(self):
|
| 723 |
+
files = [Path(fn) for fn in self.get_all_abs_files() if Path(fn).exists()]
|
| 724 |
+
if not files:
|
| 725 |
+
return 0
|
| 726 |
+
return max(path.stat().st_mtime for path in files)
|
| 727 |
+
|
| 728 |
+
def get_addable_relative_files(self):
|
| 729 |
+
return set(self.get_all_relative_files()) - set(self.get_inchat_relative_files())
|
| 730 |
+
|
| 731 |
+
def allowed_to_edit(self, path, write_content=None):
|
| 732 |
+
full_path = self.abs_root_path(path)
|
| 733 |
+
|
| 734 |
+
if full_path in self.abs_fnames:
|
| 735 |
+
if write_content:
|
| 736 |
+
self.io.write_text(full_path, write_content)
|
| 737 |
+
return full_path
|
| 738 |
+
|
| 739 |
+
if not Path(full_path).exists():
|
| 740 |
+
question = f"Allow creation of new file {path}?" # noqa: E501
|
| 741 |
+
else:
|
| 742 |
+
question = f"Allow edits to {path} which was not previously provided?" # noqa: E501
|
| 743 |
+
if not self.io.confirm_ask(question):
|
| 744 |
+
self.io.tool_error(f"Skipping edit to {path}")
|
| 745 |
+
return
|
| 746 |
+
|
| 747 |
+
if not Path(full_path).exists() and not self.dry_run:
|
| 748 |
+
Path(full_path).parent.mkdir(parents=True, exist_ok=True)
|
| 749 |
+
Path(full_path).touch()
|
| 750 |
+
|
| 751 |
+
self.abs_fnames.add(full_path)
|
| 752 |
+
|
| 753 |
+
# Check if the file is already in the repo
|
| 754 |
+
if self.repo:
|
| 755 |
+
tracked_files = set(self.repo.get_tracked_files())
|
| 756 |
+
relative_fname = self.get_rel_fname(full_path)
|
| 757 |
+
if relative_fname not in tracked_files and self.io.confirm_ask(f"Add {path} to git?"):
|
| 758 |
+
if not self.dry_run:
|
| 759 |
+
self.repo.repo.git.add(full_path)
|
| 760 |
+
|
| 761 |
+
if write_content:
|
| 762 |
+
self.io.write_text(full_path, write_content)
|
| 763 |
+
|
| 764 |
+
return full_path
|
| 765 |
+
|
| 766 |
+
apply_update_errors = 0
|
| 767 |
+
|
| 768 |
+
def apply_updates(self):
|
| 769 |
+
max_apply_update_errors = 3
|
| 770 |
+
|
| 771 |
+
try:
|
| 772 |
+
edited = self.update_files()
|
| 773 |
+
except ValueError as err:
|
| 774 |
+
err = err.args[0]
|
| 775 |
+
self.apply_update_errors += 1
|
| 776 |
+
if self.apply_update_errors < max_apply_update_errors:
|
| 777 |
+
self.io.tool_error(f"Malformed response #{self.apply_update_errors}, retrying...")
|
| 778 |
+
self.io.tool_error(str(err))
|
| 779 |
+
return None, err
|
| 780 |
+
else:
|
| 781 |
+
self.io.tool_error(f"Malformed response #{self.apply_update_errors}, aborting.")
|
| 782 |
+
return False, None
|
| 783 |
+
|
| 784 |
+
except Exception as err:
|
| 785 |
+
print(err)
|
| 786 |
+
print()
|
| 787 |
+
traceback.print_exc()
|
| 788 |
+
self.apply_update_errors += 1
|
| 789 |
+
if self.apply_update_errors < max_apply_update_errors:
|
| 790 |
+
self.io.tool_error(f"Update exception #{self.apply_update_errors}, retrying...")
|
| 791 |
+
return None, str(err)
|
| 792 |
+
else:
|
| 793 |
+
self.io.tool_error(f"Update exception #{self.apply_update_errors}, aborting")
|
| 794 |
+
return False, None
|
| 795 |
+
|
| 796 |
+
self.apply_update_errors = 0
|
| 797 |
+
|
| 798 |
+
if edited:
|
| 799 |
+
for path in sorted(edited):
|
| 800 |
+
if self.dry_run:
|
| 801 |
+
self.io.tool_output(f"Did not apply edit to {path} (--dry-run)")
|
| 802 |
+
else:
|
| 803 |
+
self.io.tool_output(f"Applied edit to {path}")
|
| 804 |
+
|
| 805 |
+
return edited, None
|
| 806 |
+
|
| 807 |
+
def parse_partial_args(self):
|
| 808 |
+
# dump(self.partial_response_function_call)
|
| 809 |
+
|
| 810 |
+
data = self.partial_response_function_call.get("arguments")
|
| 811 |
+
if not data:
|
| 812 |
+
return
|
| 813 |
+
|
| 814 |
+
try:
|
| 815 |
+
return json.loads(data)
|
| 816 |
+
except JSONDecodeError:
|
| 817 |
+
pass
|
| 818 |
+
|
| 819 |
+
try:
|
| 820 |
+
return json.loads(data + "]}")
|
| 821 |
+
except JSONDecodeError:
|
| 822 |
+
pass
|
| 823 |
+
|
| 824 |
+
try:
|
| 825 |
+
return json.loads(data + "}]}")
|
| 826 |
+
except JSONDecodeError:
|
| 827 |
+
pass
|
| 828 |
+
|
| 829 |
+
try:
|
| 830 |
+
return json.loads(data + '"}]}')
|
| 831 |
+
except JSONDecodeError:
|
| 832 |
+
pass
|
| 833 |
+
|
| 834 |
+
# commits...
|
| 835 |
+
|
| 836 |
+
def get_context_from_history(self, history):
|
| 837 |
+
context = ""
|
| 838 |
+
if history:
|
| 839 |
+
for msg in history:
|
| 840 |
+
context += "\n" + msg["role"].upper() + ": " + msg["content"] + "\n"
|
| 841 |
+
return context
|
| 842 |
+
|
| 843 |
+
def auto_commit(self):
|
| 844 |
+
context = self.get_context_from_history(self.cur_messages)
|
| 845 |
+
res = self.repo.commit(context=context, prefix="aider: ")
|
| 846 |
+
if res:
|
| 847 |
+
commit_hash, commit_message = res
|
| 848 |
+
self.last_aider_commit_hash = commit_hash
|
| 849 |
+
|
| 850 |
+
return self.gpt_prompts.files_content_gpt_edits.format(
|
| 851 |
+
hash=commit_hash,
|
| 852 |
+
message=commit_message,
|
| 853 |
+
)
|
| 854 |
+
|
| 855 |
+
self.io.tool_output("No changes made to git tracked files.")
|
| 856 |
+
return self.gpt_prompts.files_content_gpt_no_edits
|
| 857 |
+
|
| 858 |
+
def should_dirty_commit(self, inp):
|
| 859 |
+
cmds = self.commands.matching_commands(inp)
|
| 860 |
+
if cmds:
|
| 861 |
+
matching_commands, _, _ = cmds
|
| 862 |
+
if len(matching_commands) == 1:
|
| 863 |
+
cmd = matching_commands[0][1:]
|
| 864 |
+
if cmd in "add clear commit diff drop exit help ls tokens".split():
|
| 865 |
+
return
|
| 866 |
+
|
| 867 |
+
if self.last_asked_for_commit_time >= self.get_last_modified():
|
| 868 |
+
return
|
| 869 |
+
return True
|
| 870 |
+
|
| 871 |
+
def dirty_commit(self):
|
| 872 |
+
if not self.dirty_commits:
|
| 873 |
+
return
|
| 874 |
+
if not self.repo:
|
| 875 |
+
return
|
| 876 |
+
if not self.repo.is_dirty():
|
| 877 |
+
return
|
| 878 |
+
|
| 879 |
+
self.io.tool_output("Git repo has uncommitted changes.")
|
| 880 |
+
self.repo.show_diffs(self.pretty)
|
| 881 |
+
self.last_asked_for_commit_time = self.get_last_modified()
|
| 882 |
+
res = self.io.prompt_ask(
|
| 883 |
+
"Commit before the chat proceeds [y/n/commit message]?",
|
| 884 |
+
default="y",
|
| 885 |
+
).strip()
|
| 886 |
+
if res.lower() in ["n", "no"]:
|
| 887 |
+
self.io.tool_error("Skipped commmit.")
|
| 888 |
+
return
|
| 889 |
+
if res.lower() in ["y", "yes"]:
|
| 890 |
+
message = None
|
| 891 |
+
else:
|
| 892 |
+
message = res.strip()
|
| 893 |
+
|
| 894 |
+
self.repo.commit(message=message)
|
| 895 |
+
|
| 896 |
+
# files changed, move cur messages back behind the files messages
|
| 897 |
+
self.move_back_cur_messages(self.gpt_prompts.files_content_local_edits)
|
| 898 |
+
return True
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
def check_model_availability(main_model):
|
| 902 |
+
available_models = openai.Model.list()
|
| 903 |
+
model_ids = [model.id for model in available_models["data"]]
|
| 904 |
+
return main_model.name in model_ids
|
testbed/Aider-AI__aider/aider/coders/base_prompts.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class CoderPrompts:
|
| 2 |
+
files_content_gpt_edits = "I committed the changes with git hash {hash} & commit msg: {message}"
|
| 3 |
+
|
| 4 |
+
files_content_gpt_edits_no_repo = "I updated the files."
|
| 5 |
+
|
| 6 |
+
files_content_gpt_no_edits = "I didn't see any properly formatted edits in your reply?!"
|
| 7 |
+
|
| 8 |
+
files_content_local_edits = "I edited the files myself."
|
testbed/Aider-AI__aider/aider/coders/editblock_coder.py
ADDED
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import re
|
| 3 |
+
from difflib import SequenceMatcher
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from ..dump import dump # noqa: F401
|
| 7 |
+
from .base_coder import Coder
|
| 8 |
+
from .editblock_prompts import EditBlockPrompts
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class EditBlockCoder(Coder):
|
| 12 |
+
def __init__(self, *args, **kwargs):
|
| 13 |
+
self.gpt_prompts = EditBlockPrompts()
|
| 14 |
+
super().__init__(*args, **kwargs)
|
| 15 |
+
|
| 16 |
+
def update_files(self):
|
| 17 |
+
content = self.partial_response_content
|
| 18 |
+
|
| 19 |
+
# might raise ValueError for malformed ORIG/UPD blocks
|
| 20 |
+
edits = list(find_original_update_blocks(content))
|
| 21 |
+
|
| 22 |
+
edited = set()
|
| 23 |
+
for path, original, updated in edits:
|
| 24 |
+
full_path = self.allowed_to_edit(path)
|
| 25 |
+
if not full_path:
|
| 26 |
+
continue
|
| 27 |
+
content = self.io.read_text(full_path)
|
| 28 |
+
content = do_replace(full_path, content, original, updated)
|
| 29 |
+
if content:
|
| 30 |
+
self.io.write_text(full_path, content)
|
| 31 |
+
edited.add(path)
|
| 32 |
+
continue
|
| 33 |
+
raise ValueError(f"""InvalidEditBlock: edit failed!
|
| 34 |
+
|
| 35 |
+
{path} does not contain the *exact sequence* of HEAD lines you specified.
|
| 36 |
+
Try again.
|
| 37 |
+
DO NOT skip blank lines, comments, docstrings, etc!
|
| 38 |
+
The HEAD block needs to be EXACTLY the same as the lines in {path} with nothing missing!
|
| 39 |
+
|
| 40 |
+
{path} does not contain these {len(original.splitlines())} exact lines in a row:
|
| 41 |
+
```
|
| 42 |
+
{original}```
|
| 43 |
+
""")
|
| 44 |
+
|
| 45 |
+
return edited
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def prep(content):
|
| 49 |
+
if content and not content.endswith("\n"):
|
| 50 |
+
content += "\n"
|
| 51 |
+
lines = content.splitlines(keepends=True)
|
| 52 |
+
return content, lines
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def perfect_or_whitespace(whole_lines, part_lines, replace_lines):
|
| 56 |
+
# Try for a perfect match
|
| 57 |
+
res = perfect_replace(whole_lines, part_lines, replace_lines)
|
| 58 |
+
if res:
|
| 59 |
+
return res
|
| 60 |
+
|
| 61 |
+
# Try being flexible about leading whitespace
|
| 62 |
+
res = replace_part_with_missing_leading_whitespace(whole_lines, part_lines, replace_lines)
|
| 63 |
+
if res:
|
| 64 |
+
return res
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def perfect_replace(whole_lines, part_lines, replace_lines):
|
| 68 |
+
part_tup = tuple(part_lines)
|
| 69 |
+
part_len = len(part_lines)
|
| 70 |
+
|
| 71 |
+
for i in range(len(whole_lines) - part_len + 1):
|
| 72 |
+
whole_tup = tuple(whole_lines[i : i + part_len])
|
| 73 |
+
if part_tup == whole_tup:
|
| 74 |
+
res = whole_lines[:i] + replace_lines + whole_lines[i + part_len :]
|
| 75 |
+
return "".join(res)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def replace_most_similar_chunk(whole, part, replace):
|
| 79 |
+
"""Best efforts to find the `part` lines in `whole` and replace them with `replace`"""
|
| 80 |
+
|
| 81 |
+
whole, whole_lines = prep(whole)
|
| 82 |
+
part, part_lines = prep(part)
|
| 83 |
+
replace, replace_lines = prep(replace)
|
| 84 |
+
|
| 85 |
+
res = perfect_or_whitespace(whole_lines, part_lines, replace_lines)
|
| 86 |
+
if res:
|
| 87 |
+
return res
|
| 88 |
+
|
| 89 |
+
# drop leading empty line, GPT sometimes adds them spuriously (issue #25)
|
| 90 |
+
if len(part_lines) > 2 and not part_lines[0].strip():
|
| 91 |
+
skip_blank_line_part_lines = part_lines[1:]
|
| 92 |
+
res = perfect_or_whitespace(whole_lines, skip_blank_line_part_lines, replace_lines)
|
| 93 |
+
if res:
|
| 94 |
+
return res
|
| 95 |
+
|
| 96 |
+
# Try to handle when it elides code with ...
|
| 97 |
+
try:
|
| 98 |
+
res = try_dotdotdots(whole, part, replace)
|
| 99 |
+
if res:
|
| 100 |
+
return res
|
| 101 |
+
except ValueError:
|
| 102 |
+
pass
|
| 103 |
+
|
| 104 |
+
return
|
| 105 |
+
# Try fuzzy matching
|
| 106 |
+
res = replace_closest_edit_distance(whole_lines, part, part_lines, replace_lines)
|
| 107 |
+
if res:
|
| 108 |
+
return res
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def try_dotdotdots(whole, part, replace):
|
| 112 |
+
"""
|
| 113 |
+
See if the edit block has ... lines.
|
| 114 |
+
If not, return none.
|
| 115 |
+
|
| 116 |
+
If yes, try and do a perfect edit with the ... chunks.
|
| 117 |
+
If there's a mismatch or otherwise imperfect edit, raise ValueError.
|
| 118 |
+
|
| 119 |
+
If perfect edit succeeds, return the updated whole.
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
dots_re = re.compile(r"(^\s*\.\.\.\n)", re.MULTILINE | re.DOTALL)
|
| 123 |
+
|
| 124 |
+
part_pieces = re.split(dots_re, part)
|
| 125 |
+
replace_pieces = re.split(dots_re, replace)
|
| 126 |
+
|
| 127 |
+
if len(part_pieces) != len(replace_pieces):
|
| 128 |
+
raise ValueError("Unpaired ... in edit block")
|
| 129 |
+
|
| 130 |
+
if len(part_pieces) == 1:
|
| 131 |
+
# no dots in this edit block, just return None
|
| 132 |
+
return
|
| 133 |
+
|
| 134 |
+
# Compare odd strings in part_pieces and replace_pieces
|
| 135 |
+
all_dots_match = all(part_pieces[i] == replace_pieces[i] for i in range(1, len(part_pieces), 2))
|
| 136 |
+
|
| 137 |
+
if not all_dots_match:
|
| 138 |
+
raise ValueError("Unmatched ... in edit block")
|
| 139 |
+
|
| 140 |
+
part_pieces = [part_pieces[i] for i in range(0, len(part_pieces), 2)]
|
| 141 |
+
replace_pieces = [replace_pieces[i] for i in range(0, len(replace_pieces), 2)]
|
| 142 |
+
|
| 143 |
+
pairs = zip(part_pieces, replace_pieces)
|
| 144 |
+
for part, replace in pairs:
|
| 145 |
+
if not part and not replace:
|
| 146 |
+
continue
|
| 147 |
+
|
| 148 |
+
if not part and replace:
|
| 149 |
+
if not whole.endswith("\n"):
|
| 150 |
+
whole += "\n"
|
| 151 |
+
whole += replace
|
| 152 |
+
continue
|
| 153 |
+
|
| 154 |
+
if whole.count(part) != 1:
|
| 155 |
+
raise ValueError(
|
| 156 |
+
"No perfect matching chunk in edit block with ... or part appears more than once"
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
whole = whole.replace(part, replace, 1)
|
| 160 |
+
|
| 161 |
+
return whole
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def replace_part_with_missing_leading_whitespace(whole_lines, part_lines, replace_lines):
|
| 165 |
+
# GPT often messes up leading whitespace.
|
| 166 |
+
# It usually does it uniformly across the ORIG and UPD blocks.
|
| 167 |
+
# Either omitting all leading whitespace, or including only some of it.
|
| 168 |
+
|
| 169 |
+
# Outdent everything in part_lines and replace_lines by the max fixed amount possible
|
| 170 |
+
leading = [len(p) - len(p.lstrip()) for p in part_lines if p.strip()] + [
|
| 171 |
+
len(p) - len(p.lstrip()) for p in replace_lines if p.strip()
|
| 172 |
+
]
|
| 173 |
+
|
| 174 |
+
if leading and min(leading):
|
| 175 |
+
num_leading = min(leading)
|
| 176 |
+
part_lines = [p[num_leading:] if p.strip() else p for p in part_lines]
|
| 177 |
+
replace_lines = [p[num_leading:] if p.strip() else p for p in replace_lines]
|
| 178 |
+
|
| 179 |
+
# can we find an exact match not including the leading whitespace
|
| 180 |
+
num_part_lines = len(part_lines)
|
| 181 |
+
|
| 182 |
+
for i in range(len(whole_lines) - num_part_lines + 1):
|
| 183 |
+
add_leading = match_but_for_leading_whitespace(
|
| 184 |
+
whole_lines[i : i + num_part_lines], part_lines
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
if add_leading is None:
|
| 188 |
+
continue
|
| 189 |
+
|
| 190 |
+
replace_lines = [add_leading + rline if rline.strip() else rline for rline in replace_lines]
|
| 191 |
+
whole_lines = whole_lines[:i] + replace_lines + whole_lines[i + num_part_lines :]
|
| 192 |
+
return "".join(whole_lines)
|
| 193 |
+
|
| 194 |
+
return None
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def match_but_for_leading_whitespace(whole_lines, part_lines):
|
| 198 |
+
num = len(whole_lines)
|
| 199 |
+
|
| 200 |
+
# does the non-whitespace all agree?
|
| 201 |
+
if not all(whole_lines[i].lstrip() == part_lines[i].lstrip() for i in range(num)):
|
| 202 |
+
return
|
| 203 |
+
|
| 204 |
+
# are they all offset the same?
|
| 205 |
+
add = set(
|
| 206 |
+
whole_lines[i][: len(whole_lines[i]) - len(part_lines[i])]
|
| 207 |
+
for i in range(num)
|
| 208 |
+
if whole_lines[i].strip()
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
if len(add) != 1:
|
| 212 |
+
return
|
| 213 |
+
|
| 214 |
+
return add.pop()
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def replace_closest_edit_distance(whole_lines, part, part_lines, replace_lines):
|
| 218 |
+
similarity_thresh = 0.8
|
| 219 |
+
|
| 220 |
+
max_similarity = 0
|
| 221 |
+
most_similar_chunk_start = -1
|
| 222 |
+
most_similar_chunk_end = -1
|
| 223 |
+
|
| 224 |
+
scale = 0.1
|
| 225 |
+
min_len = math.floor(len(part_lines) * (1 - scale))
|
| 226 |
+
max_len = math.ceil(len(part_lines) * (1 + scale))
|
| 227 |
+
|
| 228 |
+
for length in range(min_len, max_len):
|
| 229 |
+
for i in range(len(whole_lines) - length + 1):
|
| 230 |
+
chunk = whole_lines[i : i + length]
|
| 231 |
+
chunk = "".join(chunk)
|
| 232 |
+
|
| 233 |
+
similarity = SequenceMatcher(None, chunk, part).ratio()
|
| 234 |
+
|
| 235 |
+
if similarity > max_similarity and similarity:
|
| 236 |
+
max_similarity = similarity
|
| 237 |
+
most_similar_chunk_start = i
|
| 238 |
+
most_similar_chunk_end = i + length
|
| 239 |
+
|
| 240 |
+
if max_similarity < similarity_thresh:
|
| 241 |
+
return
|
| 242 |
+
|
| 243 |
+
modified_whole = (
|
| 244 |
+
whole_lines[:most_similar_chunk_start]
|
| 245 |
+
+ replace_lines
|
| 246 |
+
+ whole_lines[most_similar_chunk_end:]
|
| 247 |
+
)
|
| 248 |
+
modified_whole = "".join(modified_whole)
|
| 249 |
+
|
| 250 |
+
return modified_whole
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def strip_quoted_wrapping(res, fname=None, fence=None):
|
| 254 |
+
"""
|
| 255 |
+
Given an input string which may have extra "wrapping" around it, remove the wrapping.
|
| 256 |
+
For example:
|
| 257 |
+
|
| 258 |
+
filename.ext
|
| 259 |
+
```
|
| 260 |
+
We just want this content
|
| 261 |
+
Not the filename and triple quotes
|
| 262 |
+
```
|
| 263 |
+
"""
|
| 264 |
+
if not res:
|
| 265 |
+
return res
|
| 266 |
+
|
| 267 |
+
if not fence:
|
| 268 |
+
fence = ("```", "```")
|
| 269 |
+
|
| 270 |
+
res = res.splitlines()
|
| 271 |
+
|
| 272 |
+
if fname and res[0].strip().endswith(Path(fname).name):
|
| 273 |
+
res = res[1:]
|
| 274 |
+
|
| 275 |
+
if res[0].startswith(fence[0]) and res[-1].startswith(fence[1]):
|
| 276 |
+
res = res[1:-1]
|
| 277 |
+
|
| 278 |
+
res = "\n".join(res)
|
| 279 |
+
if res and res[-1] != "\n":
|
| 280 |
+
res += "\n"
|
| 281 |
+
|
| 282 |
+
return res
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def do_replace(fname, content, before_text, after_text, fence=None):
|
| 286 |
+
before_text = strip_quoted_wrapping(before_text, fname, fence)
|
| 287 |
+
after_text = strip_quoted_wrapping(after_text, fname, fence)
|
| 288 |
+
fname = Path(fname)
|
| 289 |
+
|
| 290 |
+
# does it want to make a new file?
|
| 291 |
+
if not fname.exists() and not before_text.strip():
|
| 292 |
+
fname.touch()
|
| 293 |
+
content = ""
|
| 294 |
+
|
| 295 |
+
if content is None:
|
| 296 |
+
return
|
| 297 |
+
|
| 298 |
+
if not before_text.strip():
|
| 299 |
+
# append to existing file, or start a new file
|
| 300 |
+
new_content = content + after_text
|
| 301 |
+
else:
|
| 302 |
+
new_content = replace_most_similar_chunk(content, before_text, after_text)
|
| 303 |
+
|
| 304 |
+
return new_content
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
HEAD = "<<<<<<< HEAD"
|
| 308 |
+
DIVIDER = "======="
|
| 309 |
+
UPDATED = ">>>>>>> updated"
|
| 310 |
+
|
| 311 |
+
separators = "|".join([HEAD, DIVIDER, UPDATED])
|
| 312 |
+
|
| 313 |
+
split_re = re.compile(r"^((?:" + separators + r")[ ]*\n)", re.MULTILINE | re.DOTALL)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def find_original_update_blocks(content):
|
| 317 |
+
# make sure we end with a newline, otherwise the regex will miss <<UPD on the last line
|
| 318 |
+
if not content.endswith("\n"):
|
| 319 |
+
content = content + "\n"
|
| 320 |
+
|
| 321 |
+
pieces = re.split(split_re, content)
|
| 322 |
+
|
| 323 |
+
pieces.reverse()
|
| 324 |
+
processed = []
|
| 325 |
+
|
| 326 |
+
# Keep using the same filename in cases where GPT produces an edit block
|
| 327 |
+
# without a filename.
|
| 328 |
+
current_filename = None
|
| 329 |
+
try:
|
| 330 |
+
while pieces:
|
| 331 |
+
cur = pieces.pop()
|
| 332 |
+
|
| 333 |
+
if cur in (DIVIDER, UPDATED):
|
| 334 |
+
processed.append(cur)
|
| 335 |
+
raise ValueError(f"Unexpected {cur}")
|
| 336 |
+
|
| 337 |
+
if cur.strip() != HEAD:
|
| 338 |
+
processed.append(cur)
|
| 339 |
+
continue
|
| 340 |
+
|
| 341 |
+
processed.append(cur) # original_marker
|
| 342 |
+
|
| 343 |
+
filename = processed[-2].splitlines()[-1].strip()
|
| 344 |
+
try:
|
| 345 |
+
if not len(filename) or "`" in filename:
|
| 346 |
+
filename = processed[-2].splitlines()[-2].strip()
|
| 347 |
+
if not len(filename) or "`" in filename:
|
| 348 |
+
if current_filename:
|
| 349 |
+
filename = current_filename
|
| 350 |
+
else:
|
| 351 |
+
raise ValueError(
|
| 352 |
+
f"Bad/missing filename. It should go right above the {HEAD}"
|
| 353 |
+
)
|
| 354 |
+
except IndexError:
|
| 355 |
+
if current_filename:
|
| 356 |
+
filename = current_filename
|
| 357 |
+
else:
|
| 358 |
+
raise ValueError(f"Bad/missing filename. It should go right above the {HEAD}")
|
| 359 |
+
|
| 360 |
+
current_filename = filename
|
| 361 |
+
|
| 362 |
+
original_text = pieces.pop()
|
| 363 |
+
processed.append(original_text)
|
| 364 |
+
|
| 365 |
+
divider_marker = pieces.pop()
|
| 366 |
+
processed.append(divider_marker)
|
| 367 |
+
if divider_marker.strip() != DIVIDER:
|
| 368 |
+
raise ValueError(f"Expected `{DIVIDER}` not {divider_marker.strip()}")
|
| 369 |
+
|
| 370 |
+
updated_text = pieces.pop()
|
| 371 |
+
processed.append(updated_text)
|
| 372 |
+
|
| 373 |
+
updated_marker = pieces.pop()
|
| 374 |
+
processed.append(updated_marker)
|
| 375 |
+
if updated_marker.strip() != UPDATED:
|
| 376 |
+
raise ValueError(f"Expected `{UPDATED}` not `{updated_marker.strip()}")
|
| 377 |
+
|
| 378 |
+
yield filename, original_text, updated_text
|
| 379 |
+
except ValueError as e:
|
| 380 |
+
processed = "".join(processed)
|
| 381 |
+
err = e.args[0]
|
| 382 |
+
raise ValueError(f"{processed}\n^^^ {err}")
|
| 383 |
+
except IndexError:
|
| 384 |
+
processed = "".join(processed)
|
| 385 |
+
raise ValueError(f"{processed}\n^^^ Incomplete HEAD/updated block.")
|
| 386 |
+
except Exception:
|
| 387 |
+
processed = "".join(processed)
|
| 388 |
+
raise ValueError(f"{processed}\n^^^ Error parsing HEAD/updated block.")
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
if __name__ == "__main__":
|
| 392 |
+
edit = """
|
| 393 |
+
Here's the change:
|
| 394 |
+
|
| 395 |
+
```text
|
| 396 |
+
foo.txt
|
| 397 |
+
<<<<<<< HEAD
|
| 398 |
+
Two
|
| 399 |
+
=======
|
| 400 |
+
Tooooo
|
| 401 |
+
>>>>>>> updated
|
| 402 |
+
```
|
| 403 |
+
|
| 404 |
+
Hope you like it!
|
| 405 |
+
"""
|
| 406 |
+
print(list(find_original_update_blocks(edit)))
|
testbed/Aider-AI__aider/aider/coders/editblock_func_coder.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
from ..dump import dump # noqa: F401
|
| 4 |
+
from .base_coder import Coder
|
| 5 |
+
from .editblock_coder import do_replace
|
| 6 |
+
from .editblock_func_prompts import EditBlockFunctionPrompts
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class EditBlockFunctionCoder(Coder):
|
| 10 |
+
functions = [
|
| 11 |
+
dict(
|
| 12 |
+
name="replace_lines",
|
| 13 |
+
description="create or update one or more files",
|
| 14 |
+
parameters=dict(
|
| 15 |
+
type="object",
|
| 16 |
+
required=["explanation", "edits"],
|
| 17 |
+
properties=dict(
|
| 18 |
+
explanation=dict(
|
| 19 |
+
type="string",
|
| 20 |
+
description=(
|
| 21 |
+
"Step by step plan for the changes to be made to the code (future"
|
| 22 |
+
" tense, markdown format)"
|
| 23 |
+
),
|
| 24 |
+
),
|
| 25 |
+
edits=dict(
|
| 26 |
+
type="array",
|
| 27 |
+
items=dict(
|
| 28 |
+
type="object",
|
| 29 |
+
required=["path", "original_lines", "updated_lines"],
|
| 30 |
+
properties=dict(
|
| 31 |
+
path=dict(
|
| 32 |
+
type="string",
|
| 33 |
+
description="Path of file to edit",
|
| 34 |
+
),
|
| 35 |
+
original_lines=dict(
|
| 36 |
+
type="array",
|
| 37 |
+
items=dict(
|
| 38 |
+
type="string",
|
| 39 |
+
),
|
| 40 |
+
description=(
|
| 41 |
+
"A unique stretch of lines from the original file,"
|
| 42 |
+
" including all whitespace, without skipping any lines"
|
| 43 |
+
),
|
| 44 |
+
),
|
| 45 |
+
updated_lines=dict(
|
| 46 |
+
type="array",
|
| 47 |
+
items=dict(
|
| 48 |
+
type="string",
|
| 49 |
+
),
|
| 50 |
+
description="New content to replace the `original_lines` with",
|
| 51 |
+
),
|
| 52 |
+
),
|
| 53 |
+
),
|
| 54 |
+
),
|
| 55 |
+
),
|
| 56 |
+
),
|
| 57 |
+
),
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
def __init__(self, code_format, *args, **kwargs):
|
| 61 |
+
self.code_format = code_format
|
| 62 |
+
|
| 63 |
+
if code_format == "string":
|
| 64 |
+
original_lines = dict(
|
| 65 |
+
type="string",
|
| 66 |
+
description=(
|
| 67 |
+
"A unique stretch of lines from the original file, including all"
|
| 68 |
+
" whitespace and newlines, without skipping any lines"
|
| 69 |
+
),
|
| 70 |
+
)
|
| 71 |
+
updated_lines = dict(
|
| 72 |
+
type="string",
|
| 73 |
+
description="New content to replace the `original_lines` with",
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
self.functions[0]["parameters"]["properties"]["edits"]["items"]["properties"][
|
| 77 |
+
"original_lines"
|
| 78 |
+
] = original_lines
|
| 79 |
+
self.functions[0]["parameters"]["properties"]["edits"]["items"]["properties"][
|
| 80 |
+
"updated_lines"
|
| 81 |
+
] = updated_lines
|
| 82 |
+
|
| 83 |
+
self.gpt_prompts = EditBlockFunctionPrompts()
|
| 84 |
+
super().__init__(*args, **kwargs)
|
| 85 |
+
|
| 86 |
+
def render_incremental_response(self, final=False):
|
| 87 |
+
if self.partial_response_content:
|
| 88 |
+
return self.partial_response_content
|
| 89 |
+
|
| 90 |
+
args = self.parse_partial_args()
|
| 91 |
+
res = json.dumps(args, indent=4)
|
| 92 |
+
return res
|
| 93 |
+
|
| 94 |
+
def update_files(self):
|
| 95 |
+
name = self.partial_response_function_call.get("name")
|
| 96 |
+
|
| 97 |
+
if name and name != "replace_lines":
|
| 98 |
+
raise ValueError(f'Unknown function_call name="{name}", use name="replace_lines"')
|
| 99 |
+
|
| 100 |
+
args = self.parse_partial_args()
|
| 101 |
+
if not args:
|
| 102 |
+
return
|
| 103 |
+
|
| 104 |
+
edits = args.get("edits", [])
|
| 105 |
+
|
| 106 |
+
edited = set()
|
| 107 |
+
for edit in edits:
|
| 108 |
+
path = get_arg(edit, "path")
|
| 109 |
+
original = get_arg(edit, "original_lines")
|
| 110 |
+
updated = get_arg(edit, "updated_lines")
|
| 111 |
+
|
| 112 |
+
# gpt-3.5 returns lists even when instructed to return a string!
|
| 113 |
+
if self.code_format == "list" or type(original) == list:
|
| 114 |
+
original = "\n".join(original)
|
| 115 |
+
if self.code_format == "list" or type(updated) == list:
|
| 116 |
+
updated = "\n".join(updated)
|
| 117 |
+
|
| 118 |
+
if original and not original.endswith("\n"):
|
| 119 |
+
original += "\n"
|
| 120 |
+
if updated and not updated.endswith("\n"):
|
| 121 |
+
updated += "\n"
|
| 122 |
+
|
| 123 |
+
full_path = self.allowed_to_edit(path)
|
| 124 |
+
if not full_path:
|
| 125 |
+
continue
|
| 126 |
+
content = self.io.read_text(full_path)
|
| 127 |
+
content = do_replace(full_path, content, original, updated)
|
| 128 |
+
if content:
|
| 129 |
+
self.io.write_text(full_path, content)
|
| 130 |
+
edited.add(path)
|
| 131 |
+
continue
|
| 132 |
+
self.io.tool_error(f"Failed to apply edit to {path}")
|
| 133 |
+
|
| 134 |
+
return edited
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def get_arg(edit, arg):
|
| 138 |
+
if arg not in edit:
|
| 139 |
+
raise ValueError(f"Missing `{arg}` parameter: {edit}")
|
| 140 |
+
return edit[arg]
|
testbed/Aider-AI__aider/aider/coders/editblock_func_prompts.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa: E501
|
| 2 |
+
|
| 3 |
+
from .base_prompts import CoderPrompts
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class EditBlockFunctionPrompts(CoderPrompts):
|
| 7 |
+
main_system = """Act as an expert software developer.
|
| 8 |
+
Take requests for changes to the supplied code.
|
| 9 |
+
If the request is ambiguous, ask questions.
|
| 10 |
+
|
| 11 |
+
Once you understand the request you MUST use the `replace_lines` function to edit the files to make the needed changes.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
system_reminder = """
|
| 15 |
+
ONLY return code using the `replace_lines` function.
|
| 16 |
+
NEVER return code outside the `replace_lines` function.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
files_content_prefix = "Here is the current content of the files:\n"
|
| 20 |
+
files_no_full_files = "I am not sharing any files yet."
|
| 21 |
+
|
| 22 |
+
redacted_edit_message = "No changes are needed."
|
| 23 |
+
|
| 24 |
+
repo_content_prefix = (
|
| 25 |
+
"Below here are summaries of other files! Do not propose changes to these *read-only*"
|
| 26 |
+
" files without asking me first.\n"
|
| 27 |
+
)
|
testbed/Aider-AI__aider/aider/coders/editblock_prompts.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa: E501
|
| 2 |
+
|
| 3 |
+
from .base_prompts import CoderPrompts
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class EditBlockPrompts(CoderPrompts):
|
| 7 |
+
main_system = """Act as an expert software developer.
|
| 8 |
+
Always use best practices when coding.
|
| 9 |
+
When you edit or add code, respect and use existing conventions, libraries, etc.
|
| 10 |
+
|
| 11 |
+
Take requests for changes to the supplied code.
|
| 12 |
+
If the request is ambiguous, ask questions.
|
| 13 |
+
|
| 14 |
+
Once you understand the request you MUST:
|
| 15 |
+
1. List the files you need to modify. *NEVER* suggest changes to a *read-only* file. Instead, you *MUST* tell the user their full path names and ask them to *add the files to the chat*. End your reply and wait for their approval.
|
| 16 |
+
2. Think step-by-step and explain the needed changes.
|
| 17 |
+
3. Describe each change with an *edit block* per the example below.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
system_reminder = """You MUST format EVERY code change with an *edit block* like this:
|
| 21 |
+
|
| 22 |
+
{fence[0]}python
|
| 23 |
+
some/dir/example.py
|
| 24 |
+
<<<<<<< HEAD
|
| 25 |
+
# some comment
|
| 26 |
+
# Func to multiply
|
| 27 |
+
def mul(a,b)
|
| 28 |
+
=======
|
| 29 |
+
# updated comment
|
| 30 |
+
# Function to add
|
| 31 |
+
def add(a,b):
|
| 32 |
+
>>>>>>> updated
|
| 33 |
+
{fence[1]}
|
| 34 |
+
|
| 35 |
+
A program will parse the edit blocks you generate and replace the `HEAD` lines with the `updated` lines.
|
| 36 |
+
So edit blocks must be precise and unambiguous!
|
| 37 |
+
|
| 38 |
+
Every *edit block* must be fenced with {fence[0]}...{fence[1]} with the correct code language.
|
| 39 |
+
Every *edit block* must start with the full path! *NEVER* propose edit blocks for *read-only* files.
|
| 40 |
+
|
| 41 |
+
The `HEAD` section must be an *exact set of sequential lines* from the file!
|
| 42 |
+
NEVER SKIP LINES in the `HEAD` section!
|
| 43 |
+
NEVER ELIDE LINES AND REPLACE THEM WITH A COMMENT!
|
| 44 |
+
NEVER OMIT ANY WHITESPACE in the `HEAD` section!
|
| 45 |
+
|
| 46 |
+
Edits to different parts of a file each need their own *edit block*.
|
| 47 |
+
|
| 48 |
+
If you want to put code in a new file, use an edit block with:
|
| 49 |
+
- A new file path, including dir name if needed
|
| 50 |
+
- An empty `HEAD` section
|
| 51 |
+
- The new file's contents in the `updated` section
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
files_content_prefix = "These are the *read-write* files:\n"
|
| 55 |
+
|
| 56 |
+
files_no_full_files = "I am not sharing any *read-write* files yet."
|
| 57 |
+
|
| 58 |
+
repo_content_prefix = """Below here are summaries of other files!
|
| 59 |
+
Do not propose changes to these files, they are *read-only*.
|
| 60 |
+
To make a file *read-write*, ask me to *add it to the chat*.
|
| 61 |
+
"""
|
testbed/Aider-AI__aider/aider/coders/single_wholefile_func_coder.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from aider import diffs
|
| 2 |
+
|
| 3 |
+
from ..dump import dump # noqa: F401
|
| 4 |
+
from .base_coder import Coder
|
| 5 |
+
from .single_wholefile_func_prompts import SingleWholeFileFunctionPrompts
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class SingleWholeFileFunctionCoder(Coder):
|
| 9 |
+
functions = [
|
| 10 |
+
dict(
|
| 11 |
+
name="write_file",
|
| 12 |
+
description="write new content into the file",
|
| 13 |
+
parameters=dict(
|
| 14 |
+
type="object",
|
| 15 |
+
required=["explanation", "content"],
|
| 16 |
+
properties=dict(
|
| 17 |
+
explanation=dict(
|
| 18 |
+
type="string",
|
| 19 |
+
description=(
|
| 20 |
+
"Step by step plan for the changes to be made to the code (future"
|
| 21 |
+
" tense, markdown format)"
|
| 22 |
+
),
|
| 23 |
+
),
|
| 24 |
+
content=dict(
|
| 25 |
+
type="string",
|
| 26 |
+
description="Content to write to the file",
|
| 27 |
+
),
|
| 28 |
+
),
|
| 29 |
+
),
|
| 30 |
+
),
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
def __init__(self, *args, **kwargs):
|
| 34 |
+
self.gpt_prompts = SingleWholeFileFunctionPrompts()
|
| 35 |
+
super().__init__(*args, **kwargs)
|
| 36 |
+
|
| 37 |
+
def update_cur_messages(self, edited):
|
| 38 |
+
if edited:
|
| 39 |
+
self.cur_messages += [
|
| 40 |
+
dict(role="assistant", content=self.gpt_prompts.redacted_edit_message)
|
| 41 |
+
]
|
| 42 |
+
else:
|
| 43 |
+
self.cur_messages += [dict(role="assistant", content=self.partial_response_content)]
|
| 44 |
+
|
| 45 |
+
def render_incremental_response(self, final=False):
|
| 46 |
+
if self.partial_response_content:
|
| 47 |
+
return self.partial_response_content
|
| 48 |
+
|
| 49 |
+
args = self.parse_partial_args()
|
| 50 |
+
|
| 51 |
+
return str(args)
|
| 52 |
+
|
| 53 |
+
if not args:
|
| 54 |
+
return
|
| 55 |
+
|
| 56 |
+
explanation = args.get("explanation")
|
| 57 |
+
files = args.get("files", [])
|
| 58 |
+
|
| 59 |
+
res = ""
|
| 60 |
+
if explanation:
|
| 61 |
+
res += f"{explanation}\n\n"
|
| 62 |
+
|
| 63 |
+
for i, file_upd in enumerate(files):
|
| 64 |
+
path = file_upd.get("path")
|
| 65 |
+
if not path:
|
| 66 |
+
continue
|
| 67 |
+
content = file_upd.get("content")
|
| 68 |
+
if not content:
|
| 69 |
+
continue
|
| 70 |
+
|
| 71 |
+
this_final = (i < len(files) - 1) or final
|
| 72 |
+
res += self.live_diffs(path, content, this_final)
|
| 73 |
+
|
| 74 |
+
return res
|
| 75 |
+
|
| 76 |
+
def live_diffs(self, fname, content, final):
|
| 77 |
+
lines = content.splitlines(keepends=True)
|
| 78 |
+
|
| 79 |
+
# ending an existing block
|
| 80 |
+
full_path = self.abs_root_path(fname)
|
| 81 |
+
|
| 82 |
+
content = self.io.read_text(full_path)
|
| 83 |
+
if content is None:
|
| 84 |
+
orig_lines = []
|
| 85 |
+
else:
|
| 86 |
+
orig_lines = content.splitlines()
|
| 87 |
+
|
| 88 |
+
show_diff = diffs.diff_partial_update(
|
| 89 |
+
orig_lines,
|
| 90 |
+
lines,
|
| 91 |
+
final,
|
| 92 |
+
fname=fname,
|
| 93 |
+
).splitlines()
|
| 94 |
+
|
| 95 |
+
return "\n".join(show_diff)
|
| 96 |
+
|
| 97 |
+
def update_files(self):
|
| 98 |
+
name = self.partial_response_function_call.get("name")
|
| 99 |
+
if name and name != "write_file":
|
| 100 |
+
raise ValueError(f'Unknown function_call name="{name}", use name="write_file"')
|
| 101 |
+
|
| 102 |
+
args = self.parse_partial_args()
|
| 103 |
+
if not args:
|
| 104 |
+
return
|
| 105 |
+
|
| 106 |
+
content = args["content"]
|
| 107 |
+
path = self.get_inchat_relative_files()[0]
|
| 108 |
+
if self.allowed_to_edit(path, content):
|
| 109 |
+
return set([path])
|
| 110 |
+
|
| 111 |
+
return set()
|
testbed/Aider-AI__aider/aider/coders/single_wholefile_func_prompts.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa: E501
|
| 2 |
+
|
| 3 |
+
from .base_prompts import CoderPrompts
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class SingleWholeFileFunctionPrompts(CoderPrompts):
|
| 7 |
+
main_system = """Act as an expert software developer.
|
| 8 |
+
Take requests for changes to the supplied code.
|
| 9 |
+
If the request is ambiguous, ask questions.
|
| 10 |
+
|
| 11 |
+
Once you understand the request you MUST use the `write_file` function to update the file to make the changes.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
system_reminder = """
|
| 15 |
+
ONLY return code using the `write_file` function.
|
| 16 |
+
NEVER return code outside the `write_file` function.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
files_content_prefix = "Here is the current content of the file:\n"
|
| 20 |
+
files_no_full_files = "I am not sharing any files yet."
|
| 21 |
+
|
| 22 |
+
redacted_edit_message = "No changes are needed."
|
| 23 |
+
|
| 24 |
+
# TODO: should this be present for using this with gpt-4?
|
| 25 |
+
repo_content_prefix = None
|
| 26 |
+
|
| 27 |
+
# TODO: fix the chat history, except we can't keep the whole file
|
testbed/Aider-AI__aider/aider/coders/wholefile_coder.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
from aider import diffs
|
| 4 |
+
|
| 5 |
+
from ..dump import dump # noqa: F401
|
| 6 |
+
from .base_coder import Coder
|
| 7 |
+
from .wholefile_prompts import WholeFilePrompts
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class WholeFileCoder(Coder):
|
| 11 |
+
def __init__(self, *args, **kwargs):
|
| 12 |
+
self.gpt_prompts = WholeFilePrompts()
|
| 13 |
+
super().__init__(*args, **kwargs)
|
| 14 |
+
|
| 15 |
+
def update_cur_messages(self, edited):
|
| 16 |
+
if edited:
|
| 17 |
+
self.cur_messages += [
|
| 18 |
+
dict(role="assistant", content=self.gpt_prompts.redacted_edit_message)
|
| 19 |
+
]
|
| 20 |
+
else:
|
| 21 |
+
self.cur_messages += [dict(role="assistant", content=self.partial_response_content)]
|
| 22 |
+
|
| 23 |
+
def render_incremental_response(self, final):
|
| 24 |
+
try:
|
| 25 |
+
return self.update_files(mode="diff")
|
| 26 |
+
except ValueError:
|
| 27 |
+
return self.partial_response_content
|
| 28 |
+
|
| 29 |
+
def update_files(self, mode="update"):
|
| 30 |
+
content = self.partial_response_content
|
| 31 |
+
|
| 32 |
+
chat_files = self.get_inchat_relative_files()
|
| 33 |
+
|
| 34 |
+
output = []
|
| 35 |
+
lines = content.splitlines(keepends=True)
|
| 36 |
+
|
| 37 |
+
edits = []
|
| 38 |
+
|
| 39 |
+
saw_fname = None
|
| 40 |
+
fname = None
|
| 41 |
+
fname_source = None
|
| 42 |
+
new_lines = []
|
| 43 |
+
for i, line in enumerate(lines):
|
| 44 |
+
if line.startswith(self.fence[0]) or line.startswith(self.fence[1]):
|
| 45 |
+
if fname is not None:
|
| 46 |
+
# ending an existing block
|
| 47 |
+
saw_fname = None
|
| 48 |
+
|
| 49 |
+
full_path = (Path(self.root) / fname).absolute()
|
| 50 |
+
|
| 51 |
+
if mode == "diff":
|
| 52 |
+
output += self.do_live_diff(full_path, new_lines, True)
|
| 53 |
+
else:
|
| 54 |
+
edits.append((fname, fname_source, new_lines))
|
| 55 |
+
|
| 56 |
+
fname = None
|
| 57 |
+
fname_source = None
|
| 58 |
+
new_lines = []
|
| 59 |
+
continue
|
| 60 |
+
|
| 61 |
+
# fname==None ... starting a new block
|
| 62 |
+
if i > 0:
|
| 63 |
+
fname_source = "block"
|
| 64 |
+
fname = lines[i - 1].strip()
|
| 65 |
+
fname = fname.strip("*") # handle **filename.py**
|
| 66 |
+
|
| 67 |
+
# Did gpt prepend a bogus dir? It especially likes to
|
| 68 |
+
# include the path/to prefix from the one-shot example in
|
| 69 |
+
# the prompt.
|
| 70 |
+
if fname and fname not in chat_files and Path(fname).name in chat_files:
|
| 71 |
+
fname = Path(fname).name
|
| 72 |
+
if not fname: # blank line? or ``` was on first line i==0
|
| 73 |
+
if saw_fname:
|
| 74 |
+
fname = saw_fname
|
| 75 |
+
fname_source = "saw"
|
| 76 |
+
elif len(chat_files) == 1:
|
| 77 |
+
fname = chat_files[0]
|
| 78 |
+
fname_source = "chat"
|
| 79 |
+
else:
|
| 80 |
+
# TODO: sense which file it is by diff size
|
| 81 |
+
raise ValueError(
|
| 82 |
+
f"No filename provided before {self.fence[0]} in file listing"
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
elif fname is not None:
|
| 86 |
+
new_lines.append(line)
|
| 87 |
+
else:
|
| 88 |
+
for word in line.strip().split():
|
| 89 |
+
word = word.rstrip(".:,;!")
|
| 90 |
+
for chat_file in chat_files:
|
| 91 |
+
quoted_chat_file = f"`{chat_file}`"
|
| 92 |
+
if word == quoted_chat_file:
|
| 93 |
+
saw_fname = chat_file
|
| 94 |
+
|
| 95 |
+
output.append(line)
|
| 96 |
+
|
| 97 |
+
if mode == "diff":
|
| 98 |
+
if fname is not None:
|
| 99 |
+
# ending an existing block
|
| 100 |
+
full_path = (Path(self.root) / fname).absolute()
|
| 101 |
+
output += self.do_live_diff(full_path, new_lines, False)
|
| 102 |
+
return "\n".join(output)
|
| 103 |
+
|
| 104 |
+
if fname:
|
| 105 |
+
edits.append((fname, fname_source, new_lines))
|
| 106 |
+
|
| 107 |
+
edited = set()
|
| 108 |
+
# process from most reliable filename, to least reliable
|
| 109 |
+
for source in ("block", "saw", "chat"):
|
| 110 |
+
for fname, fname_source, new_lines in edits:
|
| 111 |
+
if fname_source != source:
|
| 112 |
+
continue
|
| 113 |
+
# if a higher priority source already edited the file, skip
|
| 114 |
+
if fname in edited:
|
| 115 |
+
continue
|
| 116 |
+
|
| 117 |
+
# we have a winner
|
| 118 |
+
new_lines = "".join(new_lines)
|
| 119 |
+
if self.allowed_to_edit(fname, new_lines):
|
| 120 |
+
edited.add(fname)
|
| 121 |
+
|
| 122 |
+
return edited
|
| 123 |
+
|
| 124 |
+
def do_live_diff(self, full_path, new_lines, final):
|
| 125 |
+
if full_path.exists():
|
| 126 |
+
orig_lines = self.io.read_text(full_path).splitlines(keepends=True)
|
| 127 |
+
|
| 128 |
+
show_diff = diffs.diff_partial_update(
|
| 129 |
+
orig_lines,
|
| 130 |
+
new_lines,
|
| 131 |
+
final=final,
|
| 132 |
+
).splitlines()
|
| 133 |
+
output = show_diff
|
| 134 |
+
else:
|
| 135 |
+
output = ["```"] + new_lines + ["```"]
|
| 136 |
+
|
| 137 |
+
return output
|
testbed/Aider-AI__aider/aider/coders/wholefile_func_coder.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from aider import diffs
|
| 2 |
+
|
| 3 |
+
from ..dump import dump # noqa: F401
|
| 4 |
+
from .base_coder import Coder
|
| 5 |
+
from .wholefile_func_prompts import WholeFileFunctionPrompts
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class WholeFileFunctionCoder(Coder):
|
| 9 |
+
functions = [
|
| 10 |
+
dict(
|
| 11 |
+
name="write_file",
|
| 12 |
+
description="create or update one or more files",
|
| 13 |
+
parameters=dict(
|
| 14 |
+
type="object",
|
| 15 |
+
required=["explanation", "files"],
|
| 16 |
+
properties=dict(
|
| 17 |
+
explanation=dict(
|
| 18 |
+
type="string",
|
| 19 |
+
description=(
|
| 20 |
+
"Step by step plan for the changes to be made to the code (future"
|
| 21 |
+
" tense, markdown format)"
|
| 22 |
+
),
|
| 23 |
+
),
|
| 24 |
+
files=dict(
|
| 25 |
+
type="array",
|
| 26 |
+
items=dict(
|
| 27 |
+
type="object",
|
| 28 |
+
required=["path", "content"],
|
| 29 |
+
properties=dict(
|
| 30 |
+
path=dict(
|
| 31 |
+
type="string",
|
| 32 |
+
description="Path of file to write",
|
| 33 |
+
),
|
| 34 |
+
content=dict(
|
| 35 |
+
type="string",
|
| 36 |
+
description="Content to write to the file",
|
| 37 |
+
),
|
| 38 |
+
),
|
| 39 |
+
),
|
| 40 |
+
),
|
| 41 |
+
),
|
| 42 |
+
),
|
| 43 |
+
),
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
def __init__(self, *args, **kwargs):
|
| 47 |
+
self.gpt_prompts = WholeFileFunctionPrompts()
|
| 48 |
+
super().__init__(*args, **kwargs)
|
| 49 |
+
|
| 50 |
+
def update_cur_messages(self, edited):
|
| 51 |
+
if edited:
|
| 52 |
+
self.cur_messages += [
|
| 53 |
+
dict(role="assistant", content=self.gpt_prompts.redacted_edit_message)
|
| 54 |
+
]
|
| 55 |
+
else:
|
| 56 |
+
self.cur_messages += [dict(role="assistant", content=self.partial_response_content)]
|
| 57 |
+
|
| 58 |
+
def render_incremental_response(self, final=False):
|
| 59 |
+
if self.partial_response_content:
|
| 60 |
+
return self.partial_response_content
|
| 61 |
+
|
| 62 |
+
args = self.parse_partial_args()
|
| 63 |
+
|
| 64 |
+
if not args:
|
| 65 |
+
return
|
| 66 |
+
|
| 67 |
+
explanation = args.get("explanation")
|
| 68 |
+
files = args.get("files", [])
|
| 69 |
+
|
| 70 |
+
res = ""
|
| 71 |
+
if explanation:
|
| 72 |
+
res += f"{explanation}\n\n"
|
| 73 |
+
|
| 74 |
+
for i, file_upd in enumerate(files):
|
| 75 |
+
path = file_upd.get("path")
|
| 76 |
+
if not path:
|
| 77 |
+
continue
|
| 78 |
+
content = file_upd.get("content")
|
| 79 |
+
if not content:
|
| 80 |
+
continue
|
| 81 |
+
|
| 82 |
+
this_final = (i < len(files) - 1) or final
|
| 83 |
+
res += self.live_diffs(path, content, this_final)
|
| 84 |
+
|
| 85 |
+
return res
|
| 86 |
+
|
| 87 |
+
def live_diffs(self, fname, content, final):
|
| 88 |
+
lines = content.splitlines(keepends=True)
|
| 89 |
+
|
| 90 |
+
# ending an existing block
|
| 91 |
+
full_path = self.abs_root_path(fname)
|
| 92 |
+
|
| 93 |
+
content = self.io.read_text(full_path)
|
| 94 |
+
if content is None:
|
| 95 |
+
orig_lines = []
|
| 96 |
+
else:
|
| 97 |
+
orig_lines = content.splitlines()
|
| 98 |
+
|
| 99 |
+
show_diff = diffs.diff_partial_update(
|
| 100 |
+
orig_lines,
|
| 101 |
+
lines,
|
| 102 |
+
final,
|
| 103 |
+
fname=fname,
|
| 104 |
+
).splitlines()
|
| 105 |
+
|
| 106 |
+
return "\n".join(show_diff)
|
| 107 |
+
|
| 108 |
+
def update_files(self):
|
| 109 |
+
name = self.partial_response_function_call.get("name")
|
| 110 |
+
if name and name != "write_file":
|
| 111 |
+
raise ValueError(f'Unknown function_call name="{name}", use name="write_file"')
|
| 112 |
+
|
| 113 |
+
args = self.parse_partial_args()
|
| 114 |
+
if not args:
|
| 115 |
+
return
|
| 116 |
+
|
| 117 |
+
files = args.get("files", [])
|
| 118 |
+
|
| 119 |
+
edited = set()
|
| 120 |
+
for file_upd in files:
|
| 121 |
+
path = file_upd.get("path")
|
| 122 |
+
if not path:
|
| 123 |
+
raise ValueError(f"Missing path parameter: {file_upd}")
|
| 124 |
+
|
| 125 |
+
content = file_upd.get("content")
|
| 126 |
+
if not content:
|
| 127 |
+
raise ValueError(f"Missing content parameter: {file_upd}")
|
| 128 |
+
|
| 129 |
+
if self.allowed_to_edit(path, content):
|
| 130 |
+
edited.add(path)
|
| 131 |
+
|
| 132 |
+
return edited
|
testbed/Aider-AI__aider/aider/coders/wholefile_func_prompts.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa: E501
|
| 2 |
+
|
| 3 |
+
from .base_prompts import CoderPrompts
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class WholeFileFunctionPrompts(CoderPrompts):
|
| 7 |
+
main_system = """Act as an expert software developer.
|
| 8 |
+
Take requests for changes to the supplied code.
|
| 9 |
+
If the request is ambiguous, ask questions.
|
| 10 |
+
|
| 11 |
+
Once you understand the request you MUST use the `write_file` function to edit the files to make the needed changes.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
system_reminder = """
|
| 15 |
+
ONLY return code using the `write_file` function.
|
| 16 |
+
NEVER return code outside the `write_file` function.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
files_content_prefix = "Here is the current content of the files:\n"
|
| 20 |
+
files_no_full_files = "I am not sharing any files yet."
|
| 21 |
+
|
| 22 |
+
redacted_edit_message = "No changes are needed."
|
| 23 |
+
|
| 24 |
+
# TODO: should this be present for using this with gpt-4?
|
| 25 |
+
repo_content_prefix = None
|
| 26 |
+
|
| 27 |
+
# TODO: fix the chat history, except we can't keep the whole file
|
testbed/Aider-AI__aider/aider/coders/wholefile_prompts.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa: E501
|
| 2 |
+
|
| 3 |
+
from .base_prompts import CoderPrompts
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class WholeFilePrompts(CoderPrompts):
|
| 7 |
+
main_system = """Act as an expert software developer.
|
| 8 |
+
Take requests for changes to the supplied code.
|
| 9 |
+
If the request is ambiguous, ask questions.
|
| 10 |
+
|
| 11 |
+
Once you understand the request you MUST:
|
| 12 |
+
1. Determine if any code changes are needed.
|
| 13 |
+
2. Explain any needed changes.
|
| 14 |
+
3. If changes are needed, output a copy of each file that needs changes.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
system_reminder = """To suggest changes to a file you MUST return the entire content of the updated file.
|
| 18 |
+
You MUST use this *file listing* format:
|
| 19 |
+
|
| 20 |
+
path/to/filename.js
|
| 21 |
+
{fence[0]}
|
| 22 |
+
// entire file content ...
|
| 23 |
+
// ... goes in between
|
| 24 |
+
{fence[1]}
|
| 25 |
+
|
| 26 |
+
Every *file listing* MUST use this format:
|
| 27 |
+
- First line: the filename with any originally provided path
|
| 28 |
+
- Second line: opening {fence[0]}
|
| 29 |
+
- ... entire content of the file ...
|
| 30 |
+
- Final line: closing {fence[1]}
|
| 31 |
+
|
| 32 |
+
To suggest changes to a file you MUST return a *file listing* that contains the entire content of the file.
|
| 33 |
+
*NEVER* skip, omit or elide content from a *file listing* using "..." or by adding comments like "... rest of code..."!
|
| 34 |
+
Create a new file you MUST return a *file listing* which includes an appropriate filename, including any appropriate path.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
files_content_prefix = "Here is the current content of the files:\n"
|
| 38 |
+
files_no_full_files = "I am not sharing any files yet."
|
| 39 |
+
|
| 40 |
+
redacted_edit_message = "No changes are needed."
|
| 41 |
+
|
| 42 |
+
# this coder is not able to handle repo content
|
| 43 |
+
repo_content_prefix = None
|
testbed/Aider-AI__aider/aider/commands.py
ADDED
|
@@ -0,0 +1,486 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import shlex
|
| 3 |
+
import subprocess
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import git
|
| 8 |
+
import tiktoken
|
| 9 |
+
from prompt_toolkit.completion import Completion
|
| 10 |
+
|
| 11 |
+
from aider import prompts, voice
|
| 12 |
+
|
| 13 |
+
from .dump import dump # noqa: F401
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class Commands:
|
| 17 |
+
def __init__(self, io, coder, voice_language=None):
|
| 18 |
+
self.io = io
|
| 19 |
+
self.coder = coder
|
| 20 |
+
|
| 21 |
+
if voice_language == "auto":
|
| 22 |
+
voice_language = None
|
| 23 |
+
|
| 24 |
+
self.voice_language = voice_language
|
| 25 |
+
self.tokenizer = tiktoken.encoding_for_model(coder.main_model.name)
|
| 26 |
+
|
| 27 |
+
def is_command(self, inp):
|
| 28 |
+
if inp[0] == "/":
|
| 29 |
+
return True
|
| 30 |
+
|
| 31 |
+
def get_commands(self):
|
| 32 |
+
commands = []
|
| 33 |
+
for attr in dir(self):
|
| 34 |
+
if attr.startswith("cmd_"):
|
| 35 |
+
commands.append("/" + attr[4:])
|
| 36 |
+
|
| 37 |
+
return commands
|
| 38 |
+
|
| 39 |
+
def get_command_completions(self, cmd_name, partial):
|
| 40 |
+
cmd_completions_method_name = f"completions_{cmd_name}"
|
| 41 |
+
cmd_completions_method = getattr(self, cmd_completions_method_name, None)
|
| 42 |
+
if cmd_completions_method:
|
| 43 |
+
for completion in cmd_completions_method(partial):
|
| 44 |
+
yield completion
|
| 45 |
+
|
| 46 |
+
def do_run(self, cmd_name, args):
|
| 47 |
+
cmd_method_name = f"cmd_{cmd_name}"
|
| 48 |
+
cmd_method = getattr(self, cmd_method_name, None)
|
| 49 |
+
if cmd_method:
|
| 50 |
+
return cmd_method(args)
|
| 51 |
+
else:
|
| 52 |
+
self.io.tool_output(f"Error: Command {cmd_name} not found.")
|
| 53 |
+
|
| 54 |
+
def matching_commands(self, inp):
|
| 55 |
+
words = inp.strip().split()
|
| 56 |
+
if not words:
|
| 57 |
+
return
|
| 58 |
+
|
| 59 |
+
first_word = words[0]
|
| 60 |
+
rest_inp = inp[len(words[0]) :]
|
| 61 |
+
|
| 62 |
+
all_commands = self.get_commands()
|
| 63 |
+
matching_commands = [cmd for cmd in all_commands if cmd.startswith(first_word)]
|
| 64 |
+
return matching_commands, first_word, rest_inp
|
| 65 |
+
|
| 66 |
+
def run(self, inp):
|
| 67 |
+
res = self.matching_commands(inp)
|
| 68 |
+
if res is None:
|
| 69 |
+
return
|
| 70 |
+
matching_commands, first_word, rest_inp = res
|
| 71 |
+
if len(matching_commands) == 1:
|
| 72 |
+
return self.do_run(matching_commands[0][1:], rest_inp)
|
| 73 |
+
elif len(matching_commands) > 1:
|
| 74 |
+
self.io.tool_error(f"Ambiguous command: {', '.join(matching_commands)}")
|
| 75 |
+
else:
|
| 76 |
+
self.io.tool_error(f"Invalid command: {first_word}")
|
| 77 |
+
|
| 78 |
+
# any method called cmd_xxx becomes a command automatically.
|
| 79 |
+
# each one must take an args param.
|
| 80 |
+
|
| 81 |
+
def cmd_commit(self, args):
|
| 82 |
+
"Commit edits to the repo made outside the chat (commit message optional)"
|
| 83 |
+
|
| 84 |
+
if not self.coder.repo:
|
| 85 |
+
self.io.tool_error("No git repository found.")
|
| 86 |
+
return
|
| 87 |
+
|
| 88 |
+
if not self.coder.repo.is_dirty():
|
| 89 |
+
self.io.tool_error("No more changes to commit.")
|
| 90 |
+
return
|
| 91 |
+
|
| 92 |
+
commit_message = args.strip()
|
| 93 |
+
self.coder.repo.commit(message=commit_message)
|
| 94 |
+
|
| 95 |
+
def cmd_clear(self, args):
|
| 96 |
+
"Clear the chat history"
|
| 97 |
+
|
| 98 |
+
self.coder.done_messages = []
|
| 99 |
+
self.coder.cur_messages = []
|
| 100 |
+
|
| 101 |
+
def cmd_tokens(self, args):
|
| 102 |
+
"Report on the number of tokens used by the current chat context"
|
| 103 |
+
|
| 104 |
+
res = []
|
| 105 |
+
|
| 106 |
+
# system messages
|
| 107 |
+
msgs = [
|
| 108 |
+
dict(role="system", content=self.coder.gpt_prompts.main_system),
|
| 109 |
+
dict(role="system", content=self.coder.gpt_prompts.system_reminder),
|
| 110 |
+
]
|
| 111 |
+
tokens = len(self.tokenizer.encode(json.dumps(msgs)))
|
| 112 |
+
res.append((tokens, "system messages", ""))
|
| 113 |
+
|
| 114 |
+
# chat history
|
| 115 |
+
msgs = self.coder.done_messages + self.coder.cur_messages
|
| 116 |
+
if msgs:
|
| 117 |
+
msgs = [dict(role="dummy", content=msg) for msg in msgs]
|
| 118 |
+
msgs = json.dumps(msgs)
|
| 119 |
+
tokens = len(self.tokenizer.encode(msgs))
|
| 120 |
+
res.append((tokens, "chat history", "use /clear to clear"))
|
| 121 |
+
|
| 122 |
+
# repo map
|
| 123 |
+
other_files = set(self.coder.get_all_abs_files()) - set(self.coder.abs_fnames)
|
| 124 |
+
if self.coder.repo_map:
|
| 125 |
+
repo_content = self.coder.repo_map.get_repo_map(self.coder.abs_fnames, other_files)
|
| 126 |
+
if repo_content:
|
| 127 |
+
tokens = len(self.tokenizer.encode(repo_content))
|
| 128 |
+
res.append((tokens, "repository map", "use --map-tokens to resize"))
|
| 129 |
+
|
| 130 |
+
# files
|
| 131 |
+
for fname in self.coder.abs_fnames:
|
| 132 |
+
relative_fname = self.coder.get_rel_fname(fname)
|
| 133 |
+
content = self.io.read_text(fname)
|
| 134 |
+
# approximate
|
| 135 |
+
content = f"{relative_fname}\n```\n" + content + "```\n"
|
| 136 |
+
tokens = len(self.tokenizer.encode(content))
|
| 137 |
+
res.append((tokens, f"{relative_fname}", "use /drop to drop from chat"))
|
| 138 |
+
|
| 139 |
+
self.io.tool_output("Approximate context window usage, in tokens:")
|
| 140 |
+
self.io.tool_output()
|
| 141 |
+
|
| 142 |
+
width = 8
|
| 143 |
+
cost_width = 7
|
| 144 |
+
|
| 145 |
+
def fmt(v):
|
| 146 |
+
return format(int(v), ",").rjust(width)
|
| 147 |
+
|
| 148 |
+
col_width = max(len(row[1]) for row in res)
|
| 149 |
+
|
| 150 |
+
cost_pad = " " * cost_width
|
| 151 |
+
total = 0
|
| 152 |
+
total_cost = 0.0
|
| 153 |
+
for tk, msg, tip in res:
|
| 154 |
+
total += tk
|
| 155 |
+
cost = tk * (self.coder.main_model.prompt_price / 1000)
|
| 156 |
+
total_cost += cost
|
| 157 |
+
msg = msg.ljust(col_width)
|
| 158 |
+
self.io.tool_output(f"${cost:5.2f} {fmt(tk)} {msg} {tip}")
|
| 159 |
+
|
| 160 |
+
self.io.tool_output("=" * (width + cost_width + 1))
|
| 161 |
+
self.io.tool_output(f"${total_cost:5.2f} {fmt(total)} tokens total")
|
| 162 |
+
|
| 163 |
+
limit = self.coder.main_model.max_context_tokens
|
| 164 |
+
remaining = limit - total
|
| 165 |
+
if remaining > 1024:
|
| 166 |
+
self.io.tool_output(f"{cost_pad}{fmt(remaining)} tokens remaining in context window")
|
| 167 |
+
elif remaining > 0:
|
| 168 |
+
self.io.tool_error(
|
| 169 |
+
f"{cost_pad}{fmt(remaining)} tokens remaining in context window (use /drop or"
|
| 170 |
+
" /clear to make space)"
|
| 171 |
+
)
|
| 172 |
+
else:
|
| 173 |
+
self.io.tool_error(f"{cost_pad}{fmt(remaining)} tokens remaining, window exhausted!")
|
| 174 |
+
self.io.tool_output(f"{cost_pad}{fmt(limit)} tokens max context window size")
|
| 175 |
+
|
| 176 |
+
def cmd_undo(self, args):
|
| 177 |
+
"Undo the last git commit if it was done by aider"
|
| 178 |
+
if not self.coder.repo:
|
| 179 |
+
self.io.tool_error("No git repository found.")
|
| 180 |
+
return
|
| 181 |
+
|
| 182 |
+
if self.coder.repo.is_dirty():
|
| 183 |
+
self.io.tool_error(
|
| 184 |
+
"The repository has uncommitted changes. Please commit or stash them before"
|
| 185 |
+
" undoing."
|
| 186 |
+
)
|
| 187 |
+
return
|
| 188 |
+
|
| 189 |
+
local_head = self.coder.repo.repo.git.rev_parse("HEAD")
|
| 190 |
+
current_branch = self.coder.repo.repo.active_branch.name
|
| 191 |
+
try:
|
| 192 |
+
remote_head = self.coder.repo.repo.git.rev_parse(f"origin/{current_branch}")
|
| 193 |
+
has_origin = True
|
| 194 |
+
except git.exc.GitCommandError:
|
| 195 |
+
has_origin = False
|
| 196 |
+
|
| 197 |
+
if has_origin:
|
| 198 |
+
if local_head == remote_head:
|
| 199 |
+
self.io.tool_error(
|
| 200 |
+
"The last commit has already been pushed to the origin. Undoing is not"
|
| 201 |
+
" possible."
|
| 202 |
+
)
|
| 203 |
+
return
|
| 204 |
+
|
| 205 |
+
last_commit = self.coder.repo.repo.head.commit
|
| 206 |
+
if (
|
| 207 |
+
not last_commit.message.startswith("aider:")
|
| 208 |
+
or last_commit.hexsha[:7] != self.coder.last_aider_commit_hash
|
| 209 |
+
):
|
| 210 |
+
self.io.tool_error("The last commit was not made by aider in this chat session.")
|
| 211 |
+
return
|
| 212 |
+
self.coder.repo.repo.git.reset("--hard", "HEAD~1")
|
| 213 |
+
self.io.tool_output(
|
| 214 |
+
f"{last_commit.message.strip()}\n"
|
| 215 |
+
f"The above commit {self.coder.last_aider_commit_hash} "
|
| 216 |
+
"was reset and removed from git.\n"
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
if self.coder.main_model.send_undo_reply:
|
| 220 |
+
return prompts.undo_command_reply
|
| 221 |
+
|
| 222 |
+
def cmd_diff(self, args):
|
| 223 |
+
"Display the diff of the last aider commit"
|
| 224 |
+
if not self.coder.repo:
|
| 225 |
+
self.io.tool_error("No git repository found.")
|
| 226 |
+
return
|
| 227 |
+
|
| 228 |
+
if not self.coder.last_aider_commit_hash:
|
| 229 |
+
self.io.tool_error("No previous aider commit found.")
|
| 230 |
+
return
|
| 231 |
+
|
| 232 |
+
commits = f"{self.coder.last_aider_commit_hash}~1"
|
| 233 |
+
diff = self.coder.repo.get_diffs(
|
| 234 |
+
self.coder.pretty,
|
| 235 |
+
commits,
|
| 236 |
+
self.coder.last_aider_commit_hash,
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
# don't use io.tool_output() because we don't want to log or further colorize
|
| 240 |
+
print(diff)
|
| 241 |
+
|
| 242 |
+
def completions_add(self, partial):
|
| 243 |
+
files = set(self.coder.get_all_relative_files())
|
| 244 |
+
files = files - set(self.coder.get_inchat_relative_files())
|
| 245 |
+
for fname in files:
|
| 246 |
+
if partial.lower() in fname.lower():
|
| 247 |
+
yield Completion(fname, start_position=-len(partial))
|
| 248 |
+
|
| 249 |
+
def glob_filtered_to_repo(self, pattern):
|
| 250 |
+
raw_matched_files = list(Path(self.coder.root).glob(pattern))
|
| 251 |
+
|
| 252 |
+
matched_files = []
|
| 253 |
+
for fn in raw_matched_files:
|
| 254 |
+
matched_files += expand_subdir(fn)
|
| 255 |
+
|
| 256 |
+
matched_files = [str(Path(fn).relative_to(self.coder.root)) for fn in matched_files]
|
| 257 |
+
|
| 258 |
+
# if repo, filter against it
|
| 259 |
+
if self.coder.repo:
|
| 260 |
+
git_files = self.coder.repo.get_tracked_files()
|
| 261 |
+
matched_files = [fn for fn in matched_files if str(fn) in git_files]
|
| 262 |
+
|
| 263 |
+
res = list(map(str, matched_files))
|
| 264 |
+
return res
|
| 265 |
+
|
| 266 |
+
def cmd_add(self, args):
|
| 267 |
+
"Add matching files to the chat session using glob patterns"
|
| 268 |
+
|
| 269 |
+
added_fnames = []
|
| 270 |
+
git_added = []
|
| 271 |
+
git_files = self.coder.repo.get_tracked_files() if self.coder.repo else []
|
| 272 |
+
|
| 273 |
+
all_matched_files = set()
|
| 274 |
+
for word in args.split():
|
| 275 |
+
matched_files = self.glob_filtered_to_repo(word)
|
| 276 |
+
|
| 277 |
+
if not matched_files:
|
| 278 |
+
if any(char in word for char in "*?[]"):
|
| 279 |
+
self.io.tool_error(f"No files to add matching pattern: {word}")
|
| 280 |
+
else:
|
| 281 |
+
if Path(word).exists():
|
| 282 |
+
if Path(word).is_file():
|
| 283 |
+
matched_files = [word]
|
| 284 |
+
else:
|
| 285 |
+
self.io.tool_error(f"Unable to add: {word}")
|
| 286 |
+
elif self.io.confirm_ask(
|
| 287 |
+
f"No files matched '{word}'. Do you want to create the file?"
|
| 288 |
+
):
|
| 289 |
+
(Path(self.coder.root) / word).touch()
|
| 290 |
+
matched_files = [word]
|
| 291 |
+
|
| 292 |
+
all_matched_files.update(matched_files)
|
| 293 |
+
|
| 294 |
+
for matched_file in all_matched_files:
|
| 295 |
+
abs_file_path = self.coder.abs_root_path(matched_file)
|
| 296 |
+
|
| 297 |
+
if self.coder.repo and matched_file not in git_files:
|
| 298 |
+
self.coder.repo.repo.git.add(abs_file_path)
|
| 299 |
+
git_added.append(matched_file)
|
| 300 |
+
|
| 301 |
+
if abs_file_path in self.coder.abs_fnames:
|
| 302 |
+
self.io.tool_error(f"{matched_file} is already in the chat")
|
| 303 |
+
else:
|
| 304 |
+
content = self.io.read_text(abs_file_path)
|
| 305 |
+
if content is None:
|
| 306 |
+
self.io.tool_error(f"Unable to read {matched_file}")
|
| 307 |
+
else:
|
| 308 |
+
self.coder.abs_fnames.add(abs_file_path)
|
| 309 |
+
self.io.tool_output(f"Added {matched_file} to the chat")
|
| 310 |
+
added_fnames.append(matched_file)
|
| 311 |
+
|
| 312 |
+
if self.coder.repo and git_added:
|
| 313 |
+
git_added = " ".join(git_added)
|
| 314 |
+
commit_message = f"aider: Added {git_added}"
|
| 315 |
+
self.coder.repo.commit(message=commit_message)
|
| 316 |
+
|
| 317 |
+
if not added_fnames:
|
| 318 |
+
return
|
| 319 |
+
|
| 320 |
+
# only reply if there's been some chatting since the last edit
|
| 321 |
+
if not self.coder.cur_messages:
|
| 322 |
+
return
|
| 323 |
+
|
| 324 |
+
reply = prompts.added_files.format(fnames=", ".join(added_fnames))
|
| 325 |
+
return reply
|
| 326 |
+
|
| 327 |
+
def completions_drop(self, partial):
|
| 328 |
+
files = self.coder.get_inchat_relative_files()
|
| 329 |
+
|
| 330 |
+
for fname in files:
|
| 331 |
+
if partial.lower() in fname.lower():
|
| 332 |
+
yield Completion(fname, start_position=-len(partial))
|
| 333 |
+
|
| 334 |
+
def cmd_drop(self, args):
|
| 335 |
+
"Remove matching files from the chat session"
|
| 336 |
+
|
| 337 |
+
if not args.strip():
|
| 338 |
+
self.io.tool_output("Dropping all files from the chat session.")
|
| 339 |
+
self.coder.abs_fnames = set()
|
| 340 |
+
|
| 341 |
+
for word in args.split():
|
| 342 |
+
matched_files = self.glob_filtered_to_repo(word)
|
| 343 |
+
|
| 344 |
+
if not matched_files:
|
| 345 |
+
self.io.tool_error(f"No files matched '{word}'")
|
| 346 |
+
|
| 347 |
+
for matched_file in matched_files:
|
| 348 |
+
abs_fname = self.coder.abs_root_path(matched_file)
|
| 349 |
+
if abs_fname in self.coder.abs_fnames:
|
| 350 |
+
self.coder.abs_fnames.remove(abs_fname)
|
| 351 |
+
self.io.tool_output(f"Removed {matched_file} from the chat")
|
| 352 |
+
|
| 353 |
+
def cmd_git(self, args):
|
| 354 |
+
"Run a git command"
|
| 355 |
+
combined_output = None
|
| 356 |
+
try:
|
| 357 |
+
parsed_args = shlex.split("git " + args)
|
| 358 |
+
env = dict(GIT_EDITOR="true", **subprocess.os.environ)
|
| 359 |
+
result = subprocess.run(
|
| 360 |
+
parsed_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env
|
| 361 |
+
)
|
| 362 |
+
combined_output = result.stdout
|
| 363 |
+
except Exception as e:
|
| 364 |
+
self.io.tool_error(f"Error running git command: {e}")
|
| 365 |
+
|
| 366 |
+
if combined_output is None:
|
| 367 |
+
return
|
| 368 |
+
|
| 369 |
+
self.io.tool_output(combined_output)
|
| 370 |
+
|
| 371 |
+
def cmd_run(self, args):
|
| 372 |
+
"Run a shell command and optionally add the output to the chat"
|
| 373 |
+
combined_output = None
|
| 374 |
+
try:
|
| 375 |
+
parsed_args = shlex.split(args)
|
| 376 |
+
result = subprocess.run(
|
| 377 |
+
parsed_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
|
| 378 |
+
)
|
| 379 |
+
combined_output = result.stdout
|
| 380 |
+
except Exception as e:
|
| 381 |
+
self.io.tool_error(f"Error running command: {e}")
|
| 382 |
+
|
| 383 |
+
if combined_output is None:
|
| 384 |
+
return
|
| 385 |
+
|
| 386 |
+
self.io.tool_output(combined_output)
|
| 387 |
+
|
| 388 |
+
if self.io.confirm_ask("Add the output to the chat?", default="y"):
|
| 389 |
+
for line in combined_output.splitlines():
|
| 390 |
+
self.io.tool_output(line, log_only=True)
|
| 391 |
+
|
| 392 |
+
msg = prompts.run_output.format(
|
| 393 |
+
command=args,
|
| 394 |
+
output=combined_output,
|
| 395 |
+
)
|
| 396 |
+
return msg
|
| 397 |
+
|
| 398 |
+
def cmd_exit(self, args):
|
| 399 |
+
"Exit the application"
|
| 400 |
+
sys.exit()
|
| 401 |
+
|
| 402 |
+
def cmd_ls(self, args):
|
| 403 |
+
"List all known files and those included in the chat session"
|
| 404 |
+
|
| 405 |
+
files = self.coder.get_all_relative_files()
|
| 406 |
+
|
| 407 |
+
other_files = []
|
| 408 |
+
chat_files = []
|
| 409 |
+
for file in files:
|
| 410 |
+
abs_file_path = self.coder.abs_root_path(file)
|
| 411 |
+
if abs_file_path in self.coder.abs_fnames:
|
| 412 |
+
chat_files.append(file)
|
| 413 |
+
else:
|
| 414 |
+
other_files.append(file)
|
| 415 |
+
|
| 416 |
+
if not chat_files and not other_files:
|
| 417 |
+
self.io.tool_output("\nNo files in chat or git repo.")
|
| 418 |
+
return
|
| 419 |
+
|
| 420 |
+
if chat_files:
|
| 421 |
+
self.io.tool_output("Files in chat:\n")
|
| 422 |
+
for file in chat_files:
|
| 423 |
+
self.io.tool_output(f" {file}")
|
| 424 |
+
|
| 425 |
+
if other_files:
|
| 426 |
+
self.io.tool_output("\nRepo files not in the chat:\n")
|
| 427 |
+
for file in other_files:
|
| 428 |
+
self.io.tool_output(f" {file}")
|
| 429 |
+
|
| 430 |
+
def cmd_help(self, args):
|
| 431 |
+
"Show help about all commands"
|
| 432 |
+
commands = sorted(self.get_commands())
|
| 433 |
+
for cmd in commands:
|
| 434 |
+
cmd_method_name = f"cmd_{cmd[1:]}"
|
| 435 |
+
cmd_method = getattr(self, cmd_method_name, None)
|
| 436 |
+
if cmd_method:
|
| 437 |
+
description = cmd_method.__doc__
|
| 438 |
+
self.io.tool_output(f"{cmd} {description}")
|
| 439 |
+
else:
|
| 440 |
+
self.io.tool_output(f"{cmd} No description available.")
|
| 441 |
+
|
| 442 |
+
def cmd_voice(self, args):
|
| 443 |
+
"Record and transcribe voice input"
|
| 444 |
+
v = voice.Voice()
|
| 445 |
+
|
| 446 |
+
if not v.is_audio_available():
|
| 447 |
+
self.io.tool_error("Unable to import `sounddevice`, is portaudio installed?")
|
| 448 |
+
return
|
| 449 |
+
|
| 450 |
+
history_iter = self.io.get_input_history()
|
| 451 |
+
|
| 452 |
+
history = []
|
| 453 |
+
size = 0
|
| 454 |
+
for line in history_iter:
|
| 455 |
+
if line.startswith("/"):
|
| 456 |
+
continue
|
| 457 |
+
if line in history:
|
| 458 |
+
continue
|
| 459 |
+
if size + len(line) > 1024:
|
| 460 |
+
break
|
| 461 |
+
size += len(line)
|
| 462 |
+
history.append(line)
|
| 463 |
+
|
| 464 |
+
history.reverse()
|
| 465 |
+
history = "\n".join(history)
|
| 466 |
+
|
| 467 |
+
text = v.record_and_transcribe(history, language=self.voice_language)
|
| 468 |
+
if text:
|
| 469 |
+
self.io.add_to_input_history(text)
|
| 470 |
+
print()
|
| 471 |
+
self.io.user_input(text, log_only=False)
|
| 472 |
+
print()
|
| 473 |
+
|
| 474 |
+
return text
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def expand_subdir(file_path):
|
| 478 |
+
file_path = Path(file_path)
|
| 479 |
+
if file_path.is_file():
|
| 480 |
+
yield file_path
|
| 481 |
+
return
|
| 482 |
+
|
| 483 |
+
if file_path.is_dir():
|
| 484 |
+
for file in file_path.rglob("*"):
|
| 485 |
+
if file.is_file():
|
| 486 |
+
yield str(file)
|
testbed/Aider-AI__aider/aider/diffs.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import difflib
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
from .dump import dump # noqa: F401
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
if len(sys.argv) != 3:
|
| 9 |
+
print("Usage: python diffs.py file1 file")
|
| 10 |
+
sys.exit(1)
|
| 11 |
+
|
| 12 |
+
file_orig, file_updated = sys.argv[1], sys.argv[2]
|
| 13 |
+
|
| 14 |
+
with open(file_orig, "r", encoding="utf-8") as f:
|
| 15 |
+
lines_orig = f.readlines()
|
| 16 |
+
|
| 17 |
+
with open(file_updated, "r", encoding="utf-8") as f:
|
| 18 |
+
lines_updated = f.readlines()
|
| 19 |
+
|
| 20 |
+
for i in range(len(file_updated)):
|
| 21 |
+
res = diff_partial_update(lines_orig, lines_updated[:i])
|
| 22 |
+
print(res)
|
| 23 |
+
input()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def create_progress_bar(percentage):
|
| 27 |
+
block = "█"
|
| 28 |
+
empty = "░"
|
| 29 |
+
total_blocks = 30
|
| 30 |
+
filled_blocks = int(total_blocks * percentage // 100)
|
| 31 |
+
empty_blocks = total_blocks - filled_blocks
|
| 32 |
+
bar = block * filled_blocks + empty * empty_blocks
|
| 33 |
+
return bar
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def assert_newlines(lines):
|
| 37 |
+
if not lines:
|
| 38 |
+
return
|
| 39 |
+
for line in lines[:-1]:
|
| 40 |
+
assert line and line[-1] == "\n", line
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def diff_partial_update(lines_orig, lines_updated, final=False, fname=None):
|
| 44 |
+
"""
|
| 45 |
+
Given only the first part of an updated file, show the diff while
|
| 46 |
+
ignoring the block of "deleted" lines that are past the end of the
|
| 47 |
+
partially complete update.
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
# dump(lines_orig)
|
| 51 |
+
# dump(lines_updated)
|
| 52 |
+
|
| 53 |
+
assert_newlines(lines_orig)
|
| 54 |
+
assert_newlines(lines_orig)
|
| 55 |
+
|
| 56 |
+
num_orig_lines = len(lines_orig)
|
| 57 |
+
|
| 58 |
+
if final:
|
| 59 |
+
last_non_deleted = num_orig_lines
|
| 60 |
+
else:
|
| 61 |
+
last_non_deleted = find_last_non_deleted(lines_orig, lines_updated)
|
| 62 |
+
|
| 63 |
+
# dump(last_non_deleted)
|
| 64 |
+
if last_non_deleted is None:
|
| 65 |
+
return ""
|
| 66 |
+
|
| 67 |
+
if num_orig_lines:
|
| 68 |
+
pct = last_non_deleted * 100 / num_orig_lines
|
| 69 |
+
else:
|
| 70 |
+
pct = 50
|
| 71 |
+
bar = create_progress_bar(pct)
|
| 72 |
+
bar = f" {last_non_deleted:3d} / {num_orig_lines:3d} lines [{bar}] {pct:3.0f}%\n"
|
| 73 |
+
|
| 74 |
+
lines_orig = lines_orig[:last_non_deleted]
|
| 75 |
+
|
| 76 |
+
if not final:
|
| 77 |
+
lines_updated = lines_updated[:-1] + [bar]
|
| 78 |
+
|
| 79 |
+
diff = difflib.unified_diff(lines_orig, lines_updated, n=5)
|
| 80 |
+
|
| 81 |
+
diff = list(diff)[2:]
|
| 82 |
+
|
| 83 |
+
diff = "".join(diff)
|
| 84 |
+
if not diff.endswith("\n"):
|
| 85 |
+
diff += "\n"
|
| 86 |
+
|
| 87 |
+
for i in range(3, 10):
|
| 88 |
+
backticks = "`" * i
|
| 89 |
+
if backticks not in diff:
|
| 90 |
+
break
|
| 91 |
+
|
| 92 |
+
show = f"{backticks}diff\n"
|
| 93 |
+
if fname:
|
| 94 |
+
show += f"--- {fname} original\n"
|
| 95 |
+
show += f"+++ {fname} updated\n"
|
| 96 |
+
|
| 97 |
+
show += diff
|
| 98 |
+
|
| 99 |
+
show += f"{backticks}\n\n"
|
| 100 |
+
|
| 101 |
+
# print(diff)
|
| 102 |
+
|
| 103 |
+
return show
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def find_last_non_deleted(lines_orig, lines_updated):
|
| 107 |
+
diff = list(difflib.ndiff(lines_orig, lines_updated))
|
| 108 |
+
|
| 109 |
+
num_orig = 0
|
| 110 |
+
last_non_deleted_orig = None
|
| 111 |
+
|
| 112 |
+
for line in diff:
|
| 113 |
+
# print(f"{num_orig:2d} {num_updated:2d} {line}", end="")
|
| 114 |
+
code = line[0]
|
| 115 |
+
if code == " ":
|
| 116 |
+
num_orig += 1
|
| 117 |
+
last_non_deleted_orig = num_orig
|
| 118 |
+
elif code == "-":
|
| 119 |
+
# line only in orig
|
| 120 |
+
num_orig += 1
|
| 121 |
+
elif code == "+":
|
| 122 |
+
# line only in updated
|
| 123 |
+
pass
|
| 124 |
+
|
| 125 |
+
return last_non_deleted_orig
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
if __name__ == "__main__":
|
| 129 |
+
main()
|
testbed/Aider-AI__aider/aider/dump.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import traceback
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def cvt(s):
|
| 6 |
+
if isinstance(s, str):
|
| 7 |
+
return s
|
| 8 |
+
try:
|
| 9 |
+
return json.dumps(s, indent=4)
|
| 10 |
+
except TypeError:
|
| 11 |
+
return str(s)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def dump(*vals):
|
| 15 |
+
# http://docs.python.org/library/traceback.html
|
| 16 |
+
stack = traceback.extract_stack()
|
| 17 |
+
vars = stack[-2][3]
|
| 18 |
+
|
| 19 |
+
# strip away the call to dump()
|
| 20 |
+
vars = "(".join(vars.split("(")[1:])
|
| 21 |
+
vars = ")".join(vars.split(")")[:-1])
|
| 22 |
+
|
| 23 |
+
vals = [cvt(v) for v in vals]
|
| 24 |
+
has_newline = sum(1 for v in vals if "\n" in v)
|
| 25 |
+
if has_newline:
|
| 26 |
+
print("%s:" % vars)
|
| 27 |
+
print(", ".join(vals))
|
| 28 |
+
else:
|
| 29 |
+
print("%s:" % vars, ", ".join(vals))
|
testbed/Aider-AI__aider/aider/history.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
import tiktoken
|
| 5 |
+
|
| 6 |
+
from aider import models, prompts
|
| 7 |
+
from aider.dump import dump # noqa: F401
|
| 8 |
+
from aider.sendchat import simple_send_with_retries
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ChatSummary:
|
| 12 |
+
def __init__(self, model=models.GPT35.name, max_tokens=1024):
|
| 13 |
+
self.tokenizer = tiktoken.encoding_for_model(model)
|
| 14 |
+
self.max_tokens = max_tokens
|
| 15 |
+
|
| 16 |
+
def too_big(self, messages):
|
| 17 |
+
sized = self.tokenize(messages)
|
| 18 |
+
total = sum(tokens for tokens, _msg in sized)
|
| 19 |
+
return total > self.max_tokens
|
| 20 |
+
|
| 21 |
+
def tokenize(self, messages):
|
| 22 |
+
sized = []
|
| 23 |
+
for msg in messages:
|
| 24 |
+
tokens = len(self.tokenizer.encode(json.dumps(msg)))
|
| 25 |
+
sized.append((tokens, msg))
|
| 26 |
+
return sized
|
| 27 |
+
|
| 28 |
+
def summarize(self, messages, depth=0):
|
| 29 |
+
sized = self.tokenize(messages)
|
| 30 |
+
total = sum(tokens for tokens, _msg in sized)
|
| 31 |
+
if total <= self.max_tokens and depth == 0:
|
| 32 |
+
return messages
|
| 33 |
+
|
| 34 |
+
min_split = 4
|
| 35 |
+
if len(messages) <= min_split or depth > 3:
|
| 36 |
+
return self.summarize_all(messages)
|
| 37 |
+
|
| 38 |
+
tail_tokens = 0
|
| 39 |
+
split_index = len(messages)
|
| 40 |
+
half_max_tokens = self.max_tokens // 2
|
| 41 |
+
|
| 42 |
+
# Iterate over the messages in reverse order
|
| 43 |
+
for i in range(len(sized) - 1, -1, -1):
|
| 44 |
+
tokens, _msg = sized[i]
|
| 45 |
+
if tail_tokens + tokens < half_max_tokens:
|
| 46 |
+
tail_tokens += tokens
|
| 47 |
+
split_index = i
|
| 48 |
+
else:
|
| 49 |
+
break
|
| 50 |
+
|
| 51 |
+
# Ensure the head ends with an assistant message
|
| 52 |
+
while messages[split_index - 1]["role"] != "assistant" and split_index > 1:
|
| 53 |
+
split_index -= 1
|
| 54 |
+
|
| 55 |
+
if split_index <= min_split:
|
| 56 |
+
return self.summarize_all(messages)
|
| 57 |
+
|
| 58 |
+
head = messages[:split_index]
|
| 59 |
+
tail = messages[split_index:]
|
| 60 |
+
|
| 61 |
+
summary = self.summarize_all(head)
|
| 62 |
+
|
| 63 |
+
tail_tokens = sum(tokens for tokens, msg in sized[split_index:])
|
| 64 |
+
summary_tokens = len(self.tokenizer.encode(json.dumps(summary)))
|
| 65 |
+
|
| 66 |
+
result = summary + tail
|
| 67 |
+
if summary_tokens + tail_tokens < self.max_tokens:
|
| 68 |
+
return result
|
| 69 |
+
|
| 70 |
+
return self.summarize(result, depth + 1)
|
| 71 |
+
|
| 72 |
+
def summarize_all(self, messages):
|
| 73 |
+
content = ""
|
| 74 |
+
for msg in messages:
|
| 75 |
+
role = msg["role"].upper()
|
| 76 |
+
if role not in ("USER", "ASSISTANT"):
|
| 77 |
+
continue
|
| 78 |
+
content += f"# {role}\n"
|
| 79 |
+
content += msg["content"]
|
| 80 |
+
if not content.endswith("\n"):
|
| 81 |
+
content += "\n"
|
| 82 |
+
|
| 83 |
+
messages = [
|
| 84 |
+
dict(role="system", content=prompts.summarize),
|
| 85 |
+
dict(role="user", content=content),
|
| 86 |
+
]
|
| 87 |
+
|
| 88 |
+
summary = simple_send_with_retries(model=models.GPT35.name, messages=messages)
|
| 89 |
+
summary = prompts.summary_prefix + summary
|
| 90 |
+
|
| 91 |
+
return [dict(role="user", content=summary)]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def main():
|
| 95 |
+
parser = argparse.ArgumentParser()
|
| 96 |
+
parser.add_argument("filename", help="Markdown file to parse")
|
| 97 |
+
args = parser.parse_args()
|
| 98 |
+
|
| 99 |
+
with open(args.filename, "r") as f:
|
| 100 |
+
text = f.read()
|
| 101 |
+
|
| 102 |
+
messages = []
|
| 103 |
+
assistant = []
|
| 104 |
+
for line in text.splitlines(keepends=True):
|
| 105 |
+
if line.startswith("# "):
|
| 106 |
+
continue
|
| 107 |
+
if line.startswith(">"):
|
| 108 |
+
continue
|
| 109 |
+
if line.startswith("#### /"):
|
| 110 |
+
continue
|
| 111 |
+
|
| 112 |
+
if line.startswith("#### "):
|
| 113 |
+
if assistant:
|
| 114 |
+
assistant = "".join(assistant)
|
| 115 |
+
if assistant.strip():
|
| 116 |
+
messages.append(dict(role="assistant", content=assistant))
|
| 117 |
+
assistant = []
|
| 118 |
+
|
| 119 |
+
content = line[5:]
|
| 120 |
+
if content.strip() and content.strip() != "<blank>":
|
| 121 |
+
messages.append(dict(role="user", content=line[5:]))
|
| 122 |
+
continue
|
| 123 |
+
|
| 124 |
+
assistant.append(line)
|
| 125 |
+
|
| 126 |
+
summarizer = ChatSummary(models.GPT35.name)
|
| 127 |
+
summary = summarizer.summarize(messages[-40:])
|
| 128 |
+
dump(summary)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
if __name__ == "__main__":
|
| 132 |
+
main()
|
testbed/Aider-AI__aider/aider/io.py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|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from prompt_toolkit.completion import Completer, Completion
|
| 7 |
+
from prompt_toolkit.history import FileHistory
|
| 8 |
+
from prompt_toolkit.key_binding import KeyBindings
|
| 9 |
+
from prompt_toolkit.lexers import PygmentsLexer
|
| 10 |
+
from prompt_toolkit.shortcuts import CompleteStyle, PromptSession, prompt
|
| 11 |
+
from prompt_toolkit.styles import Style
|
| 12 |
+
from pygments.lexers import MarkdownLexer, guess_lexer_for_filename
|
| 13 |
+
from pygments.token import Token
|
| 14 |
+
from pygments.util import ClassNotFound
|
| 15 |
+
from rich.console import Console
|
| 16 |
+
from rich.text import Text
|
| 17 |
+
|
| 18 |
+
from .dump import dump # noqa: F401
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class AutoCompleter(Completer):
|
| 22 |
+
def __init__(self, root, rel_fnames, addable_rel_fnames, commands, encoding):
|
| 23 |
+
self.commands = commands
|
| 24 |
+
self.addable_rel_fnames = addable_rel_fnames
|
| 25 |
+
self.rel_fnames = rel_fnames
|
| 26 |
+
self.encoding = encoding
|
| 27 |
+
|
| 28 |
+
fname_to_rel_fnames = defaultdict(list)
|
| 29 |
+
for rel_fname in addable_rel_fnames:
|
| 30 |
+
fname = os.path.basename(rel_fname)
|
| 31 |
+
if fname != rel_fname:
|
| 32 |
+
fname_to_rel_fnames[fname].append(rel_fname)
|
| 33 |
+
self.fname_to_rel_fnames = fname_to_rel_fnames
|
| 34 |
+
|
| 35 |
+
self.words = set()
|
| 36 |
+
|
| 37 |
+
for rel_fname in addable_rel_fnames:
|
| 38 |
+
self.words.add(rel_fname)
|
| 39 |
+
|
| 40 |
+
for rel_fname in rel_fnames:
|
| 41 |
+
self.words.add(rel_fname)
|
| 42 |
+
|
| 43 |
+
fname = Path(root) / rel_fname
|
| 44 |
+
try:
|
| 45 |
+
with open(fname, "r", encoding=self.encoding) as f:
|
| 46 |
+
content = f.read()
|
| 47 |
+
except FileNotFoundError:
|
| 48 |
+
continue
|
| 49 |
+
try:
|
| 50 |
+
lexer = guess_lexer_for_filename(fname, content)
|
| 51 |
+
except ClassNotFound:
|
| 52 |
+
continue
|
| 53 |
+
tokens = list(lexer.get_tokens(content))
|
| 54 |
+
self.words.update(token[1] for token in tokens if token[0] in Token.Name)
|
| 55 |
+
|
| 56 |
+
def get_completions(self, document, complete_event):
|
| 57 |
+
text = document.text_before_cursor
|
| 58 |
+
words = text.split()
|
| 59 |
+
if not words:
|
| 60 |
+
return
|
| 61 |
+
|
| 62 |
+
if text[0] == "/":
|
| 63 |
+
if len(words) == 1 and not text[-1].isspace():
|
| 64 |
+
candidates = self.commands.get_commands()
|
| 65 |
+
candidates = [(cmd, cmd) for cmd in candidates]
|
| 66 |
+
else:
|
| 67 |
+
for completion in self.commands.get_command_completions(words[0][1:], words[-1]):
|
| 68 |
+
yield completion
|
| 69 |
+
return
|
| 70 |
+
else:
|
| 71 |
+
candidates = self.words
|
| 72 |
+
candidates.update(set(self.fname_to_rel_fnames))
|
| 73 |
+
candidates = [(word, f"`{word}`") for word in candidates]
|
| 74 |
+
|
| 75 |
+
last_word = words[-1]
|
| 76 |
+
for word_match, word_insert in candidates:
|
| 77 |
+
if word_match.lower().startswith(last_word.lower()):
|
| 78 |
+
rel_fnames = self.fname_to_rel_fnames.get(word_match, [])
|
| 79 |
+
if rel_fnames:
|
| 80 |
+
for rel_fname in rel_fnames:
|
| 81 |
+
yield Completion(
|
| 82 |
+
f"`{rel_fname}`", start_position=-len(last_word), display=rel_fname
|
| 83 |
+
)
|
| 84 |
+
else:
|
| 85 |
+
yield Completion(
|
| 86 |
+
word_insert, start_position=-len(last_word), display=word_match
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class InputOutput:
|
| 91 |
+
num_error_outputs = 0
|
| 92 |
+
num_user_asks = 0
|
| 93 |
+
|
| 94 |
+
def __init__(
|
| 95 |
+
self,
|
| 96 |
+
pretty=True,
|
| 97 |
+
yes=False,
|
| 98 |
+
input_history_file=None,
|
| 99 |
+
chat_history_file=None,
|
| 100 |
+
input=None,
|
| 101 |
+
output=None,
|
| 102 |
+
user_input_color="blue",
|
| 103 |
+
tool_output_color=None,
|
| 104 |
+
tool_error_color="red",
|
| 105 |
+
encoding="utf-8",
|
| 106 |
+
dry_run=False,
|
| 107 |
+
):
|
| 108 |
+
no_color = os.environ.get("NO_COLOR")
|
| 109 |
+
if no_color is not None and no_color != "":
|
| 110 |
+
pretty = False
|
| 111 |
+
|
| 112 |
+
self.user_input_color = user_input_color if pretty else None
|
| 113 |
+
self.tool_output_color = tool_output_color if pretty else None
|
| 114 |
+
self.tool_error_color = tool_error_color if pretty else None
|
| 115 |
+
|
| 116 |
+
self.input = input
|
| 117 |
+
self.output = output
|
| 118 |
+
|
| 119 |
+
self.pretty = pretty
|
| 120 |
+
if self.output:
|
| 121 |
+
self.pretty = False
|
| 122 |
+
|
| 123 |
+
self.yes = yes
|
| 124 |
+
|
| 125 |
+
self.input_history_file = input_history_file
|
| 126 |
+
if chat_history_file is not None:
|
| 127 |
+
self.chat_history_file = Path(chat_history_file)
|
| 128 |
+
else:
|
| 129 |
+
self.chat_history_file = None
|
| 130 |
+
|
| 131 |
+
self.encoding = encoding
|
| 132 |
+
self.dry_run = dry_run
|
| 133 |
+
|
| 134 |
+
if pretty:
|
| 135 |
+
self.console = Console()
|
| 136 |
+
else:
|
| 137 |
+
self.console = Console(force_terminal=False, no_color=True)
|
| 138 |
+
|
| 139 |
+
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 140 |
+
self.append_chat_history(f"\n# aider chat started at {current_time}\n\n")
|
| 141 |
+
|
| 142 |
+
def read_text(self, filename):
|
| 143 |
+
try:
|
| 144 |
+
with open(str(filename), "r", encoding=self.encoding) as f:
|
| 145 |
+
return f.read()
|
| 146 |
+
except FileNotFoundError:
|
| 147 |
+
self.tool_error(f"{filename}: file not found error")
|
| 148 |
+
return
|
| 149 |
+
except UnicodeError as e:
|
| 150 |
+
self.tool_error(f"{filename}: {e}")
|
| 151 |
+
self.tool_error("Use --encoding to set the unicode encoding.")
|
| 152 |
+
return
|
| 153 |
+
|
| 154 |
+
def write_text(self, filename, content):
|
| 155 |
+
if self.dry_run:
|
| 156 |
+
return
|
| 157 |
+
with open(str(filename), "w", encoding=self.encoding) as f:
|
| 158 |
+
f.write(content)
|
| 159 |
+
|
| 160 |
+
def get_input(self, root, rel_fnames, addable_rel_fnames, commands):
|
| 161 |
+
if self.pretty:
|
| 162 |
+
style = dict(style=self.user_input_color) if self.user_input_color else dict()
|
| 163 |
+
self.console.rule(**style)
|
| 164 |
+
else:
|
| 165 |
+
print()
|
| 166 |
+
|
| 167 |
+
rel_fnames = list(rel_fnames)
|
| 168 |
+
show = " ".join(rel_fnames)
|
| 169 |
+
if len(show) > 10:
|
| 170 |
+
show += "\n"
|
| 171 |
+
show += "> "
|
| 172 |
+
|
| 173 |
+
inp = ""
|
| 174 |
+
multiline_input = False
|
| 175 |
+
|
| 176 |
+
if self.user_input_color:
|
| 177 |
+
style = Style.from_dict(
|
| 178 |
+
{
|
| 179 |
+
"": self.user_input_color,
|
| 180 |
+
"pygments.literal.string": f"bold italic {self.user_input_color}",
|
| 181 |
+
}
|
| 182 |
+
)
|
| 183 |
+
else:
|
| 184 |
+
style = None
|
| 185 |
+
|
| 186 |
+
while True:
|
| 187 |
+
completer_instance = AutoCompleter(
|
| 188 |
+
root, rel_fnames, addable_rel_fnames, commands, self.encoding
|
| 189 |
+
)
|
| 190 |
+
if multiline_input:
|
| 191 |
+
show = ". "
|
| 192 |
+
|
| 193 |
+
session_kwargs = {
|
| 194 |
+
"message": show,
|
| 195 |
+
"completer": completer_instance,
|
| 196 |
+
"reserve_space_for_menu": 4,
|
| 197 |
+
"complete_style": CompleteStyle.MULTI_COLUMN,
|
| 198 |
+
"input": self.input,
|
| 199 |
+
"output": self.output,
|
| 200 |
+
"lexer": PygmentsLexer(MarkdownLexer),
|
| 201 |
+
}
|
| 202 |
+
if style:
|
| 203 |
+
session_kwargs["style"] = style
|
| 204 |
+
|
| 205 |
+
if self.input_history_file is not None:
|
| 206 |
+
session_kwargs["history"] = FileHistory(self.input_history_file)
|
| 207 |
+
|
| 208 |
+
kb = KeyBindings()
|
| 209 |
+
|
| 210 |
+
@kb.add("escape", "c-m", eager=True)
|
| 211 |
+
def _(event):
|
| 212 |
+
event.current_buffer.insert_text("\n")
|
| 213 |
+
|
| 214 |
+
session = PromptSession(key_bindings=kb, **session_kwargs)
|
| 215 |
+
line = session.prompt()
|
| 216 |
+
|
| 217 |
+
if line and line[0] == "{" and not multiline_input:
|
| 218 |
+
multiline_input = True
|
| 219 |
+
inp += line[1:] + "\n"
|
| 220 |
+
continue
|
| 221 |
+
elif line and line[-1] == "}" and multiline_input:
|
| 222 |
+
inp += line[:-1] + "\n"
|
| 223 |
+
break
|
| 224 |
+
elif multiline_input:
|
| 225 |
+
inp += line + "\n"
|
| 226 |
+
else:
|
| 227 |
+
inp = line
|
| 228 |
+
break
|
| 229 |
+
|
| 230 |
+
print()
|
| 231 |
+
self.user_input(inp)
|
| 232 |
+
return inp
|
| 233 |
+
|
| 234 |
+
def add_to_input_history(self, inp):
|
| 235 |
+
if not self.input_history_file:
|
| 236 |
+
return
|
| 237 |
+
FileHistory(self.input_history_file).append_string(inp)
|
| 238 |
+
|
| 239 |
+
def get_input_history(self):
|
| 240 |
+
if not self.input_history_file:
|
| 241 |
+
return []
|
| 242 |
+
|
| 243 |
+
fh = FileHistory(self.input_history_file)
|
| 244 |
+
return fh.load_history_strings()
|
| 245 |
+
|
| 246 |
+
def user_input(self, inp, log_only=True):
|
| 247 |
+
if not log_only:
|
| 248 |
+
style = dict(style=self.user_input_color) if self.user_input_color else dict()
|
| 249 |
+
self.console.print(inp, **style)
|
| 250 |
+
|
| 251 |
+
prefix = "####"
|
| 252 |
+
if inp:
|
| 253 |
+
hist = inp.splitlines()
|
| 254 |
+
else:
|
| 255 |
+
hist = ["<blank>"]
|
| 256 |
+
|
| 257 |
+
hist = f" \n{prefix} ".join(hist)
|
| 258 |
+
|
| 259 |
+
hist = f"""
|
| 260 |
+
{prefix} {hist}"""
|
| 261 |
+
self.append_chat_history(hist, linebreak=True)
|
| 262 |
+
|
| 263 |
+
# OUTPUT
|
| 264 |
+
|
| 265 |
+
def ai_output(self, content):
|
| 266 |
+
hist = "\n" + content.strip() + "\n\n"
|
| 267 |
+
self.append_chat_history(hist)
|
| 268 |
+
|
| 269 |
+
def confirm_ask(self, question, default="y"):
|
| 270 |
+
self.num_user_asks += 1
|
| 271 |
+
|
| 272 |
+
if self.yes is True:
|
| 273 |
+
res = "yes"
|
| 274 |
+
elif self.yes is False:
|
| 275 |
+
res = "no"
|
| 276 |
+
else:
|
| 277 |
+
res = prompt(question + " ", default=default)
|
| 278 |
+
|
| 279 |
+
hist = f"{question.strip()} {res.strip()}"
|
| 280 |
+
self.append_chat_history(hist, linebreak=True, blockquote=True)
|
| 281 |
+
if self.yes in (True, False):
|
| 282 |
+
self.tool_output(hist)
|
| 283 |
+
|
| 284 |
+
if not res or not res.strip():
|
| 285 |
+
return
|
| 286 |
+
return res.strip().lower().startswith("y")
|
| 287 |
+
|
| 288 |
+
def prompt_ask(self, question, default=None):
|
| 289 |
+
self.num_user_asks += 1
|
| 290 |
+
|
| 291 |
+
if self.yes is True:
|
| 292 |
+
res = "yes"
|
| 293 |
+
elif self.yes is False:
|
| 294 |
+
res = "no"
|
| 295 |
+
else:
|
| 296 |
+
res = prompt(question + " ", default=default)
|
| 297 |
+
|
| 298 |
+
hist = f"{question.strip()} {res.strip()}"
|
| 299 |
+
self.append_chat_history(hist, linebreak=True, blockquote=True)
|
| 300 |
+
if self.yes in (True, False):
|
| 301 |
+
self.tool_output(hist)
|
| 302 |
+
|
| 303 |
+
return res
|
| 304 |
+
|
| 305 |
+
def tool_error(self, message):
|
| 306 |
+
self.num_error_outputs += 1
|
| 307 |
+
|
| 308 |
+
if message.strip():
|
| 309 |
+
hist = f"{message.strip()}"
|
| 310 |
+
self.append_chat_history(hist, linebreak=True, blockquote=True)
|
| 311 |
+
|
| 312 |
+
message = Text(message)
|
| 313 |
+
style = dict(style=self.tool_error_color) if self.tool_error_color else dict()
|
| 314 |
+
self.console.print(message, **style)
|
| 315 |
+
|
| 316 |
+
def tool_output(self, *messages, log_only=False):
|
| 317 |
+
if messages:
|
| 318 |
+
hist = " ".join(messages)
|
| 319 |
+
hist = f"{hist.strip()}"
|
| 320 |
+
self.append_chat_history(hist, linebreak=True, blockquote=True)
|
| 321 |
+
|
| 322 |
+
if not log_only:
|
| 323 |
+
messages = list(map(Text, messages))
|
| 324 |
+
style = dict(style=self.tool_output_color) if self.tool_output_color else dict()
|
| 325 |
+
self.console.print(*messages, **style)
|
| 326 |
+
|
| 327 |
+
def append_chat_history(self, text, linebreak=False, blockquote=False):
|
| 328 |
+
if blockquote:
|
| 329 |
+
text = text.strip()
|
| 330 |
+
text = "> " + text
|
| 331 |
+
if linebreak:
|
| 332 |
+
text = text.rstrip()
|
| 333 |
+
text = text + " \n"
|
| 334 |
+
if not text.endswith("\n"):
|
| 335 |
+
text += "\n"
|
| 336 |
+
if self.chat_history_file is not None:
|
| 337 |
+
with self.chat_history_file.open("a", encoding=self.encoding) as f:
|
| 338 |
+
f.write(text)
|
testbed/Aider-AI__aider/aider/main.py
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
from aider import __version__, models
|
| 10 |
+
from aider.coders import Coder
|
| 11 |
+
from aider.io import InputOutput
|
| 12 |
+
from aider.repo import GitRepo
|
| 13 |
+
from aider.versioncheck import check_version
|
| 14 |
+
|
| 15 |
+
from .dump import dump # noqa: F401
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def get_git_root():
|
| 19 |
+
"""Try and guess the git repo, since the conf.yml can be at the repo root"""
|
| 20 |
+
try:
|
| 21 |
+
repo = git.Repo(search_parent_directories=True)
|
| 22 |
+
return repo.working_tree_dir
|
| 23 |
+
except git.InvalidGitRepositoryError:
|
| 24 |
+
return None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def guessed_wrong_repo(io, git_root, fnames, git_dname):
|
| 28 |
+
"""After we parse the args, we can determine the real repo. Did we guess wrong?"""
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
check_repo = Path(GitRepo(io, fnames, git_dname).root).resolve()
|
| 32 |
+
except FileNotFoundError:
|
| 33 |
+
return
|
| 34 |
+
|
| 35 |
+
# we had no guess, rely on the "true" repo result
|
| 36 |
+
if not git_root:
|
| 37 |
+
return str(check_repo)
|
| 38 |
+
|
| 39 |
+
git_root = Path(git_root).resolve()
|
| 40 |
+
if check_repo == git_root:
|
| 41 |
+
return
|
| 42 |
+
|
| 43 |
+
return str(check_repo)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def setup_git(git_root, io):
|
| 47 |
+
if git_root:
|
| 48 |
+
return git_root
|
| 49 |
+
|
| 50 |
+
if not io.confirm_ask("No git repo found, create one to track GPT's changes (recommended)?"):
|
| 51 |
+
return
|
| 52 |
+
|
| 53 |
+
git_root = str(Path.cwd().resolve())
|
| 54 |
+
|
| 55 |
+
check_gitignore(git_root, io, False)
|
| 56 |
+
|
| 57 |
+
repo = git.Repo.init(git_root)
|
| 58 |
+
global_git_config = git.GitConfigParser([str(Path.home() / ".gitconfig")], read_only=True)
|
| 59 |
+
with repo.config_writer() as git_config:
|
| 60 |
+
if not global_git_config.has_option("user", "name"):
|
| 61 |
+
git_config.set_value("user", "name", "Your Name")
|
| 62 |
+
io.tool_error('Update git name with: git config --global user.name "Your Name"')
|
| 63 |
+
if not global_git_config.has_option("user", "email"):
|
| 64 |
+
git_config.set_value("user", "email", "you@example.com")
|
| 65 |
+
io.tool_error('Update git email with: git config --global user.email "you@example.com"')
|
| 66 |
+
|
| 67 |
+
io.tool_output("Git repository created in the current working directory.")
|
| 68 |
+
|
| 69 |
+
return repo.working_tree_dir
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def check_gitignore(git_root, io, ask=True):
|
| 73 |
+
if not git_root:
|
| 74 |
+
return
|
| 75 |
+
|
| 76 |
+
pat = ".aider*"
|
| 77 |
+
|
| 78 |
+
gitignore_file = Path(git_root) / ".gitignore"
|
| 79 |
+
if gitignore_file.exists():
|
| 80 |
+
content = io.read_text(gitignore_file)
|
| 81 |
+
if pat in content.splitlines():
|
| 82 |
+
return
|
| 83 |
+
else:
|
| 84 |
+
content = ""
|
| 85 |
+
|
| 86 |
+
if ask and not io.confirm_ask(f"Add {pat} to .gitignore (recommended)?"):
|
| 87 |
+
return
|
| 88 |
+
|
| 89 |
+
if content and not content.endswith("\n"):
|
| 90 |
+
content += "\n"
|
| 91 |
+
content += pat + "\n"
|
| 92 |
+
io.write_text(gitignore_file, content)
|
| 93 |
+
|
| 94 |
+
io.tool_output(f"Added {pat} to .gitignore")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def main(argv=None, input=None, output=None, force_git_root=None):
|
| 98 |
+
if argv is None:
|
| 99 |
+
argv = sys.argv[1:]
|
| 100 |
+
|
| 101 |
+
if force_git_root:
|
| 102 |
+
git_root = force_git_root
|
| 103 |
+
else:
|
| 104 |
+
git_root = get_git_root()
|
| 105 |
+
|
| 106 |
+
conf_fname = Path(".aider.conf.yml")
|
| 107 |
+
|
| 108 |
+
default_config_files = [conf_fname.resolve()] # CWD
|
| 109 |
+
if git_root:
|
| 110 |
+
git_conf = Path(git_root) / conf_fname # git root
|
| 111 |
+
if git_conf not in default_config_files:
|
| 112 |
+
default_config_files.append(git_conf)
|
| 113 |
+
default_config_files.append(Path.home() / conf_fname) # homedir
|
| 114 |
+
default_config_files = list(map(str, default_config_files))
|
| 115 |
+
|
| 116 |
+
parser = configargparse.ArgumentParser(
|
| 117 |
+
description="aider is GPT powered coding in your terminal",
|
| 118 |
+
add_config_file_help=True,
|
| 119 |
+
default_config_files=default_config_files,
|
| 120 |
+
config_file_parser_class=configargparse.YAMLConfigFileParser,
|
| 121 |
+
auto_env_var_prefix="AIDER_",
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
##########
|
| 125 |
+
core_group = parser.add_argument_group("Main")
|
| 126 |
+
core_group.add_argument(
|
| 127 |
+
"files",
|
| 128 |
+
metavar="FILE",
|
| 129 |
+
nargs="*",
|
| 130 |
+
help="the directory of a git repo, or a list of files to edit with GPT (optional)",
|
| 131 |
+
)
|
| 132 |
+
core_group.add_argument(
|
| 133 |
+
"--openai-api-key",
|
| 134 |
+
metavar="OPENAI_API_KEY",
|
| 135 |
+
help="Specify the OpenAI API key",
|
| 136 |
+
env_var="OPENAI_API_KEY",
|
| 137 |
+
)
|
| 138 |
+
core_group.add_argument(
|
| 139 |
+
"--model",
|
| 140 |
+
metavar="MODEL",
|
| 141 |
+
default=models.GPT4.name,
|
| 142 |
+
help=f"Specify the model to use for the main chat (default: {models.GPT4.name})",
|
| 143 |
+
)
|
| 144 |
+
core_group.add_argument(
|
| 145 |
+
"-3",
|
| 146 |
+
action="store_const",
|
| 147 |
+
dest="model",
|
| 148 |
+
const=models.GPT35_16k.name,
|
| 149 |
+
help=f"Use {models.GPT35_16k.name} model for the main chat (gpt-4 is better)",
|
| 150 |
+
)
|
| 151 |
+
core_group.add_argument(
|
| 152 |
+
"--voice-language",
|
| 153 |
+
metavar="VOICE_LANGUAGE",
|
| 154 |
+
default="en",
|
| 155 |
+
help="Specify the language for voice using ISO 639-1 code (default: auto)",
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
##########
|
| 159 |
+
model_group = parser.add_argument_group("Advanced Model Settings")
|
| 160 |
+
model_group.add_argument(
|
| 161 |
+
"--openai-api-base",
|
| 162 |
+
metavar="OPENAI_API_BASE",
|
| 163 |
+
help="Specify the openai.api_base (default: https://api.openai.com/v1)",
|
| 164 |
+
)
|
| 165 |
+
model_group.add_argument(
|
| 166 |
+
"--openai-api-type",
|
| 167 |
+
metavar="OPENAI_API_TYPE",
|
| 168 |
+
help="Specify the openai.api_type",
|
| 169 |
+
)
|
| 170 |
+
model_group.add_argument(
|
| 171 |
+
"--openai-api-version",
|
| 172 |
+
metavar="OPENAI_API_VERSION",
|
| 173 |
+
help="Specify the openai.api_version",
|
| 174 |
+
)
|
| 175 |
+
model_group.add_argument(
|
| 176 |
+
"--openai-api-deployment-id",
|
| 177 |
+
metavar="OPENAI_API_DEPLOYMENT_ID",
|
| 178 |
+
help="Specify the deployment_id arg to be passed to openai.ChatCompletion.create()",
|
| 179 |
+
)
|
| 180 |
+
model_group.add_argument(
|
| 181 |
+
"--openai-api-engine",
|
| 182 |
+
metavar="OPENAI_API_ENGINE",
|
| 183 |
+
help="Specify the engine arg to be passed to openai.ChatCompletion.create()",
|
| 184 |
+
)
|
| 185 |
+
model_group.add_argument(
|
| 186 |
+
"--edit-format",
|
| 187 |
+
metavar="EDIT_FORMAT",
|
| 188 |
+
default=None,
|
| 189 |
+
help="Specify what edit format GPT should use (default depends on model)",
|
| 190 |
+
)
|
| 191 |
+
model_group.add_argument(
|
| 192 |
+
"--map-tokens",
|
| 193 |
+
type=int,
|
| 194 |
+
default=1024,
|
| 195 |
+
help="Max number of tokens to use for repo map, use 0 to disable (default: 1024)",
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
##########
|
| 199 |
+
history_group = parser.add_argument_group("History Files")
|
| 200 |
+
default_input_history_file = (
|
| 201 |
+
os.path.join(git_root, ".aider.input.history") if git_root else ".aider.input.history"
|
| 202 |
+
)
|
| 203 |
+
default_chat_history_file = (
|
| 204 |
+
os.path.join(git_root, ".aider.chat.history.md") if git_root else ".aider.chat.history.md"
|
| 205 |
+
)
|
| 206 |
+
history_group.add_argument(
|
| 207 |
+
"--input-history-file",
|
| 208 |
+
metavar="INPUT_HISTORY_FILE",
|
| 209 |
+
default=default_input_history_file,
|
| 210 |
+
help=f"Specify the chat input history file (default: {default_input_history_file})",
|
| 211 |
+
)
|
| 212 |
+
history_group.add_argument(
|
| 213 |
+
"--chat-history-file",
|
| 214 |
+
metavar="CHAT_HISTORY_FILE",
|
| 215 |
+
default=default_chat_history_file,
|
| 216 |
+
help=f"Specify the chat history file (default: {default_chat_history_file})",
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
##########
|
| 220 |
+
output_group = parser.add_argument_group("Output Settings")
|
| 221 |
+
output_group.add_argument(
|
| 222 |
+
"--dark-mode",
|
| 223 |
+
action="store_true",
|
| 224 |
+
help="Use colors suitable for a dark terminal background (default: False)",
|
| 225 |
+
default=False,
|
| 226 |
+
)
|
| 227 |
+
output_group.add_argument(
|
| 228 |
+
"--light-mode",
|
| 229 |
+
action="store_true",
|
| 230 |
+
help="Use colors suitable for a light terminal background (default: False)",
|
| 231 |
+
default=False,
|
| 232 |
+
)
|
| 233 |
+
output_group.add_argument(
|
| 234 |
+
"--pretty",
|
| 235 |
+
action="store_true",
|
| 236 |
+
default=True,
|
| 237 |
+
help="Enable pretty, colorized output (default: True)",
|
| 238 |
+
)
|
| 239 |
+
output_group.add_argument(
|
| 240 |
+
"--no-pretty",
|
| 241 |
+
action="store_false",
|
| 242 |
+
dest="pretty",
|
| 243 |
+
help="Disable pretty, colorized output",
|
| 244 |
+
)
|
| 245 |
+
output_group.add_argument(
|
| 246 |
+
"--no-stream",
|
| 247 |
+
action="store_false",
|
| 248 |
+
dest="stream",
|
| 249 |
+
default=True,
|
| 250 |
+
help="Disable streaming responses",
|
| 251 |
+
)
|
| 252 |
+
output_group.add_argument(
|
| 253 |
+
"--user-input-color",
|
| 254 |
+
default="#00cc00",
|
| 255 |
+
help="Set the color for user input (default: #00cc00)",
|
| 256 |
+
)
|
| 257 |
+
output_group.add_argument(
|
| 258 |
+
"--tool-output-color",
|
| 259 |
+
default=None,
|
| 260 |
+
help="Set the color for tool output (default: None)",
|
| 261 |
+
)
|
| 262 |
+
output_group.add_argument(
|
| 263 |
+
"--tool-error-color",
|
| 264 |
+
default="#FF2222",
|
| 265 |
+
help="Set the color for tool error messages (default: red)",
|
| 266 |
+
)
|
| 267 |
+
output_group.add_argument(
|
| 268 |
+
"--assistant-output-color",
|
| 269 |
+
default="#0088ff",
|
| 270 |
+
help="Set the color for assistant output (default: #0088ff)",
|
| 271 |
+
)
|
| 272 |
+
output_group.add_argument(
|
| 273 |
+
"--code-theme",
|
| 274 |
+
default="default",
|
| 275 |
+
help=(
|
| 276 |
+
"Set the markdown code theme (default: default, other options include monokai,"
|
| 277 |
+
" solarized-dark, solarized-light)"
|
| 278 |
+
),
|
| 279 |
+
)
|
| 280 |
+
output_group.add_argument(
|
| 281 |
+
"--show-diffs",
|
| 282 |
+
action="store_true",
|
| 283 |
+
help="Show diffs when committing changes (default: False)",
|
| 284 |
+
default=False,
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
##########
|
| 288 |
+
git_group = parser.add_argument_group("Git Settings")
|
| 289 |
+
git_group.add_argument(
|
| 290 |
+
"--no-git",
|
| 291 |
+
action="store_false",
|
| 292 |
+
dest="git",
|
| 293 |
+
default=True,
|
| 294 |
+
help="Do not look for a git repo",
|
| 295 |
+
)
|
| 296 |
+
git_group.add_argument(
|
| 297 |
+
"--auto-commits",
|
| 298 |
+
action="store_true",
|
| 299 |
+
dest="auto_commits",
|
| 300 |
+
default=True,
|
| 301 |
+
help="Enable auto commit of GPT changes (default: True)",
|
| 302 |
+
)
|
| 303 |
+
git_group.add_argument(
|
| 304 |
+
"--no-auto-commits",
|
| 305 |
+
action="store_false",
|
| 306 |
+
dest="auto_commits",
|
| 307 |
+
help="Disable auto commit of GPT changes (implies --no-dirty-commits)",
|
| 308 |
+
)
|
| 309 |
+
git_group.add_argument(
|
| 310 |
+
"--dirty-commits",
|
| 311 |
+
action="store_true",
|
| 312 |
+
dest="dirty_commits",
|
| 313 |
+
help="Enable commits when repo is found dirty",
|
| 314 |
+
default=True,
|
| 315 |
+
)
|
| 316 |
+
git_group.add_argument(
|
| 317 |
+
"--no-dirty-commits",
|
| 318 |
+
action="store_false",
|
| 319 |
+
dest="dirty_commits",
|
| 320 |
+
help="Disable commits when repo is found dirty",
|
| 321 |
+
)
|
| 322 |
+
git_group.add_argument(
|
| 323 |
+
"--dry-run",
|
| 324 |
+
action="store_true",
|
| 325 |
+
help="Perform a dry run without modifying files (default: False)",
|
| 326 |
+
default=False,
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
##########
|
| 330 |
+
other_group = parser.add_argument_group("Other Settings")
|
| 331 |
+
other_group.add_argument(
|
| 332 |
+
"--version",
|
| 333 |
+
action="version",
|
| 334 |
+
version=f"%(prog)s {__version__}",
|
| 335 |
+
help="Show the version number and exit",
|
| 336 |
+
)
|
| 337 |
+
other_group.add_argument(
|
| 338 |
+
"--apply",
|
| 339 |
+
metavar="FILE",
|
| 340 |
+
help="Apply the changes from the given file instead of running the chat (debug)",
|
| 341 |
+
)
|
| 342 |
+
other_group.add_argument(
|
| 343 |
+
"--yes",
|
| 344 |
+
action="store_true",
|
| 345 |
+
help="Always say yes to every confirmation",
|
| 346 |
+
default=None,
|
| 347 |
+
)
|
| 348 |
+
other_group.add_argument(
|
| 349 |
+
"-v",
|
| 350 |
+
"--verbose",
|
| 351 |
+
action="store_true",
|
| 352 |
+
help="Enable verbose output",
|
| 353 |
+
default=False,
|
| 354 |
+
)
|
| 355 |
+
other_group.add_argument(
|
| 356 |
+
"--show-repo-map",
|
| 357 |
+
action="store_true",
|
| 358 |
+
help="Print the repo map and exit (debug)",
|
| 359 |
+
default=False,
|
| 360 |
+
)
|
| 361 |
+
other_group.add_argument(
|
| 362 |
+
"--message",
|
| 363 |
+
"--msg",
|
| 364 |
+
"-m",
|
| 365 |
+
metavar="COMMAND",
|
| 366 |
+
help="Specify a single message to send GPT, process reply then exit (disables chat mode)",
|
| 367 |
+
)
|
| 368 |
+
other_group.add_argument(
|
| 369 |
+
"-c",
|
| 370 |
+
"--config",
|
| 371 |
+
is_config_file=True,
|
| 372 |
+
metavar="CONFIG_FILE",
|
| 373 |
+
help=(
|
| 374 |
+
"Specify the config file (default: search for .aider.conf.yml in git root, cwd"
|
| 375 |
+
" or home directory)"
|
| 376 |
+
),
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
args = parser.parse_args(argv)
|
| 380 |
+
|
| 381 |
+
if args.dark_mode:
|
| 382 |
+
args.user_input_color = "#32FF32"
|
| 383 |
+
args.tool_error_color = "#FF3333"
|
| 384 |
+
args.assistant_output_color = "#00FFFF"
|
| 385 |
+
args.code_theme = "monokai"
|
| 386 |
+
|
| 387 |
+
if args.light_mode:
|
| 388 |
+
args.user_input_color = "green"
|
| 389 |
+
args.tool_error_color = "red"
|
| 390 |
+
args.assistant_output_color = "blue"
|
| 391 |
+
args.code_theme = "default"
|
| 392 |
+
|
| 393 |
+
io = InputOutput(
|
| 394 |
+
args.pretty,
|
| 395 |
+
args.yes,
|
| 396 |
+
args.input_history_file,
|
| 397 |
+
args.chat_history_file,
|
| 398 |
+
input=input,
|
| 399 |
+
output=output,
|
| 400 |
+
user_input_color=args.user_input_color,
|
| 401 |
+
tool_output_color=args.tool_output_color,
|
| 402 |
+
tool_error_color=args.tool_error_color,
|
| 403 |
+
dry_run=args.dry_run,
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
fnames = [str(Path(fn).resolve()) for fn in args.files]
|
| 407 |
+
if len(args.files) > 1:
|
| 408 |
+
good = True
|
| 409 |
+
for fname in args.files:
|
| 410 |
+
if Path(fname).is_dir():
|
| 411 |
+
io.tool_error(f"{fname} is a directory, not provided alone.")
|
| 412 |
+
good = False
|
| 413 |
+
if not good:
|
| 414 |
+
io.tool_error(
|
| 415 |
+
"Provide either a single directory of a git repo, or a list of one or more files."
|
| 416 |
+
)
|
| 417 |
+
return 1
|
| 418 |
+
|
| 419 |
+
git_dname = None
|
| 420 |
+
if len(args.files) == 1:
|
| 421 |
+
if Path(args.files[0]).is_dir():
|
| 422 |
+
if args.git:
|
| 423 |
+
git_dname = str(Path(args.files[0]).resolve())
|
| 424 |
+
fnames = []
|
| 425 |
+
else:
|
| 426 |
+
io.tool_error(f"{args.files[0]} is a directory, but --no-git selected.")
|
| 427 |
+
return 1
|
| 428 |
+
|
| 429 |
+
# We can't know the git repo for sure until after parsing the args.
|
| 430 |
+
# If we guessed wrong, reparse because that changes things like
|
| 431 |
+
# the location of the config.yml and history files.
|
| 432 |
+
if args.git and not force_git_root:
|
| 433 |
+
right_repo_root = guessed_wrong_repo(io, git_root, fnames, git_dname)
|
| 434 |
+
if right_repo_root:
|
| 435 |
+
return main(argv, input, output, right_repo_root)
|
| 436 |
+
|
| 437 |
+
io.tool_output(f"Aider v{__version__}")
|
| 438 |
+
|
| 439 |
+
check_version(io.tool_error)
|
| 440 |
+
|
| 441 |
+
if "VSCODE_GIT_IPC_HANDLE" in os.environ:
|
| 442 |
+
args.pretty = False
|
| 443 |
+
io.tool_output("VSCode terminal detected, pretty output has been disabled.")
|
| 444 |
+
|
| 445 |
+
if args.git:
|
| 446 |
+
git_root = setup_git(git_root, io)
|
| 447 |
+
check_gitignore(git_root, io)
|
| 448 |
+
|
| 449 |
+
def scrub_sensitive_info(text):
|
| 450 |
+
# Replace sensitive information with placeholder
|
| 451 |
+
return text.replace(args.openai_api_key, "***")
|
| 452 |
+
|
| 453 |
+
if args.verbose:
|
| 454 |
+
show = scrub_sensitive_info(parser.format_values())
|
| 455 |
+
io.tool_output(show)
|
| 456 |
+
io.tool_output("Option settings:")
|
| 457 |
+
for arg, val in sorted(vars(args).items()):
|
| 458 |
+
io.tool_output(f" - {arg}: {scrub_sensitive_info(str(val))}")
|
| 459 |
+
|
| 460 |
+
io.tool_output(*sys.argv, log_only=True)
|
| 461 |
+
|
| 462 |
+
if not args.openai_api_key:
|
| 463 |
+
if os.name == "nt":
|
| 464 |
+
io.tool_error(
|
| 465 |
+
"No OpenAI API key provided. Use --openai-api-key or setx OPENAI_API_KEY."
|
| 466 |
+
)
|
| 467 |
+
else:
|
| 468 |
+
io.tool_error(
|
| 469 |
+
"No OpenAI API key provided. Use --openai-api-key or export OPENAI_API_KEY."
|
| 470 |
+
)
|
| 471 |
+
return 1
|
| 472 |
+
|
| 473 |
+
main_model = models.Model(args.model)
|
| 474 |
+
|
| 475 |
+
openai.api_key = args.openai_api_key
|
| 476 |
+
for attr in ("base", "type", "version", "deployment_id", "engine"):
|
| 477 |
+
arg_key = f"openai_api_{attr}"
|
| 478 |
+
val = getattr(args, arg_key)
|
| 479 |
+
if val is not None:
|
| 480 |
+
mod_key = f"api_{attr}"
|
| 481 |
+
setattr(openai, mod_key, val)
|
| 482 |
+
io.tool_output(f"Setting openai.{mod_key}={val}")
|
| 483 |
+
|
| 484 |
+
try:
|
| 485 |
+
coder = Coder.create(
|
| 486 |
+
main_model,
|
| 487 |
+
args.edit_format,
|
| 488 |
+
io,
|
| 489 |
+
##
|
| 490 |
+
fnames=fnames,
|
| 491 |
+
git_dname=git_dname,
|
| 492 |
+
pretty=args.pretty,
|
| 493 |
+
show_diffs=args.show_diffs,
|
| 494 |
+
auto_commits=args.auto_commits,
|
| 495 |
+
dirty_commits=args.dirty_commits,
|
| 496 |
+
dry_run=args.dry_run,
|
| 497 |
+
map_tokens=args.map_tokens,
|
| 498 |
+
verbose=args.verbose,
|
| 499 |
+
assistant_output_color=args.assistant_output_color,
|
| 500 |
+
code_theme=args.code_theme,
|
| 501 |
+
stream=args.stream,
|
| 502 |
+
use_git=args.git,
|
| 503 |
+
voice_language=args.voice_language,
|
| 504 |
+
)
|
| 505 |
+
except ValueError as err:
|
| 506 |
+
io.tool_error(str(err))
|
| 507 |
+
return 1
|
| 508 |
+
|
| 509 |
+
if args.show_repo_map:
|
| 510 |
+
repo_map = coder.get_repo_map()
|
| 511 |
+
if repo_map:
|
| 512 |
+
io.tool_output(repo_map)
|
| 513 |
+
return
|
| 514 |
+
|
| 515 |
+
if args.apply:
|
| 516 |
+
content = io.read_text(args.apply)
|
| 517 |
+
if content is None:
|
| 518 |
+
return
|
| 519 |
+
coder.partial_response_content = content
|
| 520 |
+
coder.apply_updates()
|
| 521 |
+
return
|
| 522 |
+
|
| 523 |
+
io.tool_output("Use /help to see in-chat commands, run with --help to see cmd line args")
|
| 524 |
+
|
| 525 |
+
coder.dirty_commit()
|
| 526 |
+
|
| 527 |
+
if args.message:
|
| 528 |
+
io.tool_output()
|
| 529 |
+
coder.run(with_message=args.message)
|
| 530 |
+
else:
|
| 531 |
+
coder.run()
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
if __name__ == "__main__":
|
| 535 |
+
status = main()
|
| 536 |
+
sys.exit(status)
|
testbed/Aider-AI__aider/aider/models.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
known_tokens = {
|
| 4 |
+
"gpt-3.5-turbo": 4,
|
| 5 |
+
"gpt-4": 8,
|
| 6 |
+
}
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Model:
|
| 10 |
+
always_available = False
|
| 11 |
+
use_repo_map = False
|
| 12 |
+
send_undo_reply = False
|
| 13 |
+
|
| 14 |
+
prompt_price = None
|
| 15 |
+
completion_price = None
|
| 16 |
+
|
| 17 |
+
def __init__(self, name):
|
| 18 |
+
self.name = name
|
| 19 |
+
|
| 20 |
+
tokens = None
|
| 21 |
+
|
| 22 |
+
match = re.search(r"-([0-9]+)k", name)
|
| 23 |
+
if match:
|
| 24 |
+
tokens = int(match.group(1))
|
| 25 |
+
else:
|
| 26 |
+
for m, t in known_tokens.items():
|
| 27 |
+
if name.startswith(m):
|
| 28 |
+
tokens = t
|
| 29 |
+
|
| 30 |
+
if tokens is None:
|
| 31 |
+
raise ValueError(f"Unknown context window size for model: {name}")
|
| 32 |
+
|
| 33 |
+
self.max_context_tokens = tokens * 1024
|
| 34 |
+
|
| 35 |
+
if self.is_gpt4():
|
| 36 |
+
self.edit_format = "diff"
|
| 37 |
+
self.use_repo_map = True
|
| 38 |
+
self.send_undo_reply = True
|
| 39 |
+
|
| 40 |
+
if tokens == 8:
|
| 41 |
+
self.prompt_price = 0.03
|
| 42 |
+
self.completion_price = 0.06
|
| 43 |
+
elif tokens == 32:
|
| 44 |
+
self.prompt_price = 0.06
|
| 45 |
+
self.completion_price = 0.12
|
| 46 |
+
|
| 47 |
+
return
|
| 48 |
+
|
| 49 |
+
if self.is_gpt35():
|
| 50 |
+
self.edit_format = "whole"
|
| 51 |
+
self.always_available = True
|
| 52 |
+
|
| 53 |
+
if tokens == 4:
|
| 54 |
+
self.prompt_price = 0.0015
|
| 55 |
+
self.completion_price = 0.002
|
| 56 |
+
elif tokens == 16:
|
| 57 |
+
self.prompt_price = 0.003
|
| 58 |
+
self.completion_price = 0.004
|
| 59 |
+
|
| 60 |
+
return
|
| 61 |
+
|
| 62 |
+
raise ValueError(f"Unsupported model: {name}")
|
| 63 |
+
|
| 64 |
+
def is_gpt4(self):
|
| 65 |
+
return self.name.startswith("gpt-4")
|
| 66 |
+
|
| 67 |
+
def is_gpt35(self):
|
| 68 |
+
return self.name.startswith("gpt-3.5-turbo")
|
| 69 |
+
|
| 70 |
+
def __str__(self):
|
| 71 |
+
return self.name
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
GPT4 = Model("gpt-4")
|
| 75 |
+
GPT35 = Model("gpt-3.5-turbo")
|
| 76 |
+
GPT35_16k = Model("gpt-3.5-turbo-16k")
|
testbed/Aider-AI__aider/aider/prompts.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa: E501
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
# COMMIT
|
| 5 |
+
commit_system = """You are an expert software engineer.
|
| 6 |
+
Review the provided context and diffs which are about to be committed to a git repo.
|
| 7 |
+
Generate a *SHORT* 1 line, 1 sentence commit message that describes the purpose of the changes.
|
| 8 |
+
The commit message MUST be in the past tense.
|
| 9 |
+
It must describe the changes *which have been made* in the diffs!
|
| 10 |
+
Reply with JUST the commit message, without quotes, comments, questions, etc!
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
# COMMANDS
|
| 14 |
+
undo_command_reply = "I did `git reset --hard HEAD~1` to discard the last edits."
|
| 15 |
+
|
| 16 |
+
added_files = "I added these *read-write* files: {fnames}"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
run_output = """I ran this command:
|
| 20 |
+
|
| 21 |
+
{command}
|
| 22 |
+
|
| 23 |
+
And got this output:
|
| 24 |
+
|
| 25 |
+
{output}
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
# CHAT HISTORY
|
| 29 |
+
summarize = """*Briefly* summarize this partial conversation about programming.
|
| 30 |
+
Include less detail about older parts and more detail about the most recent messages.
|
| 31 |
+
Start a new paragraph every time the topic changes!
|
| 32 |
+
|
| 33 |
+
This is only part of a longer conversation so *DO NOT* conclude the summary with language like "Finally, ...". Because the conversation continues after the summary.
|
| 34 |
+
The summary *MUST* include the function names, libraries, packages that are being discussed.
|
| 35 |
+
The summary *MUST* include the filenames that are being referenced by the assistant inside the ```...``` fenced code blocks!
|
| 36 |
+
The summaries *MUST NOT* include ```...``` fenced code blocks!
|
| 37 |
+
|
| 38 |
+
Phrase the summary with the USER in first person, telling the ASSISTANT about the conversation.
|
| 39 |
+
Write *as* the user.
|
| 40 |
+
The user should refer to the assistant as *you*.
|
| 41 |
+
Start the summary with "I asked you...".
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
summary_prefix = "I spoke to you previously about a number of things.\n"
|
testbed/Aider-AI__aider/aider/repo.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path, PurePosixPath
|
| 3 |
+
|
| 4 |
+
import git
|
| 5 |
+
|
| 6 |
+
from aider import models, prompts, utils
|
| 7 |
+
from aider.sendchat import simple_send_with_retries
|
| 8 |
+
|
| 9 |
+
from .dump import dump # noqa: F401
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class GitRepo:
|
| 13 |
+
repo = None
|
| 14 |
+
|
| 15 |
+
def __init__(self, io, fnames, git_dname):
|
| 16 |
+
self.io = io
|
| 17 |
+
|
| 18 |
+
if git_dname:
|
| 19 |
+
check_fnames = [git_dname]
|
| 20 |
+
elif fnames:
|
| 21 |
+
check_fnames = fnames
|
| 22 |
+
else:
|
| 23 |
+
check_fnames = ["."]
|
| 24 |
+
|
| 25 |
+
repo_paths = []
|
| 26 |
+
for fname in check_fnames:
|
| 27 |
+
fname = Path(fname)
|
| 28 |
+
fname = fname.resolve()
|
| 29 |
+
|
| 30 |
+
if not fname.exists() and fname.parent.exists():
|
| 31 |
+
fname = fname.parent
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
repo_path = git.Repo(fname, search_parent_directories=True).working_dir
|
| 35 |
+
repo_path = utils.safe_abs_path(repo_path)
|
| 36 |
+
repo_paths.append(repo_path)
|
| 37 |
+
except git.exc.InvalidGitRepositoryError:
|
| 38 |
+
pass
|
| 39 |
+
|
| 40 |
+
num_repos = len(set(repo_paths))
|
| 41 |
+
|
| 42 |
+
if num_repos == 0:
|
| 43 |
+
raise FileNotFoundError
|
| 44 |
+
if num_repos > 1:
|
| 45 |
+
self.io.tool_error("Files are in different git repos.")
|
| 46 |
+
raise FileNotFoundError
|
| 47 |
+
|
| 48 |
+
# https://github.com/gitpython-developers/GitPython/issues/427
|
| 49 |
+
self.repo = git.Repo(repo_paths.pop(), odbt=git.GitDB)
|
| 50 |
+
self.root = utils.safe_abs_path(self.repo.working_tree_dir)
|
| 51 |
+
|
| 52 |
+
def add_new_files(self, fnames):
|
| 53 |
+
cur_files = [str(Path(fn).resolve()) for fn in self.get_tracked_files()]
|
| 54 |
+
for fname in fnames:
|
| 55 |
+
if str(Path(fname).resolve()) in cur_files:
|
| 56 |
+
continue
|
| 57 |
+
if not Path(fname).exists():
|
| 58 |
+
continue
|
| 59 |
+
self.io.tool_output(f"Adding {fname} to git")
|
| 60 |
+
self.repo.git.add(fname)
|
| 61 |
+
|
| 62 |
+
def commit(self, context=None, prefix=None, message=None):
|
| 63 |
+
if not self.repo.is_dirty():
|
| 64 |
+
return
|
| 65 |
+
|
| 66 |
+
if message:
|
| 67 |
+
commit_message = message
|
| 68 |
+
else:
|
| 69 |
+
diffs = self.get_diffs(False)
|
| 70 |
+
commit_message = self.get_commit_message(diffs, context)
|
| 71 |
+
|
| 72 |
+
if not commit_message:
|
| 73 |
+
commit_message = "(no commit message provided)"
|
| 74 |
+
|
| 75 |
+
if prefix:
|
| 76 |
+
commit_message = prefix + commit_message
|
| 77 |
+
|
| 78 |
+
full_commit_message = commit_message
|
| 79 |
+
if context:
|
| 80 |
+
full_commit_message += "\n\n# Aider chat conversation:\n\n" + context
|
| 81 |
+
|
| 82 |
+
self.repo.git.commit("-a", "-m", full_commit_message, "--no-verify")
|
| 83 |
+
commit_hash = self.repo.head.commit.hexsha[:7]
|
| 84 |
+
self.io.tool_output(f"Commit {commit_hash} {commit_message}")
|
| 85 |
+
|
| 86 |
+
return commit_hash, commit_message
|
| 87 |
+
|
| 88 |
+
def get_rel_repo_dir(self):
|
| 89 |
+
try:
|
| 90 |
+
return os.path.relpath(self.repo.git_dir, os.getcwd())
|
| 91 |
+
except ValueError:
|
| 92 |
+
return self.repo.git_dir
|
| 93 |
+
|
| 94 |
+
def get_commit_message(self, diffs, context):
|
| 95 |
+
if len(diffs) >= 4 * 1024 * 4:
|
| 96 |
+
self.io.tool_error(
|
| 97 |
+
f"Diff is too large for {models.GPT35.name} to generate a commit message."
|
| 98 |
+
)
|
| 99 |
+
return
|
| 100 |
+
|
| 101 |
+
diffs = "# Diffs:\n" + diffs
|
| 102 |
+
|
| 103 |
+
content = ""
|
| 104 |
+
if context:
|
| 105 |
+
content += context + "\n"
|
| 106 |
+
content += diffs
|
| 107 |
+
|
| 108 |
+
messages = [
|
| 109 |
+
dict(role="system", content=prompts.commit_system),
|
| 110 |
+
dict(role="user", content=content),
|
| 111 |
+
]
|
| 112 |
+
|
| 113 |
+
for model in [models.GPT35.name, models.GPT35_16k.name]:
|
| 114 |
+
commit_message = simple_send_with_retries(model, messages)
|
| 115 |
+
if commit_message:
|
| 116 |
+
break
|
| 117 |
+
|
| 118 |
+
if not commit_message:
|
| 119 |
+
self.io.tool_error("Failed to generate commit message!")
|
| 120 |
+
return
|
| 121 |
+
|
| 122 |
+
commit_message = commit_message.strip()
|
| 123 |
+
if commit_message and commit_message[0] == '"' and commit_message[-1] == '"':
|
| 124 |
+
commit_message = commit_message[1:-1].strip()
|
| 125 |
+
|
| 126 |
+
return commit_message
|
| 127 |
+
|
| 128 |
+
def get_diffs(self, pretty, *args):
|
| 129 |
+
args = list(args)
|
| 130 |
+
|
| 131 |
+
# if args are specified, just add --pretty if needed
|
| 132 |
+
if args:
|
| 133 |
+
if pretty:
|
| 134 |
+
args = ["--color"] + args
|
| 135 |
+
return self.repo.git.diff(*args)
|
| 136 |
+
|
| 137 |
+
# otherwise, we always want diffs of index and working dir
|
| 138 |
+
|
| 139 |
+
try:
|
| 140 |
+
commits = self.repo.iter_commits(self.repo.active_branch)
|
| 141 |
+
current_branch_has_commits = any(commits)
|
| 142 |
+
except git.exc.GitCommandError:
|
| 143 |
+
current_branch_has_commits = False
|
| 144 |
+
|
| 145 |
+
if pretty:
|
| 146 |
+
args = ["--color"]
|
| 147 |
+
|
| 148 |
+
if current_branch_has_commits:
|
| 149 |
+
# if there is a HEAD, just diff against it to pick up index + working
|
| 150 |
+
args += ["HEAD"]
|
| 151 |
+
return self.repo.git.diff(*args)
|
| 152 |
+
|
| 153 |
+
# diffs in the index
|
| 154 |
+
diffs = self.repo.git.diff(*(args + ["--cached"]))
|
| 155 |
+
# plus, diffs in the working dir
|
| 156 |
+
diffs += self.repo.git.diff(*args)
|
| 157 |
+
|
| 158 |
+
return diffs
|
| 159 |
+
|
| 160 |
+
def show_diffs(self, pretty):
|
| 161 |
+
diffs = self.get_diffs(pretty)
|
| 162 |
+
print(diffs)
|
| 163 |
+
|
| 164 |
+
def get_tracked_files(self):
|
| 165 |
+
if not self.repo:
|
| 166 |
+
return []
|
| 167 |
+
|
| 168 |
+
try:
|
| 169 |
+
commit = self.repo.head.commit
|
| 170 |
+
except ValueError:
|
| 171 |
+
commit = None
|
| 172 |
+
|
| 173 |
+
files = []
|
| 174 |
+
if commit:
|
| 175 |
+
for blob in commit.tree.traverse():
|
| 176 |
+
if blob.type == "blob": # blob is a file
|
| 177 |
+
files.append(blob.path)
|
| 178 |
+
|
| 179 |
+
# Add staged files
|
| 180 |
+
index = self.repo.index
|
| 181 |
+
staged_files = [path for path, _ in index.entries.keys()]
|
| 182 |
+
|
| 183 |
+
files.extend(staged_files)
|
| 184 |
+
|
| 185 |
+
# convert to appropriate os.sep, since git always normalizes to /
|
| 186 |
+
res = set(
|
| 187 |
+
str(Path(PurePosixPath((Path(self.root) / path).relative_to(self.root))))
|
| 188 |
+
for path in files
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
return res
|
| 192 |
+
|
| 193 |
+
def is_dirty(self):
|
| 194 |
+
return self.repo.is_dirty()
|
testbed/Aider-AI__aider/aider/repomap.py
ADDED
|
@@ -0,0 +1,471 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import colorsys
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import random
|
| 5 |
+
import subprocess
|
| 6 |
+
import sys
|
| 7 |
+
import tempfile
|
| 8 |
+
from collections import Counter, defaultdict
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import networkx as nx
|
| 12 |
+
import tiktoken
|
| 13 |
+
from diskcache import Cache
|
| 14 |
+
from pygments.lexers import guess_lexer_for_filename
|
| 15 |
+
from pygments.token import Token
|
| 16 |
+
from pygments.util import ClassNotFound
|
| 17 |
+
from tqdm import tqdm
|
| 18 |
+
|
| 19 |
+
from aider import models
|
| 20 |
+
|
| 21 |
+
from .dump import dump # noqa: F402
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def to_tree(tags):
|
| 25 |
+
if not tags:
|
| 26 |
+
return ""
|
| 27 |
+
|
| 28 |
+
tags = sorted(tags)
|
| 29 |
+
|
| 30 |
+
output = ""
|
| 31 |
+
last = [None] * len(tags[0])
|
| 32 |
+
tab = "\t"
|
| 33 |
+
for tag in tags:
|
| 34 |
+
tag = list(tag)
|
| 35 |
+
|
| 36 |
+
for i in range(len(last) + 1):
|
| 37 |
+
if i == len(last):
|
| 38 |
+
break
|
| 39 |
+
if last[i] != tag[i]:
|
| 40 |
+
break
|
| 41 |
+
|
| 42 |
+
num_common = i
|
| 43 |
+
|
| 44 |
+
indent = tab * num_common
|
| 45 |
+
rest = tag[num_common:]
|
| 46 |
+
for item in rest:
|
| 47 |
+
output += indent + item + "\n"
|
| 48 |
+
indent += tab
|
| 49 |
+
last = tag
|
| 50 |
+
|
| 51 |
+
return output
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def fname_to_components(fname, with_colon):
|
| 55 |
+
path_components = fname.split(os.sep)
|
| 56 |
+
res = [pc + os.sep for pc in path_components[:-1]]
|
| 57 |
+
if with_colon:
|
| 58 |
+
res.append(path_components[-1] + ":")
|
| 59 |
+
else:
|
| 60 |
+
res.append(path_components[-1])
|
| 61 |
+
return res
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class RepoMap:
|
| 65 |
+
CACHE_VERSION = 1
|
| 66 |
+
ctags_cmd = [
|
| 67 |
+
"ctags",
|
| 68 |
+
"--fields=+S",
|
| 69 |
+
"--extras=-F",
|
| 70 |
+
"--output-format=json",
|
| 71 |
+
"--output-encoding=utf-8",
|
| 72 |
+
]
|
| 73 |
+
IDENT_CACHE_DIR = f".aider.ident.cache.v{CACHE_VERSION}"
|
| 74 |
+
TAGS_CACHE_DIR = f".aider.tags.cache.v{CACHE_VERSION}"
|
| 75 |
+
|
| 76 |
+
ctags_disabled_reason = "ctags not initialized"
|
| 77 |
+
|
| 78 |
+
cache_missing = False
|
| 79 |
+
|
| 80 |
+
def __init__(
|
| 81 |
+
self,
|
| 82 |
+
map_tokens=1024,
|
| 83 |
+
root=None,
|
| 84 |
+
main_model=models.GPT4,
|
| 85 |
+
io=None,
|
| 86 |
+
repo_content_prefix=None,
|
| 87 |
+
verbose=False,
|
| 88 |
+
):
|
| 89 |
+
self.io = io
|
| 90 |
+
self.verbose = verbose
|
| 91 |
+
|
| 92 |
+
if not root:
|
| 93 |
+
root = os.getcwd()
|
| 94 |
+
self.root = root
|
| 95 |
+
|
| 96 |
+
self.load_ident_cache()
|
| 97 |
+
self.load_tags_cache()
|
| 98 |
+
|
| 99 |
+
self.max_map_tokens = map_tokens
|
| 100 |
+
self.has_ctags = self.check_for_ctags()
|
| 101 |
+
|
| 102 |
+
if map_tokens > 0 and self.has_ctags:
|
| 103 |
+
self.use_ctags = True
|
| 104 |
+
else:
|
| 105 |
+
self.use_ctags = False
|
| 106 |
+
|
| 107 |
+
self.tokenizer = tiktoken.encoding_for_model(main_model.name)
|
| 108 |
+
self.repo_content_prefix = repo_content_prefix
|
| 109 |
+
|
| 110 |
+
def get_repo_map(self, chat_files, other_files):
|
| 111 |
+
res = self.choose_files_listing(chat_files, other_files)
|
| 112 |
+
if not res:
|
| 113 |
+
return
|
| 114 |
+
|
| 115 |
+
files_listing, ctags_msg = res
|
| 116 |
+
|
| 117 |
+
if chat_files:
|
| 118 |
+
other = "other "
|
| 119 |
+
else:
|
| 120 |
+
other = ""
|
| 121 |
+
|
| 122 |
+
if self.repo_content_prefix:
|
| 123 |
+
repo_content = self.repo_content_prefix.format(
|
| 124 |
+
other=other,
|
| 125 |
+
ctags_msg=ctags_msg,
|
| 126 |
+
)
|
| 127 |
+
else:
|
| 128 |
+
repo_content = ""
|
| 129 |
+
|
| 130 |
+
repo_content += files_listing
|
| 131 |
+
|
| 132 |
+
return repo_content
|
| 133 |
+
|
| 134 |
+
def choose_files_listing(self, chat_files, other_files):
|
| 135 |
+
if self.max_map_tokens <= 0:
|
| 136 |
+
return
|
| 137 |
+
|
| 138 |
+
if not other_files:
|
| 139 |
+
return
|
| 140 |
+
|
| 141 |
+
if self.use_ctags:
|
| 142 |
+
files_listing = self.get_ranked_tags_map(chat_files, other_files)
|
| 143 |
+
if files_listing:
|
| 144 |
+
num_tokens = self.token_count(files_listing)
|
| 145 |
+
if self.verbose:
|
| 146 |
+
self.io.tool_output(f"ctags map: {num_tokens/1024:.1f} k-tokens")
|
| 147 |
+
ctags_msg = " with selected ctags info"
|
| 148 |
+
return files_listing, ctags_msg
|
| 149 |
+
|
| 150 |
+
files_listing = self.get_simple_files_map(other_files)
|
| 151 |
+
ctags_msg = ""
|
| 152 |
+
num_tokens = self.token_count(files_listing)
|
| 153 |
+
if self.verbose:
|
| 154 |
+
self.io.tool_output(f"simple map: {num_tokens/1024:.1f} k-tokens")
|
| 155 |
+
if num_tokens < self.max_map_tokens:
|
| 156 |
+
return files_listing, ctags_msg
|
| 157 |
+
|
| 158 |
+
def get_simple_files_map(self, other_files):
|
| 159 |
+
fnames = []
|
| 160 |
+
for fname in other_files:
|
| 161 |
+
fname = self.get_rel_fname(fname)
|
| 162 |
+
fname = fname_to_components(fname, False)
|
| 163 |
+
fnames.append(fname)
|
| 164 |
+
|
| 165 |
+
return to_tree(fnames)
|
| 166 |
+
|
| 167 |
+
def token_count(self, string):
|
| 168 |
+
return len(self.tokenizer.encode(string))
|
| 169 |
+
|
| 170 |
+
def get_rel_fname(self, fname):
|
| 171 |
+
return os.path.relpath(fname, self.root)
|
| 172 |
+
|
| 173 |
+
def split_path(self, path):
|
| 174 |
+
path = os.path.relpath(path, self.root)
|
| 175 |
+
return [path + ":"]
|
| 176 |
+
|
| 177 |
+
def run_ctags(self, filename):
|
| 178 |
+
# Check if the file is in the cache and if the modification time has not changed
|
| 179 |
+
file_mtime = self.get_mtime(filename)
|
| 180 |
+
if file_mtime is None:
|
| 181 |
+
return []
|
| 182 |
+
|
| 183 |
+
cache_key = filename
|
| 184 |
+
if cache_key in self.TAGS_CACHE and self.TAGS_CACHE[cache_key]["mtime"] == file_mtime:
|
| 185 |
+
return self.TAGS_CACHE[cache_key]["data"]
|
| 186 |
+
|
| 187 |
+
cmd = self.ctags_cmd + [
|
| 188 |
+
f"--input-encoding={self.io.encoding}",
|
| 189 |
+
filename,
|
| 190 |
+
]
|
| 191 |
+
output = subprocess.check_output(cmd, stderr=subprocess.PIPE).decode("utf-8")
|
| 192 |
+
output_lines = output.splitlines()
|
| 193 |
+
|
| 194 |
+
data = []
|
| 195 |
+
for line in output_lines:
|
| 196 |
+
try:
|
| 197 |
+
data.append(json.loads(line))
|
| 198 |
+
except json.decoder.JSONDecodeError as err:
|
| 199 |
+
self.io.tool_error(f"Error parsing ctags output: {err}")
|
| 200 |
+
self.io.tool_error(repr(line))
|
| 201 |
+
|
| 202 |
+
# Update the cache
|
| 203 |
+
self.TAGS_CACHE[cache_key] = {"mtime": file_mtime, "data": data}
|
| 204 |
+
self.save_tags_cache()
|
| 205 |
+
return data
|
| 206 |
+
|
| 207 |
+
def check_for_ctags(self):
|
| 208 |
+
try:
|
| 209 |
+
executable = self.ctags_cmd[0]
|
| 210 |
+
cmd = [executable, "--version"]
|
| 211 |
+
output = subprocess.check_output(cmd, stderr=subprocess.PIPE).decode("utf-8")
|
| 212 |
+
output = output.lower()
|
| 213 |
+
|
| 214 |
+
cmd = " ".join(cmd)
|
| 215 |
+
|
| 216 |
+
if "universal ctags" not in output:
|
| 217 |
+
self.ctags_disabled_reason = f"{cmd} does not claim to be universal ctags"
|
| 218 |
+
return
|
| 219 |
+
if "+json" not in output:
|
| 220 |
+
self.ctags_disabled_reason = f"{cmd} does not list +json support"
|
| 221 |
+
return
|
| 222 |
+
|
| 223 |
+
with tempfile.TemporaryDirectory() as tempdir:
|
| 224 |
+
hello_py = os.path.join(tempdir, "hello.py")
|
| 225 |
+
with open(hello_py, "w", encoding="utf-8") as f:
|
| 226 |
+
f.write("def hello():\n print('Hello, world!')\n")
|
| 227 |
+
self.run_ctags(hello_py)
|
| 228 |
+
except FileNotFoundError:
|
| 229 |
+
self.ctags_disabled_reason = f"{executable} executable not found"
|
| 230 |
+
return
|
| 231 |
+
except Exception as err:
|
| 232 |
+
self.ctags_disabled_reason = f"error running universal-ctags: {err}"
|
| 233 |
+
return
|
| 234 |
+
|
| 235 |
+
return True
|
| 236 |
+
|
| 237 |
+
def load_tags_cache(self):
|
| 238 |
+
path = Path(self.root) / self.TAGS_CACHE_DIR
|
| 239 |
+
if not path.exists():
|
| 240 |
+
self.cache_missing = True
|
| 241 |
+
self.TAGS_CACHE = Cache(path)
|
| 242 |
+
|
| 243 |
+
def save_tags_cache(self):
|
| 244 |
+
pass
|
| 245 |
+
|
| 246 |
+
def load_ident_cache(self):
|
| 247 |
+
path = Path(self.root) / self.IDENT_CACHE_DIR
|
| 248 |
+
if not path.exists():
|
| 249 |
+
self.cache_missing = True
|
| 250 |
+
self.IDENT_CACHE = Cache(path)
|
| 251 |
+
|
| 252 |
+
def save_ident_cache(self):
|
| 253 |
+
pass
|
| 254 |
+
|
| 255 |
+
def get_mtime(self, fname):
|
| 256 |
+
try:
|
| 257 |
+
return os.path.getmtime(fname)
|
| 258 |
+
except FileNotFoundError:
|
| 259 |
+
self.io.tool_error(f"File not found error: {fname}")
|
| 260 |
+
|
| 261 |
+
def get_name_identifiers(self, fname, uniq=True):
|
| 262 |
+
file_mtime = self.get_mtime(fname)
|
| 263 |
+
if file_mtime is None:
|
| 264 |
+
return set()
|
| 265 |
+
|
| 266 |
+
cache_key = fname
|
| 267 |
+
if cache_key in self.IDENT_CACHE and self.IDENT_CACHE[cache_key]["mtime"] == file_mtime:
|
| 268 |
+
idents = self.IDENT_CACHE[cache_key]["data"]
|
| 269 |
+
else:
|
| 270 |
+
idents = self.get_name_identifiers_uncached(fname)
|
| 271 |
+
self.IDENT_CACHE[cache_key] = {"mtime": file_mtime, "data": idents}
|
| 272 |
+
self.save_ident_cache()
|
| 273 |
+
|
| 274 |
+
if uniq:
|
| 275 |
+
idents = set(idents)
|
| 276 |
+
return idents
|
| 277 |
+
|
| 278 |
+
def get_name_identifiers_uncached(self, fname):
|
| 279 |
+
content = self.io.read_text(fname)
|
| 280 |
+
if content is None:
|
| 281 |
+
return list()
|
| 282 |
+
|
| 283 |
+
try:
|
| 284 |
+
lexer = guess_lexer_for_filename(fname, content)
|
| 285 |
+
except ClassNotFound:
|
| 286 |
+
return list()
|
| 287 |
+
|
| 288 |
+
# lexer.get_tokens_unprocessed() returns (char position in file, token type, token string)
|
| 289 |
+
tokens = list(lexer.get_tokens_unprocessed(content))
|
| 290 |
+
res = [token[2] for token in tokens if token[1] in Token.Name]
|
| 291 |
+
return res
|
| 292 |
+
|
| 293 |
+
def get_ranked_tags(self, chat_fnames, other_fnames):
|
| 294 |
+
defines = defaultdict(set)
|
| 295 |
+
references = defaultdict(list)
|
| 296 |
+
definitions = defaultdict(set)
|
| 297 |
+
|
| 298 |
+
personalization = dict()
|
| 299 |
+
|
| 300 |
+
fnames = set(chat_fnames).union(set(other_fnames))
|
| 301 |
+
chat_rel_fnames = set()
|
| 302 |
+
|
| 303 |
+
fnames = sorted(fnames)
|
| 304 |
+
|
| 305 |
+
if self.cache_missing:
|
| 306 |
+
fnames = tqdm(fnames)
|
| 307 |
+
self.cache_missing = False
|
| 308 |
+
|
| 309 |
+
for fname in fnames:
|
| 310 |
+
if not Path(fname).is_file():
|
| 311 |
+
self.io.tool_error(f"Repo-map can't include {fname}")
|
| 312 |
+
continue
|
| 313 |
+
|
| 314 |
+
# dump(fname)
|
| 315 |
+
rel_fname = os.path.relpath(fname, self.root)
|
| 316 |
+
|
| 317 |
+
if fname in chat_fnames:
|
| 318 |
+
personalization[rel_fname] = 1.0
|
| 319 |
+
chat_rel_fnames.add(rel_fname)
|
| 320 |
+
|
| 321 |
+
data = self.run_ctags(fname)
|
| 322 |
+
|
| 323 |
+
for tag in data:
|
| 324 |
+
ident = tag["name"]
|
| 325 |
+
defines[ident].add(rel_fname)
|
| 326 |
+
|
| 327 |
+
scope = tag.get("scope")
|
| 328 |
+
kind = tag.get("kind")
|
| 329 |
+
name = tag.get("name")
|
| 330 |
+
signature = tag.get("signature")
|
| 331 |
+
|
| 332 |
+
last = name
|
| 333 |
+
if signature:
|
| 334 |
+
last += " " + signature
|
| 335 |
+
|
| 336 |
+
res = [rel_fname]
|
| 337 |
+
if scope:
|
| 338 |
+
res.append(scope)
|
| 339 |
+
res += [kind, last]
|
| 340 |
+
|
| 341 |
+
key = (rel_fname, ident)
|
| 342 |
+
definitions[key].add(tuple(res))
|
| 343 |
+
# definitions[key].add((rel_fname,))
|
| 344 |
+
|
| 345 |
+
idents = self.get_name_identifiers(fname, uniq=False)
|
| 346 |
+
for ident in idents:
|
| 347 |
+
# dump("ref", fname, ident)
|
| 348 |
+
references[ident].append(rel_fname)
|
| 349 |
+
|
| 350 |
+
idents = set(defines.keys()).intersection(set(references.keys()))
|
| 351 |
+
|
| 352 |
+
G = nx.MultiDiGraph()
|
| 353 |
+
|
| 354 |
+
for ident in idents:
|
| 355 |
+
definers = defines[ident]
|
| 356 |
+
for referencer, num_refs in Counter(references[ident]).items():
|
| 357 |
+
for definer in definers:
|
| 358 |
+
if referencer == definer:
|
| 359 |
+
continue
|
| 360 |
+
G.add_edge(referencer, definer, weight=num_refs, ident=ident)
|
| 361 |
+
|
| 362 |
+
if personalization:
|
| 363 |
+
pers_args = dict(personalization=personalization, dangling=personalization)
|
| 364 |
+
else:
|
| 365 |
+
pers_args = dict()
|
| 366 |
+
|
| 367 |
+
try:
|
| 368 |
+
ranked = nx.pagerank(G, weight="weight", **pers_args)
|
| 369 |
+
except ZeroDivisionError:
|
| 370 |
+
return []
|
| 371 |
+
|
| 372 |
+
# distribute the rank from each source node, across all of its out edges
|
| 373 |
+
ranked_definitions = defaultdict(float)
|
| 374 |
+
for src in G.nodes:
|
| 375 |
+
src_rank = ranked[src]
|
| 376 |
+
total_weight = sum(data["weight"] for _src, _dst, data in G.out_edges(src, data=True))
|
| 377 |
+
# dump(src, src_rank, total_weight)
|
| 378 |
+
for _src, dst, data in G.out_edges(src, data=True):
|
| 379 |
+
data["rank"] = src_rank * data["weight"] / total_weight
|
| 380 |
+
ident = data["ident"]
|
| 381 |
+
ranked_definitions[(dst, ident)] += data["rank"]
|
| 382 |
+
|
| 383 |
+
ranked_tags = []
|
| 384 |
+
ranked_definitions = sorted(ranked_definitions.items(), reverse=True, key=lambda x: x[1])
|
| 385 |
+
for (fname, ident), rank in ranked_definitions:
|
| 386 |
+
# print(f"{rank:.03f} {fname} {ident}")
|
| 387 |
+
if fname in chat_rel_fnames:
|
| 388 |
+
continue
|
| 389 |
+
ranked_tags += list(definitions.get((fname, ident), []))
|
| 390 |
+
|
| 391 |
+
rel_other_fnames_without_tags = set(
|
| 392 |
+
os.path.relpath(fname, self.root) for fname in other_fnames
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
fnames_already_included = set(rt[0] for rt in ranked_tags)
|
| 396 |
+
|
| 397 |
+
top_rank = sorted([(rank, node) for (node, rank) in ranked.items()], reverse=True)
|
| 398 |
+
for rank, fname in top_rank:
|
| 399 |
+
if fname in rel_other_fnames_without_tags:
|
| 400 |
+
rel_other_fnames_without_tags.remove(fname)
|
| 401 |
+
if fname not in fnames_already_included:
|
| 402 |
+
ranked_tags.append((fname,))
|
| 403 |
+
|
| 404 |
+
for fname in rel_other_fnames_without_tags:
|
| 405 |
+
ranked_tags.append((fname,))
|
| 406 |
+
|
| 407 |
+
return ranked_tags
|
| 408 |
+
|
| 409 |
+
def get_ranked_tags_map(self, chat_fnames, other_fnames=None):
|
| 410 |
+
if not other_fnames:
|
| 411 |
+
other_fnames = list()
|
| 412 |
+
|
| 413 |
+
ranked_tags = self.get_ranked_tags(chat_fnames, other_fnames)
|
| 414 |
+
num_tags = len(ranked_tags)
|
| 415 |
+
|
| 416 |
+
lower_bound = 0
|
| 417 |
+
upper_bound = num_tags
|
| 418 |
+
best_tree = None
|
| 419 |
+
|
| 420 |
+
while lower_bound <= upper_bound:
|
| 421 |
+
middle = (lower_bound + upper_bound) // 2
|
| 422 |
+
tree = to_tree(ranked_tags[:middle])
|
| 423 |
+
num_tokens = self.token_count(tree)
|
| 424 |
+
# dump(middle, num_tokens)
|
| 425 |
+
|
| 426 |
+
if num_tokens < self.max_map_tokens:
|
| 427 |
+
best_tree = tree
|
| 428 |
+
lower_bound = middle + 1
|
| 429 |
+
else:
|
| 430 |
+
upper_bound = middle - 1
|
| 431 |
+
|
| 432 |
+
return best_tree
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def find_py_files(directory):
|
| 436 |
+
if not os.path.isdir(directory):
|
| 437 |
+
return [directory]
|
| 438 |
+
|
| 439 |
+
py_files = []
|
| 440 |
+
for root, dirs, files in os.walk(directory):
|
| 441 |
+
for file in files:
|
| 442 |
+
if file.endswith(".py"):
|
| 443 |
+
py_files.append(os.path.join(root, file))
|
| 444 |
+
return py_files
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def get_random_color():
|
| 448 |
+
hue = random.random()
|
| 449 |
+
r, g, b = [int(x * 255) for x in colorsys.hsv_to_rgb(hue, 1, 0.75)]
|
| 450 |
+
res = f"#{r:02x}{g:02x}{b:02x}"
|
| 451 |
+
return res
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
if __name__ == "__main__":
|
| 455 |
+
fnames = sys.argv[1:]
|
| 456 |
+
|
| 457 |
+
chat_fnames = []
|
| 458 |
+
other_fnames = []
|
| 459 |
+
for dname in sys.argv[1:]:
|
| 460 |
+
if ".venv" in dname:
|
| 461 |
+
other_fnames += find_py_files(dname)
|
| 462 |
+
else:
|
| 463 |
+
chat_fnames += find_py_files(dname)
|
| 464 |
+
|
| 465 |
+
root = os.path.commonpath(chat_fnames)
|
| 466 |
+
|
| 467 |
+
rm = RepoMap(root=root)
|
| 468 |
+
repo_map = rm.get_ranked_tags_map(chat_fnames, other_fnames)
|
| 469 |
+
|
| 470 |
+
dump(len(repo_map))
|
| 471 |
+
print(repo_map)
|
testbed/Aider-AI__aider/aider/sendchat.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
import backoff
|
| 5 |
+
import openai
|
| 6 |
+
import requests
|
| 7 |
+
|
| 8 |
+
# from diskcache import Cache
|
| 9 |
+
from openai.error import (
|
| 10 |
+
APIConnectionError,
|
| 11 |
+
APIError,
|
| 12 |
+
RateLimitError,
|
| 13 |
+
ServiceUnavailableError,
|
| 14 |
+
Timeout,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
CACHE_PATH = "~/.aider.send.cache.v1"
|
| 18 |
+
CACHE = None
|
| 19 |
+
# CACHE = Cache(CACHE_PATH)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@backoff.on_exception(
|
| 23 |
+
backoff.expo,
|
| 24 |
+
(
|
| 25 |
+
Timeout,
|
| 26 |
+
APIError,
|
| 27 |
+
ServiceUnavailableError,
|
| 28 |
+
RateLimitError,
|
| 29 |
+
APIConnectionError,
|
| 30 |
+
requests.exceptions.ConnectionError,
|
| 31 |
+
),
|
| 32 |
+
max_tries=10,
|
| 33 |
+
on_backoff=lambda details: print(
|
| 34 |
+
f"{details.get('exception','Exception')}\nRetry in {details['wait']:.1f} seconds."
|
| 35 |
+
),
|
| 36 |
+
)
|
| 37 |
+
def send_with_retries(model, messages, functions, stream):
|
| 38 |
+
kwargs = dict(
|
| 39 |
+
model=model,
|
| 40 |
+
messages=messages,
|
| 41 |
+
temperature=0,
|
| 42 |
+
stream=stream,
|
| 43 |
+
)
|
| 44 |
+
if functions is not None:
|
| 45 |
+
kwargs["functions"] = functions
|
| 46 |
+
|
| 47 |
+
# we are abusing the openai object to stash these values
|
| 48 |
+
if hasattr(openai, "api_deployment_id"):
|
| 49 |
+
kwargs["deployment_id"] = openai.api_deployment_id
|
| 50 |
+
if hasattr(openai, "api_engine"):
|
| 51 |
+
kwargs["engine"] = openai.api_engine
|
| 52 |
+
|
| 53 |
+
key = json.dumps(kwargs, sort_keys=True).encode()
|
| 54 |
+
|
| 55 |
+
# Generate SHA1 hash of kwargs and append it to chat_completion_call_hashes
|
| 56 |
+
hash_object = hashlib.sha1(key)
|
| 57 |
+
|
| 58 |
+
if not stream and CACHE is not None and key in CACHE:
|
| 59 |
+
return hash_object, CACHE[key]
|
| 60 |
+
|
| 61 |
+
res = openai.ChatCompletion.create(**kwargs)
|
| 62 |
+
|
| 63 |
+
if not stream and CACHE is not None:
|
| 64 |
+
CACHE[key] = res
|
| 65 |
+
|
| 66 |
+
return hash_object, res
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def simple_send_with_retries(model, messages):
|
| 70 |
+
try:
|
| 71 |
+
_hash, response = send_with_retries(
|
| 72 |
+
model=model,
|
| 73 |
+
messages=messages,
|
| 74 |
+
functions=None,
|
| 75 |
+
stream=False,
|
| 76 |
+
)
|
| 77 |
+
return response.choices[0].message.content
|
| 78 |
+
except (AttributeError, openai.error.InvalidRequestError):
|
| 79 |
+
return
|
testbed/Aider-AI__aider/aider/utils.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
from .dump import dump # noqa: F401
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def safe_abs_path(res):
|
| 7 |
+
"Gives an abs path, which safely returns a full (not 8.3) windows path"
|
| 8 |
+
res = Path(res).resolve()
|
| 9 |
+
return str(res)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def show_messages(messages, title=None, functions=None):
|
| 13 |
+
if title:
|
| 14 |
+
print(title.upper(), "*" * 50)
|
| 15 |
+
|
| 16 |
+
for msg in messages:
|
| 17 |
+
role = msg["role"].upper()
|
| 18 |
+
content = msg.get("content")
|
| 19 |
+
if content:
|
| 20 |
+
for line in content.splitlines():
|
| 21 |
+
print(role, line)
|
| 22 |
+
content = msg.get("function_call")
|
| 23 |
+
if content:
|
| 24 |
+
print(role, content)
|
| 25 |
+
|
| 26 |
+
if functions:
|
| 27 |
+
dump(functions)
|
testbed/Aider-AI__aider/aider/versioncheck.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
|
| 3 |
+
import packaging.version
|
| 4 |
+
import requests
|
| 5 |
+
|
| 6 |
+
import aider
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def check_version(print_cmd):
|
| 10 |
+
try:
|
| 11 |
+
response = requests.get("https://pypi.org/pypi/aider-chat/json")
|
| 12 |
+
data = response.json()
|
| 13 |
+
latest_version = data["info"]["version"]
|
| 14 |
+
current_version = aider.__version__
|
| 15 |
+
|
| 16 |
+
if packaging.version.parse(latest_version) <= packaging.version.parse(current_version):
|
| 17 |
+
return
|
| 18 |
+
|
| 19 |
+
print_cmd(f"Newer version v{latest_version} is available. To upgrade, run:")
|
| 20 |
+
py = sys.executable
|
| 21 |
+
print_cmd(f"{py} -m pip install --upgrade aider-chat")
|
| 22 |
+
except Exception as err:
|
| 23 |
+
print_cmd(f"Error checking pypi for new version: {err}")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if __name__ == "__main__":
|
| 27 |
+
check_version(print)
|
testbed/Aider-AI__aider/aider/voice.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import queue
|
| 3 |
+
import tempfile
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import openai
|
| 8 |
+
from prompt_toolkit.shortcuts import prompt
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
import sounddevice as sd
|
| 12 |
+
except OSError:
|
| 13 |
+
sd = None
|
| 14 |
+
|
| 15 |
+
import soundfile as sf
|
| 16 |
+
|
| 17 |
+
from .dump import dump # noqa: F401
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Voice:
|
| 21 |
+
max_rms = 0
|
| 22 |
+
min_rms = 1e5
|
| 23 |
+
pct = 0
|
| 24 |
+
|
| 25 |
+
threshold = 0.15
|
| 26 |
+
|
| 27 |
+
def is_audio_available(self):
|
| 28 |
+
return sd is not None
|
| 29 |
+
|
| 30 |
+
def callback(self, indata, frames, time, status):
|
| 31 |
+
"""This is called (from a separate thread) for each audio block."""
|
| 32 |
+
rms = np.sqrt(np.mean(indata**2))
|
| 33 |
+
self.max_rms = max(self.max_rms, rms)
|
| 34 |
+
self.min_rms = min(self.min_rms, rms)
|
| 35 |
+
|
| 36 |
+
rng = self.max_rms - self.min_rms
|
| 37 |
+
if rng > 0.001:
|
| 38 |
+
self.pct = (rms - self.min_rms) / rng
|
| 39 |
+
else:
|
| 40 |
+
self.pct = 0.5
|
| 41 |
+
|
| 42 |
+
self.q.put(indata.copy())
|
| 43 |
+
|
| 44 |
+
def get_prompt(self):
|
| 45 |
+
num = 10
|
| 46 |
+
if np.isnan(self.pct) or self.pct < self.threshold:
|
| 47 |
+
cnt = 0
|
| 48 |
+
else:
|
| 49 |
+
cnt = int(self.pct * 10)
|
| 50 |
+
|
| 51 |
+
bar = "░" * cnt + "█" * (num - cnt)
|
| 52 |
+
bar = bar[:num]
|
| 53 |
+
|
| 54 |
+
dur = time.time() - self.start_time
|
| 55 |
+
return f"Recording, press ENTER when done... {dur:.1f}sec {bar}"
|
| 56 |
+
|
| 57 |
+
def record_and_transcribe(self, history=None, language=None):
|
| 58 |
+
try:
|
| 59 |
+
return self.raw_record_and_transcribe(history, language)
|
| 60 |
+
except KeyboardInterrupt:
|
| 61 |
+
return
|
| 62 |
+
|
| 63 |
+
def raw_record_and_transcribe(self, history, language):
|
| 64 |
+
self.q = queue.Queue()
|
| 65 |
+
|
| 66 |
+
filename = tempfile.mktemp(suffix=".wav")
|
| 67 |
+
|
| 68 |
+
sample_rate = 16000 # 16kHz
|
| 69 |
+
|
| 70 |
+
self.start_time = time.time()
|
| 71 |
+
|
| 72 |
+
with sd.InputStream(samplerate=sample_rate, channels=1, callback=self.callback):
|
| 73 |
+
prompt(self.get_prompt, refresh_interval=0.1)
|
| 74 |
+
|
| 75 |
+
with sf.SoundFile(filename, mode="x", samplerate=sample_rate, channels=1) as file:
|
| 76 |
+
while not self.q.empty():
|
| 77 |
+
file.write(self.q.get())
|
| 78 |
+
|
| 79 |
+
with open(filename, "rb") as fh:
|
| 80 |
+
transcript = openai.Audio.transcribe("whisper-1", fh, prompt=history, language=language)
|
| 81 |
+
|
| 82 |
+
text = transcript["text"]
|
| 83 |
+
return text
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
if __name__ == "__main__":
|
| 87 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 88 |
+
if not api_key:
|
| 89 |
+
raise ValueError("Please set the OPENAI_API_KEY environment variable.")
|
| 90 |
+
print(Voice().record_and_transcribe())
|
testbed/Aider-AI__aider/assets/benchmarks.svg
ADDED
|
|
testbed/Aider-AI__aider/assets/css/style.scss
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
---
|
| 3 |
+
|
| 4 |
+
@import "{{ site.theme }}";
|
| 5 |
+
|
| 6 |
+
.btn {
|
| 7 |
+
display: inline-block;
|
| 8 |
+
width: auto;
|
| 9 |
+
}
|
| 10 |
+
.btn + .btn {
|
| 11 |
+
margin-top: 0;
|
| 12 |
+
margin-left: 0.75rem;
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
.chat-transcript {
|
| 16 |
+
font-family: 'Courier New', Courier, monospace;
|
| 17 |
+
background-color: #000;
|
| 18 |
+
color: #0f0;
|
| 19 |
+
padding: 1em 1em 1em 1em;
|
| 20 |
+
border-radius: 5px;
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
.chat-transcript blockquote {
|
| 24 |
+
padding: 0;
|
| 25 |
+
margin-left: 0;
|
| 26 |
+
color: #819198;
|
| 27 |
+
border-left: none
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
.chat-transcript blockquote>:first-child {
|
| 31 |
+
margin-top: 0
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
.chat-transcript blockquote>:last-child {
|
| 35 |
+
margin-bottom: 0
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
.chat-transcript li,
|
| 40 |
+
.chat-transcript p {
|
| 41 |
+
color: #00FFFF;
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
.chat-transcript h1 {
|
| 45 |
+
display: none;
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
.chat-transcript h4 {
|
| 49 |
+
color: #32FF32;
|
| 50 |
+
border-top: 1px solid #32FF32;
|
| 51 |
+
padding-top: 10px;
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
.chat-transcript h4::before {
|
| 55 |
+
content: '> ';
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
.chat-transcript blockquote p {
|
| 59 |
+
color: #ffffff;
|
| 60 |
+
}
|
| 61 |
+
.chat-transcript::before {
|
| 62 |
+
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="90" height="25"><circle cx="7" cy="15" r="7" fill="%23f92672"/><circle cx="27" cy="15" r="7" fill="%23f4bf75"/><circle cx="47" cy="15" r="7" fill="%23a6e22e"/></svg>');
|
| 63 |
+
display: block;
|
| 64 |
+
margin-bottom: 0;
|
| 65 |
+
position: relative;
|
| 66 |
+
top: -0.5em;
|
| 67 |
+
}
|
testbed/Aider-AI__aider/assets/screencast.svg
ADDED
|
|
testbed/Aider-AI__aider/benchmark/__init__.py
ADDED
|
File without changes
|
testbed/Aider-AI__aider/benchmark/benchmark.py
ADDED
|
@@ -0,0 +1,696 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
import datetime
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import random
|
| 7 |
+
import re
|
| 8 |
+
import shutil
|
| 9 |
+
import subprocess
|
| 10 |
+
import time
|
| 11 |
+
from collections import defaultdict
|
| 12 |
+
from json.decoder import JSONDecodeError
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from types import SimpleNamespace
|
| 15 |
+
from typing import List
|
| 16 |
+
|
| 17 |
+
import git
|
| 18 |
+
import lox
|
| 19 |
+
import matplotlib.pyplot as plt
|
| 20 |
+
import numpy as np
|
| 21 |
+
import openai
|
| 22 |
+
import pandas as pd
|
| 23 |
+
import prompts
|
| 24 |
+
import typer
|
| 25 |
+
from imgcat import imgcat
|
| 26 |
+
from rich.console import Console
|
| 27 |
+
|
| 28 |
+
from aider import models
|
| 29 |
+
from aider.coders import Coder
|
| 30 |
+
from aider.dump import dump # noqa: F401
|
| 31 |
+
from aider.io import InputOutput
|
| 32 |
+
|
| 33 |
+
BENCHMARK_DNAME = Path(os.environ["AIDER_BENCHMARK_DIR"])
|
| 34 |
+
|
| 35 |
+
ORIGINAL_DNAME = BENCHMARK_DNAME / "exercism-python"
|
| 36 |
+
|
| 37 |
+
app = typer.Typer(add_completion=False, pretty_exceptions_enable=False)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def show_stats(dirnames):
|
| 41 |
+
raw_rows = []
|
| 42 |
+
for dirname in dirnames:
|
| 43 |
+
row = summarize_results(dirname)
|
| 44 |
+
raw_rows.append(row)
|
| 45 |
+
|
| 46 |
+
return
|
| 47 |
+
|
| 48 |
+
repeats = []
|
| 49 |
+
seen = dict()
|
| 50 |
+
rows = []
|
| 51 |
+
for row in raw_rows:
|
| 52 |
+
if not row:
|
| 53 |
+
continue
|
| 54 |
+
|
| 55 |
+
if row.model == "gpt-3.5-turbo":
|
| 56 |
+
row.model = "gpt-3.5-turbo-0613"
|
| 57 |
+
if row.edit_format == "diff-func-string":
|
| 58 |
+
row.edit_format = "diff-func"
|
| 59 |
+
|
| 60 |
+
if (
|
| 61 |
+
row.model == "gpt-3.5-turbo-0613"
|
| 62 |
+
and row.edit_format == "whole"
|
| 63 |
+
and "repeat" not in row.dir_name
|
| 64 |
+
):
|
| 65 |
+
# remember this row, so we can update it with the repeat_avg
|
| 66 |
+
repeat_row = len(rows)
|
| 67 |
+
|
| 68 |
+
pieces = row.model.split("-")
|
| 69 |
+
row.model = "-".join(pieces[:3])
|
| 70 |
+
if pieces[3:]:
|
| 71 |
+
row.model += "\n-" + "-".join(pieces[3:])
|
| 72 |
+
|
| 73 |
+
if row.completed_tests < 133:
|
| 74 |
+
print(f"Warning: {row.dir_name} is incomplete: {row.completed_tests}")
|
| 75 |
+
|
| 76 |
+
if "repeat" in row.dir_name:
|
| 77 |
+
repeats.append(vars(row))
|
| 78 |
+
continue
|
| 79 |
+
|
| 80 |
+
kind = (row.model, row.edit_format)
|
| 81 |
+
if kind in seen:
|
| 82 |
+
dump(row.dir_name)
|
| 83 |
+
dump(seen[kind])
|
| 84 |
+
return
|
| 85 |
+
|
| 86 |
+
seen[kind] = row.dir_name
|
| 87 |
+
rows.append(vars(row))
|
| 88 |
+
|
| 89 |
+
if repeats:
|
| 90 |
+
extra = rows[repeat_row]
|
| 91 |
+
dump(extra)
|
| 92 |
+
repeats.append(extra)
|
| 93 |
+
repeats = pd.DataFrame.from_records(repeats)
|
| 94 |
+
repeat_max = repeats["pass_rate_2"].max()
|
| 95 |
+
repeat_min = repeats["pass_rate_2"].min()
|
| 96 |
+
repeat_avg = repeats["pass_rate_2"].mean()
|
| 97 |
+
|
| 98 |
+
repeat_lo = repeat_avg - repeat_min
|
| 99 |
+
repeat_hi = repeat_max - repeat_avg
|
| 100 |
+
|
| 101 |
+
dump(repeat_max)
|
| 102 |
+
dump(repeat_min)
|
| 103 |
+
dump(repeat_avg)
|
| 104 |
+
|
| 105 |
+
# use the average in the main bar
|
| 106 |
+
rows[repeat_row]["pass_rate_2"] = repeat_avg
|
| 107 |
+
|
| 108 |
+
df = pd.DataFrame.from_records(rows)
|
| 109 |
+
df.sort_values(by=["model", "edit_format"], inplace=True)
|
| 110 |
+
|
| 111 |
+
tries = [df.groupby(["model", "edit_format"])["pass_rate_2"].mean()]
|
| 112 |
+
if True:
|
| 113 |
+
tries += [df.groupby(["model", "edit_format"])["pass_rate_1"].mean()]
|
| 114 |
+
|
| 115 |
+
plt.rcParams["hatch.linewidth"] = 0.5
|
| 116 |
+
plt.rcParams["hatch.color"] = "#444444"
|
| 117 |
+
|
| 118 |
+
from matplotlib import rc
|
| 119 |
+
|
| 120 |
+
rc("font", **{"family": "sans-serif", "sans-serif": ["Helvetica"], "size": 10})
|
| 121 |
+
|
| 122 |
+
fig, ax = plt.subplots(figsize=(6, 4))
|
| 123 |
+
ax.grid(axis="y", zorder=0, lw=0.2)
|
| 124 |
+
|
| 125 |
+
zorder = 1
|
| 126 |
+
for grouped in tries:
|
| 127 |
+
zorder += 1
|
| 128 |
+
df = grouped.unstack()
|
| 129 |
+
num_models, num_formats = df.shape
|
| 130 |
+
|
| 131 |
+
pos = np.array(range(num_models))
|
| 132 |
+
width = 0.8 / num_formats
|
| 133 |
+
|
| 134 |
+
formats = df.columns
|
| 135 |
+
models = df.index
|
| 136 |
+
|
| 137 |
+
for i, fmt in enumerate(formats):
|
| 138 |
+
if zorder > 1:
|
| 139 |
+
edge = dict(
|
| 140 |
+
edgecolor="#ffffff",
|
| 141 |
+
linewidth=1.5,
|
| 142 |
+
)
|
| 143 |
+
else:
|
| 144 |
+
edge = dict()
|
| 145 |
+
if zorder == 2:
|
| 146 |
+
edge["label"] = fmt
|
| 147 |
+
|
| 148 |
+
color = "#b3e6a8" if "diff" in fmt else "#b3d1e6"
|
| 149 |
+
hatch = "////" if "func" in fmt else ""
|
| 150 |
+
rects = ax.bar(
|
| 151 |
+
pos + i * width,
|
| 152 |
+
df[fmt],
|
| 153 |
+
width * 0.95,
|
| 154 |
+
color=color,
|
| 155 |
+
hatch=hatch,
|
| 156 |
+
zorder=zorder,
|
| 157 |
+
**edge,
|
| 158 |
+
)
|
| 159 |
+
if zorder == 2:
|
| 160 |
+
ax.bar_label(rects, padding=4, labels=[f"{v:.0f}%" for v in df[fmt]], size=6)
|
| 161 |
+
|
| 162 |
+
if len(repeats):
|
| 163 |
+
ax.errorbar(
|
| 164 |
+
1.4,
|
| 165 |
+
repeat_avg,
|
| 166 |
+
yerr=[[repeat_lo], [repeat_hi]],
|
| 167 |
+
fmt="none",
|
| 168 |
+
zorder=5,
|
| 169 |
+
capsize=2.5,
|
| 170 |
+
elinewidth=1,
|
| 171 |
+
markeredgewidth=1,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
ax.set_xticks([p + 1.5 * width for p in pos])
|
| 175 |
+
ax.set_xticklabels(models)
|
| 176 |
+
|
| 177 |
+
top = 95
|
| 178 |
+
ax.annotate(
|
| 179 |
+
"First attempt,\nbased on\ninstructions",
|
| 180 |
+
xy=(2.9, 51),
|
| 181 |
+
xytext=(2.5, top),
|
| 182 |
+
horizontalalignment="center",
|
| 183 |
+
verticalalignment="top",
|
| 184 |
+
arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=0.3"},
|
| 185 |
+
)
|
| 186 |
+
ax.annotate(
|
| 187 |
+
"Second attempt,\nbased on\nunit test errors",
|
| 188 |
+
xy=(3.1, 68),
|
| 189 |
+
xytext=(4.25, top),
|
| 190 |
+
horizontalalignment="center",
|
| 191 |
+
verticalalignment="top",
|
| 192 |
+
arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=0.3"},
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
ax.set_ylabel("Percent of exercises completed successfully")
|
| 196 |
+
# ax.set_xlabel("Model")
|
| 197 |
+
ax.set_title("GPT Code Editing")
|
| 198 |
+
ax.legend(
|
| 199 |
+
title="Edit Format",
|
| 200 |
+
loc="upper left",
|
| 201 |
+
# bbox_to_anchor=(0.95, 0.95),
|
| 202 |
+
)
|
| 203 |
+
ax.set_ylim(top=100)
|
| 204 |
+
|
| 205 |
+
plt.tight_layout()
|
| 206 |
+
plt.savefig("tmp.svg")
|
| 207 |
+
imgcat(fig)
|
| 208 |
+
|
| 209 |
+
# df.to_csv("tmp.benchmarks.csv")
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def resolve_dirname(dirname, use_single_prior, make_new):
|
| 213 |
+
if len(dirname.parts) > 1:
|
| 214 |
+
return dirname
|
| 215 |
+
|
| 216 |
+
priors = list(BENCHMARK_DNAME.glob(f"*--{dirname}"))
|
| 217 |
+
if len(priors) == 1 and use_single_prior:
|
| 218 |
+
dirname = priors[0].name
|
| 219 |
+
print(f"Using pre-existing {dirname}")
|
| 220 |
+
elif len(priors):
|
| 221 |
+
if not make_new:
|
| 222 |
+
print(f"Prior runs of {dirname} exist, use --new or name one explicitly")
|
| 223 |
+
print()
|
| 224 |
+
for prior in priors:
|
| 225 |
+
print(prior)
|
| 226 |
+
return
|
| 227 |
+
|
| 228 |
+
if not re.match(r"\d\d\d\d-\d\d-\d\d-", str(dirname)):
|
| 229 |
+
now = datetime.datetime.now()
|
| 230 |
+
now = now.strftime("%Y-%m-%d-%H-%M-%S--")
|
| 231 |
+
dirname = now + dirname.name
|
| 232 |
+
|
| 233 |
+
dirname = BENCHMARK_DNAME / dirname
|
| 234 |
+
return dirname
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
@app.command()
|
| 238 |
+
def main(
|
| 239 |
+
dirnames: List[str] = typer.Argument(..., help="Directory names"),
|
| 240 |
+
model: str = typer.Option("gpt-3.5-turbo", "--model", "-m", help="Model name"),
|
| 241 |
+
edit_format: str = typer.Option(None, "--edit-format", "-e", help="Edit format"),
|
| 242 |
+
keywords: str = typer.Option(
|
| 243 |
+
None, "--keywords", "-k", help="Only run tests that contain keywords (comma sep)"
|
| 244 |
+
),
|
| 245 |
+
clean: bool = typer.Option(
|
| 246 |
+
False, "--clean", "-c", help="Discard the existing testdir and make a clean copy"
|
| 247 |
+
),
|
| 248 |
+
cont: bool = typer.Option(False, "--cont", help="Continue the (single) matching testdir"),
|
| 249 |
+
make_new: bool = typer.Option(False, "--new", "-n", help="Make a new dated testdir"),
|
| 250 |
+
no_unit_tests: bool = typer.Option(False, "--no-unit-tests", help="Do not run unit tests"),
|
| 251 |
+
no_aider: bool = typer.Option(False, "--no-aider", help="Do not run aider"),
|
| 252 |
+
verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),
|
| 253 |
+
stats_only: bool = typer.Option(
|
| 254 |
+
False, "--stats", "-s", help="Do not run tests, just collect stats on completed tests"
|
| 255 |
+
),
|
| 256 |
+
diffs_only: bool = typer.Option(False, "--diffs", help="Just diff the provided stats dirs"),
|
| 257 |
+
tries: int = typer.Option(2, "--tries", "-r", help="Number of tries for running tests"),
|
| 258 |
+
threads: int = typer.Option(1, "--threads", "-t", help="Number of threads to run in parallel"),
|
| 259 |
+
num_tests: int = typer.Option(-1, "--num-tests", "-n", help="Number of tests to run"),
|
| 260 |
+
):
|
| 261 |
+
repo = git.Repo(search_parent_directories=True)
|
| 262 |
+
commit_hash = repo.head.object.hexsha[:7]
|
| 263 |
+
if repo.is_dirty():
|
| 264 |
+
commit_hash += "-dirty"
|
| 265 |
+
|
| 266 |
+
if len(dirnames) > 1 and not (stats_only or diffs_only):
|
| 267 |
+
print("Only provide 1 dirname unless running with --stats or --diffs")
|
| 268 |
+
return 1
|
| 269 |
+
|
| 270 |
+
updated_dirnames = []
|
| 271 |
+
for dirname in dirnames:
|
| 272 |
+
dirname = Path(dirname)
|
| 273 |
+
dirname = resolve_dirname(dirname, stats_only or cont, make_new)
|
| 274 |
+
if not dirname:
|
| 275 |
+
return 1
|
| 276 |
+
updated_dirnames.append(dirname)
|
| 277 |
+
|
| 278 |
+
if stats_only:
|
| 279 |
+
return show_stats(updated_dirnames)
|
| 280 |
+
|
| 281 |
+
if diffs_only:
|
| 282 |
+
return show_diffs(updated_dirnames)
|
| 283 |
+
|
| 284 |
+
assert len(updated_dirnames) == 1, updated_dirnames
|
| 285 |
+
dirname = updated_dirnames[0]
|
| 286 |
+
|
| 287 |
+
if "AIDER_DOCKER" not in os.environ:
|
| 288 |
+
print("Warning: benchmarking runs unvetted code from GPT, run in a docker container")
|
| 289 |
+
return
|
| 290 |
+
|
| 291 |
+
assert BENCHMARK_DNAME.exists() and BENCHMARK_DNAME.is_dir(), BENCHMARK_DNAME
|
| 292 |
+
assert ORIGINAL_DNAME.exists() and ORIGINAL_DNAME.is_dir(), ORIGINAL_DNAME
|
| 293 |
+
|
| 294 |
+
if clean and dirname.exists():
|
| 295 |
+
print("Cleaning up and replacing", dirname)
|
| 296 |
+
dir_files = set(fn.name for fn in dirname.glob("*"))
|
| 297 |
+
original_files = set(fn.name for fn in ORIGINAL_DNAME.glob("*"))
|
| 298 |
+
if dir_files != original_files:
|
| 299 |
+
print("ERROR: will not delete dir that does not look like original tests", dirname)
|
| 300 |
+
return
|
| 301 |
+
|
| 302 |
+
dest = dirname.parent / "OLD" / dirname.name
|
| 303 |
+
if dest.exists():
|
| 304 |
+
old_now = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
|
| 305 |
+
dest = dirname.parent / "OLD" / (old_now + dirname.name)
|
| 306 |
+
|
| 307 |
+
dirname.rename(dest)
|
| 308 |
+
|
| 309 |
+
if not dirname.exists():
|
| 310 |
+
shutil.copytree(ORIGINAL_DNAME, dirname)
|
| 311 |
+
|
| 312 |
+
test_dnames = sorted(os.listdir(dirname))
|
| 313 |
+
|
| 314 |
+
if keywords:
|
| 315 |
+
keywords = keywords.split(",")
|
| 316 |
+
test_dnames = [dn for dn in test_dnames for keyword in keywords if keyword in dn]
|
| 317 |
+
|
| 318 |
+
random.shuffle(test_dnames)
|
| 319 |
+
if num_tests > 0:
|
| 320 |
+
test_dnames = test_dnames[:num_tests]
|
| 321 |
+
|
| 322 |
+
if threads == 1:
|
| 323 |
+
all_results = []
|
| 324 |
+
for testname in test_dnames:
|
| 325 |
+
results = run_test(
|
| 326 |
+
dirname / testname,
|
| 327 |
+
model,
|
| 328 |
+
edit_format,
|
| 329 |
+
tries,
|
| 330 |
+
no_unit_tests,
|
| 331 |
+
no_aider,
|
| 332 |
+
verbose,
|
| 333 |
+
commit_hash,
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
all_results.append(results)
|
| 337 |
+
summarize_results(dirname)
|
| 338 |
+
else:
|
| 339 |
+
run_test_threaded = lox.thread(threads)(run_test)
|
| 340 |
+
for testname in test_dnames:
|
| 341 |
+
run_test_threaded.scatter(
|
| 342 |
+
dirname / testname,
|
| 343 |
+
model,
|
| 344 |
+
edit_format,
|
| 345 |
+
tries,
|
| 346 |
+
no_unit_tests,
|
| 347 |
+
no_aider,
|
| 348 |
+
verbose,
|
| 349 |
+
commit_hash,
|
| 350 |
+
)
|
| 351 |
+
all_results = run_test_threaded.gather(tqdm=True)
|
| 352 |
+
|
| 353 |
+
print()
|
| 354 |
+
print()
|
| 355 |
+
print()
|
| 356 |
+
summarize_results(dirname)
|
| 357 |
+
|
| 358 |
+
return 0
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def show_diffs(dirnames):
|
| 362 |
+
dirnames = sorted(dirnames)
|
| 363 |
+
|
| 364 |
+
all_results = dict((dirname, load_results(dirname)) for dirname in dirnames)
|
| 365 |
+
testcases = set()
|
| 366 |
+
for results in all_results.values():
|
| 367 |
+
testcases.update(result["testcase"] for result in results)
|
| 368 |
+
|
| 369 |
+
testcases = sorted(testcases)
|
| 370 |
+
|
| 371 |
+
unchanged = set()
|
| 372 |
+
|
| 373 |
+
for testcase in testcases:
|
| 374 |
+
all_outcomes = []
|
| 375 |
+
for dirname in dirnames:
|
| 376 |
+
results = all_results[dirname]
|
| 377 |
+
result = [r for r in results if r["testcase"] == testcase][0]
|
| 378 |
+
|
| 379 |
+
outcomes = tuple(result["tests_outcomes"])
|
| 380 |
+
all_outcomes.append(True in outcomes)
|
| 381 |
+
|
| 382 |
+
if len(set(all_outcomes)) == 1:
|
| 383 |
+
unchanged.add(testcase)
|
| 384 |
+
continue
|
| 385 |
+
|
| 386 |
+
print()
|
| 387 |
+
print(testcase)
|
| 388 |
+
for outcome, dirname in zip(all_outcomes, dirnames):
|
| 389 |
+
print(outcome, f"{dirname}/{testcase}/.aider.chat.history.md")
|
| 390 |
+
|
| 391 |
+
changed = set(testcases) - unchanged
|
| 392 |
+
print()
|
| 393 |
+
print("changed:", len(changed), ",".join(sorted(changed)))
|
| 394 |
+
print("unchanged:", len(unchanged), ",".join(sorted(unchanged)))
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def load_results(dirname):
|
| 398 |
+
dirname = Path(dirname)
|
| 399 |
+
all_results = [json.loads(fname.read_text()) for fname in dirname.glob("*/.aider.results.json")]
|
| 400 |
+
return all_results
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def summarize_results(dirname):
|
| 404 |
+
all_results = load_results(dirname)
|
| 405 |
+
|
| 406 |
+
res = SimpleNamespace()
|
| 407 |
+
res.total_tests = len(list(Path(dirname).glob("*")))
|
| 408 |
+
|
| 409 |
+
try:
|
| 410 |
+
tries = max(len(results["tests_outcomes"]) for results in all_results if results)
|
| 411 |
+
except ValueError:
|
| 412 |
+
tries = 0
|
| 413 |
+
|
| 414 |
+
res.dir_name = str(dirname)
|
| 415 |
+
|
| 416 |
+
passed_tests = [0] * tries
|
| 417 |
+
|
| 418 |
+
res.completed_tests = 0
|
| 419 |
+
res.duration = 0
|
| 420 |
+
res.cost = 0
|
| 421 |
+
res.error_outputs = 0
|
| 422 |
+
res.user_asks = 0
|
| 423 |
+
res.test_timeouts = 0
|
| 424 |
+
res.exhausted_context_windows = 0
|
| 425 |
+
|
| 426 |
+
variants = defaultdict(set)
|
| 427 |
+
|
| 428 |
+
for results in all_results:
|
| 429 |
+
if not results:
|
| 430 |
+
continue
|
| 431 |
+
|
| 432 |
+
res.completed_tests += 1
|
| 433 |
+
passed = results["tests_outcomes"][-1]
|
| 434 |
+
if passed:
|
| 435 |
+
for i in range(len(results["tests_outcomes"]) - 1, tries):
|
| 436 |
+
passed_tests[i] += 1
|
| 437 |
+
|
| 438 |
+
res.cost += results["cost"]
|
| 439 |
+
res.duration += results["duration"]
|
| 440 |
+
res.test_timeouts += results.get("test_timeouts", 0)
|
| 441 |
+
|
| 442 |
+
res.error_outputs += results.get("num_error_outputs", 0)
|
| 443 |
+
res.user_asks += results.get("num_user_asks", 0)
|
| 444 |
+
res.exhausted_context_windows += results.get("num_exhausted_context_windows", 0)
|
| 445 |
+
|
| 446 |
+
for key in "model edit_format commit_hash".split():
|
| 447 |
+
val = results.get(key)
|
| 448 |
+
variants[key].add(val)
|
| 449 |
+
|
| 450 |
+
if not res.completed_tests:
|
| 451 |
+
return
|
| 452 |
+
|
| 453 |
+
console = Console(highlight=False)
|
| 454 |
+
console.rule(title=str(dirname))
|
| 455 |
+
|
| 456 |
+
console.print(f"test-cases: {res.completed_tests}")
|
| 457 |
+
for key, val in variants.items():
|
| 458 |
+
if len(val) > 1:
|
| 459 |
+
style = "red"
|
| 460 |
+
else:
|
| 461 |
+
style = None
|
| 462 |
+
val = ", ".join(map(str, val))
|
| 463 |
+
setattr(res, key, val)
|
| 464 |
+
console.print(f"{key}: {val}", style=style)
|
| 465 |
+
print("num_error_outputs:", res.error_outputs)
|
| 466 |
+
print("num_user_asks:", res.user_asks)
|
| 467 |
+
|
| 468 |
+
style = "red" if res.exhausted_context_windows else None
|
| 469 |
+
console.print("num_exhausted_context_windows", res.exhausted_context_windows, style=style)
|
| 470 |
+
|
| 471 |
+
style = "red" if res.test_timeouts else None
|
| 472 |
+
console.print("test_timeouts:", res.test_timeouts, style=style)
|
| 473 |
+
|
| 474 |
+
console.print()
|
| 475 |
+
for i in range(tries):
|
| 476 |
+
pass_rate = 100 * passed_tests[i] / res.completed_tests
|
| 477 |
+
console.print(f"{pass_rate:.1f}% correct after try {i}")
|
| 478 |
+
setattr(res, f"pass_rate_{i+1}", pass_rate)
|
| 479 |
+
|
| 480 |
+
console.print()
|
| 481 |
+
res.avg_duration = res.duration / res.completed_tests
|
| 482 |
+
|
| 483 |
+
console.print(f"duration: {res.avg_duration:.1f} sec/test-case")
|
| 484 |
+
|
| 485 |
+
res.avg_cost = res.cost / res.completed_tests
|
| 486 |
+
|
| 487 |
+
projected_cost = res.avg_cost * res.total_tests
|
| 488 |
+
|
| 489 |
+
console.print(
|
| 490 |
+
f"costs: ${res.avg_cost:.4f}/test-case, ${res.cost:.2f} total,"
|
| 491 |
+
f" ${projected_cost:.2f} projected"
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
console.rule()
|
| 495 |
+
|
| 496 |
+
# print(json.dumps(vars(res), indent=4, sort_keys=True))
|
| 497 |
+
return res
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def run_test(
|
| 501 |
+
testdir, model_name, edit_format, tries, no_unit_tests, no_aider, verbose, commit_hash
|
| 502 |
+
):
|
| 503 |
+
if not os.path.isdir(testdir):
|
| 504 |
+
print("Not a dir:", testdir)
|
| 505 |
+
return
|
| 506 |
+
|
| 507 |
+
testdir = Path(testdir)
|
| 508 |
+
|
| 509 |
+
history_fname = testdir / ".aider.chat.history.md"
|
| 510 |
+
|
| 511 |
+
results_fname = testdir / ".aider.results.json"
|
| 512 |
+
if results_fname.exists():
|
| 513 |
+
try:
|
| 514 |
+
res = json.loads(results_fname.read_text())
|
| 515 |
+
return res
|
| 516 |
+
except JSONDecodeError:
|
| 517 |
+
print(f"{results_fname} failed to parse, skipping")
|
| 518 |
+
return
|
| 519 |
+
|
| 520 |
+
fnames = []
|
| 521 |
+
for fname in testdir.glob("*"):
|
| 522 |
+
if "test" not in fname.name and fname.is_file() and fname.name[0] != ".":
|
| 523 |
+
fnames.append(fname)
|
| 524 |
+
|
| 525 |
+
# restore the original file, in case we interrupted a prev run
|
| 526 |
+
# after it had saved changes
|
| 527 |
+
original_fname = ORIGINAL_DNAME / testdir.name / fname.name
|
| 528 |
+
shutil.copy(original_fname, fname)
|
| 529 |
+
|
| 530 |
+
file_list = " ".join(fname.name for fname in fnames)
|
| 531 |
+
|
| 532 |
+
instructions = ""
|
| 533 |
+
|
| 534 |
+
introduction = testdir / ".docs/introduction.md"
|
| 535 |
+
if introduction.exists():
|
| 536 |
+
instructions += introduction.read_text()
|
| 537 |
+
instructions += (testdir / ".docs/instructions.md").read_text()
|
| 538 |
+
instructions_append = testdir / ".docs/instructions.append.md"
|
| 539 |
+
if instructions_append.exists():
|
| 540 |
+
instructions += instructions_append.read_text()
|
| 541 |
+
|
| 542 |
+
instructions += prompts.instructions_addendum.format(file_list=file_list)
|
| 543 |
+
|
| 544 |
+
io = InputOutput(
|
| 545 |
+
pretty=True,
|
| 546 |
+
yes=False,
|
| 547 |
+
chat_history_file=history_fname,
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
main_model = models.Model(model_name)
|
| 551 |
+
edit_format = edit_format or main_model.edit_format
|
| 552 |
+
|
| 553 |
+
dump(main_model)
|
| 554 |
+
dump(edit_format)
|
| 555 |
+
show_fnames = ",".join(map(str, fnames))
|
| 556 |
+
print("fnames:", show_fnames)
|
| 557 |
+
|
| 558 |
+
openai.api_key = os.environ["OPENAI_API_KEY"]
|
| 559 |
+
|
| 560 |
+
coder = Coder.create(
|
| 561 |
+
main_model,
|
| 562 |
+
edit_format,
|
| 563 |
+
io,
|
| 564 |
+
fnames=fnames,
|
| 565 |
+
use_git=False,
|
| 566 |
+
stream=False,
|
| 567 |
+
pretty=False,
|
| 568 |
+
verbose=verbose,
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
timeouts = 0
|
| 572 |
+
|
| 573 |
+
dur = 0
|
| 574 |
+
test_outcomes = []
|
| 575 |
+
for i in range(tries):
|
| 576 |
+
start = time.time()
|
| 577 |
+
if not no_aider:
|
| 578 |
+
coder.run(with_message=instructions)
|
| 579 |
+
dur += time.time() - start
|
| 580 |
+
|
| 581 |
+
if coder.last_keyboard_interrupt:
|
| 582 |
+
raise KeyboardInterrupt
|
| 583 |
+
|
| 584 |
+
if no_unit_tests:
|
| 585 |
+
break
|
| 586 |
+
|
| 587 |
+
try:
|
| 588 |
+
errors = run_unit_tests(testdir, history_fname)
|
| 589 |
+
except subprocess.TimeoutExpired:
|
| 590 |
+
errors = "Tests timed out!"
|
| 591 |
+
timeouts += 1
|
| 592 |
+
|
| 593 |
+
if errors:
|
| 594 |
+
test_outcomes.append(False)
|
| 595 |
+
else:
|
| 596 |
+
test_outcomes.append(True)
|
| 597 |
+
break
|
| 598 |
+
|
| 599 |
+
errors = errors.splitlines()
|
| 600 |
+
print(errors[-1])
|
| 601 |
+
errors = errors[:50]
|
| 602 |
+
errors = "\n".join(errors)
|
| 603 |
+
instructions = errors
|
| 604 |
+
instructions += prompts.test_failures.format(file_list=file_list)
|
| 605 |
+
|
| 606 |
+
results = dict(
|
| 607 |
+
testdir=str(testdir),
|
| 608 |
+
testcase=testdir.name,
|
| 609 |
+
model=main_model.name,
|
| 610 |
+
edit_format=edit_format,
|
| 611 |
+
tests_outcomes=test_outcomes,
|
| 612 |
+
cost=coder.total_cost,
|
| 613 |
+
duration=dur,
|
| 614 |
+
test_timeouts=timeouts,
|
| 615 |
+
commit_hash=commit_hash,
|
| 616 |
+
num_error_outputs=io.num_error_outputs,
|
| 617 |
+
num_user_asks=io.num_user_asks,
|
| 618 |
+
num_exhausted_context_windows=coder.num_exhausted_context_windows,
|
| 619 |
+
chat_hashes=list(
|
| 620 |
+
zip(
|
| 621 |
+
coder.chat_completion_call_hashes,
|
| 622 |
+
coder.chat_completion_response_hashes,
|
| 623 |
+
)
|
| 624 |
+
),
|
| 625 |
+
)
|
| 626 |
+
dump(results)
|
| 627 |
+
|
| 628 |
+
results_fname.write_text(json.dumps(results, indent=4))
|
| 629 |
+
|
| 630 |
+
return results
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
def run_unit_tests(testdir, history_fname):
|
| 634 |
+
command = [
|
| 635 |
+
"python",
|
| 636 |
+
"-m",
|
| 637 |
+
"unittest",
|
| 638 |
+
"discover",
|
| 639 |
+
"-s",
|
| 640 |
+
str(testdir),
|
| 641 |
+
"-t",
|
| 642 |
+
str(testdir),
|
| 643 |
+
"-p",
|
| 644 |
+
"*_test.py",
|
| 645 |
+
]
|
| 646 |
+
print(" ".join(command))
|
| 647 |
+
|
| 648 |
+
timeout = 60
|
| 649 |
+
|
| 650 |
+
result = subprocess.run(
|
| 651 |
+
command,
|
| 652 |
+
stdout=subprocess.PIPE,
|
| 653 |
+
stderr=subprocess.STDOUT,
|
| 654 |
+
text=True,
|
| 655 |
+
timeout=timeout,
|
| 656 |
+
)
|
| 657 |
+
|
| 658 |
+
success = result.returncode == 0
|
| 659 |
+
res = result.stdout
|
| 660 |
+
res = cleanup_test_output(res, testdir)
|
| 661 |
+
|
| 662 |
+
with history_fname.open("a") as fh:
|
| 663 |
+
fh.write(f"```\n{res}\n```")
|
| 664 |
+
|
| 665 |
+
if not success:
|
| 666 |
+
print(f"Tests failed: {testdir}")
|
| 667 |
+
return res
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
def cleanup_test_output(output, testdir):
|
| 671 |
+
# remove timing info, to avoid randomizing the response to GPT
|
| 672 |
+
res = re.sub(
|
| 673 |
+
r"^Ran \d+ tests in \d+\.\d+s$",
|
| 674 |
+
"",
|
| 675 |
+
output,
|
| 676 |
+
flags=re.MULTILINE,
|
| 677 |
+
)
|
| 678 |
+
res = re.sub(
|
| 679 |
+
r"^====*$",
|
| 680 |
+
"====",
|
| 681 |
+
res,
|
| 682 |
+
flags=re.MULTILINE,
|
| 683 |
+
)
|
| 684 |
+
res = re.sub(
|
| 685 |
+
r"^----*$",
|
| 686 |
+
"----",
|
| 687 |
+
res,
|
| 688 |
+
flags=re.MULTILINE,
|
| 689 |
+
)
|
| 690 |
+
|
| 691 |
+
res = res.replace(str(testdir), str(testdir.name))
|
| 692 |
+
return res
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
if __name__ == "__main__":
|
| 696 |
+
app()
|
testbed/Aider-AI__aider/benchmark/docker.sh
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
docker run \
|
| 4 |
+
-it --rm \
|
| 5 |
+
-v `pwd`:/aider \
|
| 6 |
+
-v `pwd`/tmp.benchmarks/.:/benchmarks \
|
| 7 |
+
-e OPENAI_API_KEY=$OPENAI_API_KEY \
|
| 8 |
+
-e HISTFILE=/aider/.bash_history \
|
| 9 |
+
-e AIDER_DOCKER=1 \
|
| 10 |
+
-e AIDER_BENCHMARK_DIR=/benchmarks \
|
| 11 |
+
aider-benchmark \
|
| 12 |
+
bash
|
testbed/Aider-AI__aider/benchmark/docker_build.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
set -e
|
| 4 |
+
|
| 5 |
+
docker build \
|
| 6 |
+
--file benchmark/Dockerfile \
|
| 7 |
+
-t aider-benchmark \
|
| 8 |
+
.
|
testbed/Aider-AI__aider/benchmark/plot.sh
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
# exit when any command fails
|
| 4 |
+
set -e
|
| 5 |
+
|
| 6 |
+
./benchmark/benchmark.py --stats \
|
| 7 |
+
2023-06-29-11-04-31--gpt-3.5-turbo-0301 \
|
| 8 |
+
2023-06-29-11-17-32--gpt-3.5-turbo-0613 \
|
| 9 |
+
2023-06-29-22-18-10--diff-func-string-accept-lists \
|
| 10 |
+
2023-06-29-22-33-14--whole-func \
|
| 11 |
+
2023-06-29-22-33-21--whole-func-string \
|
| 12 |
+
2023-06-30-02-39-48--0613-diff \
|
| 13 |
+
2023-06-30-02-59-11--0301-diff \
|
| 14 |
+
2023-06-30-03-53-55--gpt-3.5-turbo-16k-0613-diff \
|
| 15 |
+
2023-06-30-04-34-00--gpt-3.5-turbo-16k-0613-diff-func-string \
|
| 16 |
+
2023-06-30-05-02-45--gpt-3.5-turbo-16k-0613-whole \
|
| 17 |
+
2023-06-30-05-08-40--gpt-3.5-turbo-16k-0613-whole-func \
|
| 18 |
+
2023-06-30-05-31-44--gpt-4-0314-whole \
|
| 19 |
+
2023-06-30-05-43-54--gpt-4-0314-diff \
|
| 20 |
+
2023-06-30-06-06-02--gpt-4-0613-diff-func-string \
|
| 21 |
+
2023-06-30-06-19-22--gpt-4-0613-whole \
|
| 22 |
+
2023-06-30-13-09-51--gpt-4-0613-diff \
|
| 23 |
+
2023-06-30-13-28-09--gpt-4-0613-whole-func \
|
| 24 |
+
2023-06-30-17-05-20--gpt-3.5-0613-whole-repeat-1 \
|
| 25 |
+
2023-06-30-17-17-42--gpt-3.5-0613-whole-repeat-2 \
|
| 26 |
+
2023-06-30-17-27-04--gpt-3.5-0613-whole-repeat-3 \
|
| 27 |
+
2023-06-30-17-35-07--gpt-3.5-0613-whole-repeat-4 \
|
| 28 |
+
2023-06-30-17-46-25--gpt-3.5-0613-whole-repeat-5
|
| 29 |
+
|
testbed/Aider-AI__aider/benchmark/prompts.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
instructions_addendum = """
|
| 2 |
+
####
|
| 3 |
+
|
| 4 |
+
Use the above instructions to modify the supplied files: {file_list}
|
| 5 |
+
Keep and implement the existing function or class stubs, they will be called from unit tests.
|
| 6 |
+
Only use standard python libraries, don't suggest installing any packages.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
test_failures = """
|
| 11 |
+
####
|
| 12 |
+
|
| 13 |
+
See the testing errors above.
|
| 14 |
+
The tests are correct.
|
| 15 |
+
Fix the code in {file_list} to resolve the errors.
|
| 16 |
+
"""
|
testbed/Aider-AI__aider/benchmark/rungrid.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
import subprocess
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
from aider.dump import dump # noqa: F401
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main():
|
| 10 |
+
models = [
|
| 11 |
+
# "gpt-3.5-turbo-0301",
|
| 12 |
+
"gpt-3.5-turbo-0613",
|
| 13 |
+
# "gpt-3.5-turbo-16k-0613",
|
| 14 |
+
# "gpt-4-0314",
|
| 15 |
+
# "gpt-4-0613",
|
| 16 |
+
]
|
| 17 |
+
edit_formats = [
|
| 18 |
+
# "diff",
|
| 19 |
+
# "diff-func",
|
| 20 |
+
"whole",
|
| 21 |
+
# "whole-func",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
for repeat in range(1, 10, 1):
|
| 25 |
+
for model in models:
|
| 26 |
+
for edit_format in edit_formats:
|
| 27 |
+
# dump(model, edit_format)
|
| 28 |
+
|
| 29 |
+
if "-func" in edit_format and "-03" in model:
|
| 30 |
+
continue
|
| 31 |
+
|
| 32 |
+
# if (model, edit_format) == ("gpt-3.5-turbo-16k-0613", "whole-func"):
|
| 33 |
+
# # sublist reliably hangs the API?
|
| 34 |
+
# continue
|
| 35 |
+
|
| 36 |
+
# dirname = f"rungrid-{model}-{edit_format}"
|
| 37 |
+
dirname = f"rungrid-{model}-{edit_format}-repeat-{repeat}"
|
| 38 |
+
run(dirname, model, edit_format)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def run(dirname, model, edit_format):
|
| 42 |
+
cmd = [
|
| 43 |
+
"./benchmark/benchmark.py",
|
| 44 |
+
dirname,
|
| 45 |
+
"--model",
|
| 46 |
+
model,
|
| 47 |
+
"--edit-format",
|
| 48 |
+
edit_format,
|
| 49 |
+
"--threads",
|
| 50 |
+
"10",
|
| 51 |
+
"--cont",
|
| 52 |
+
]
|
| 53 |
+
print(" ".join(cmd))
|
| 54 |
+
|
| 55 |
+
subprocess.run(cmd, check=True)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
if __name__ == "__main__":
|
| 59 |
+
status = main()
|
| 60 |
+
sys.exit(status)
|
testbed/Aider-AI__aider/benchmark/test_benchmark.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa: E501
|
| 2 |
+
|
| 3 |
+
import unittest
|
| 4 |
+
|
| 5 |
+
from benchmark import cleanup_test_output
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TestCleanupTestOutput(unittest.TestCase):
|
| 9 |
+
def test_cleanup_test_output(self):
|
| 10 |
+
# Test case with timing info
|
| 11 |
+
output = "Ran 5 tests in 0.003s\nOK"
|
| 12 |
+
expected = "\nOK"
|
| 13 |
+
self.assertEqual(cleanup_test_output(output), expected)
|
| 14 |
+
|
| 15 |
+
# Test case without timing info
|
| 16 |
+
output = "OK"
|
| 17 |
+
expected = "OK"
|
| 18 |
+
self.assertEqual(cleanup_test_output(output), expected)
|
| 19 |
+
|
| 20 |
+
def test_cleanup_test_output_lines(self):
|
| 21 |
+
# Test case with timing info
|
| 22 |
+
output = """F
|
| 23 |
+
======================================================================
|
| 24 |
+
FAIL: test_cleanup_test_output (test_benchmark.TestCleanupTestOutput.test_cleanup_test_output)
|
| 25 |
+
----------------------------------------------------------------------
|
| 26 |
+
Traceback (most recent call last):
|
| 27 |
+
File "/Users/gauthier/Projects/aider/benchmark/test_benchmark.py", line 14, in test_cleanup_test_output
|
| 28 |
+
self.assertEqual(cleanup_test_output(output), expected)
|
| 29 |
+
AssertionError: 'OK' != 'OKx'
|
| 30 |
+
- OK
|
| 31 |
+
+ OKx
|
| 32 |
+
? +
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
expected = """F
|
| 36 |
+
====
|
| 37 |
+
FAIL: test_cleanup_test_output (test_benchmark.TestCleanupTestOutput.test_cleanup_test_output)
|
| 38 |
+
----
|
| 39 |
+
Traceback (most recent call last):
|
| 40 |
+
File "/Users/gauthier/Projects/aider/benchmark/test_benchmark.py", line 14, in test_cleanup_test_output
|
| 41 |
+
self.assertEqual(cleanup_test_output(output), expected)
|
| 42 |
+
AssertionError: 'OK' != 'OKx'
|
| 43 |
+
- OK
|
| 44 |
+
+ OKx
|
| 45 |
+
? +
|
| 46 |
+
"""
|
| 47 |
+
self.assertEqual(cleanup_test_output(output), expected)
|
testbed/Aider-AI__aider/docs/install.md
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Installing aider
|
| 3 |
+
|
| 4 |
+
- [pip install aider-chat](#pip-install-aider-chat)
|
| 5 |
+
- [Provide your OpenAI API key](#provide-your-openai-api-key)
|
| 6 |
+
- [Install git](#install-git)
|
| 7 |
+
|
| 8 |
+
Optional steps:
|
| 9 |
+
|
| 10 |
+
- [Install universal ctags (optional)](#install-universal-ctags-optional)
|
| 11 |
+
- [Add aider to your editor (optional)](#add-aider-to-your-editor-optional)
|
| 12 |
+
- [Install PortAudio (optional)](#install-portaudio-optional)
|
| 13 |
+
|
| 14 |
+
## pip install aider-chat
|
| 15 |
+
|
| 16 |
+
Install the “aider-chat” package with pip from one of these sources:
|
| 17 |
+
|
| 18 |
+
* PyPI hosts the released and most stable version:
|
| 19 |
+
* `python -m pip install aider-chat`
|
| 20 |
+
* GitHub hosts the latest version, which is under active development:
|
| 21 |
+
* `python -m pip install git+https://github.com/paul-gauthier/aider.git`
|
| 22 |
+
* If you've git cloned the aider repository already, you can install "live" from your local copy. This is mostly useful if you are developing aider and want your current modifications to take effect immediately.
|
| 23 |
+
* `python -m pip install -e .`
|
| 24 |
+
|
| 25 |
+
On Windows, you may need to run `py -m pip install ...` to install python packages.
|
| 26 |
+
|
| 27 |
+
## Provide your OpenAI API key
|
| 28 |
+
|
| 29 |
+
You need a
|
| 30 |
+
[paid API key from OpenAI](https://help.openai.com/en/articles/4936850-where-do-i-find-my-secret-api-key)
|
| 31 |
+
to use aider. Note that this is different than being a "ChatGPT Plus" subscriber.
|
| 32 |
+
|
| 33 |
+
You can place your api key in an environment variable:
|
| 34 |
+
|
| 35 |
+
* `export OPENAI_API_KEY=sk-...` on Linux or Mac
|
| 36 |
+
* `setx OPENAI_API_KEY sk-...` in Windows PowerShell
|
| 37 |
+
|
| 38 |
+
Or you can create a `.aider.conf.yml` file in your home directory.
|
| 39 |
+
Put a line in it like this to specify your api key:
|
| 40 |
+
|
| 41 |
+
```
|
| 42 |
+
openai-api-key: sk-...
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
Or you can provide your key as a command line argument:
|
| 46 |
+
|
| 47 |
+
```
|
| 48 |
+
aider --openai-api-key sk-...
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
## Install git
|
| 52 |
+
|
| 53 |
+
Make sure you have git installed and available on your shell path.
|
| 54 |
+
Here are
|
| 55 |
+
[instructions for installing git in various environments](https://github.com/git-guides/install-git).
|
| 56 |
+
|
| 57 |
+
## You are done!
|
| 58 |
+
|
| 59 |
+
See the [usage instructions](/#usage) to start coding with aider.
|
| 60 |
+
|
| 61 |
+
The rest of the install steps are completely optional.
|
| 62 |
+
|
| 63 |
+
---
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
## Install universal ctags (optional)
|
| 67 |
+
|
| 68 |
+
Aider does not require ctags, and will operate just fine without it.
|
| 69 |
+
|
| 70 |
+
Installing ctags is helpful if you plan to use aider and GPT-4 with repositories
|
| 71 |
+
that have more than a handful of files.
|
| 72 |
+
This allows aider to build a
|
| 73 |
+
[map of your entire git repo](https://aider.chat/docs/ctags.html)
|
| 74 |
+
and share it with GPT to help it better understand and modify large codebases.
|
| 75 |
+
|
| 76 |
+
Aider only attempts to use ctags with GPT-4,
|
| 77 |
+
and currently doesn't use ctags at all with GPT-3.5.
|
| 78 |
+
So if your OpenAI API key doesn't support GPT-4, then you don't need ctags.
|
| 79 |
+
|
| 80 |
+
You should consult the
|
| 81 |
+
[universal ctags repo](https://github.com/universal-ctags/ctags)
|
| 82 |
+
for official instructions on how to install it in your environment.
|
| 83 |
+
But you may be able to install a compatible version using these commands:
|
| 84 |
+
|
| 85 |
+
* Mac: `brew update && brew install universal-ctags`
|
| 86 |
+
* Windows: `choco install universal-ctags`
|
| 87 |
+
* Ubuntu: `sudo apt update && sudo apt install universal-ctags`
|
| 88 |
+
|
| 89 |
+
You know aider has found a working ctags if you see this output when you launch aider:
|
| 90 |
+
|
| 91 |
+
```
|
| 92 |
+
Aider v0.8.3-dev
|
| 93 |
+
Model: gpt-4
|
| 94 |
+
Git repo: .git
|
| 95 |
+
Repo-map: universal-ctags using 1024 tokens <======
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
Some things to be aware of:
|
| 99 |
+
|
| 100 |
+
* The `ctags` command needs to be on your shell path so that it will run by default when aider invokes `ctags ...`.
|
| 101 |
+
* You need a build which includes the json feature. You can check by running `ctags --version` and looking for `+json` in the `Optional compiled features` list.
|
| 102 |
+
|
| 103 |
+
```
|
| 104 |
+
$ ctags --version
|
| 105 |
+
|
| 106 |
+
Universal Ctags 6.0.0, Copyright (C) 2015-2022 Universal Ctags Team
|
| 107 |
+
Universal Ctags is derived from Exuberant Ctags.
|
| 108 |
+
Exuberant Ctags 5.8, Copyright (C) 1996-2009 Darren Hiebert
|
| 109 |
+
Compiled: Jun 25 2023, 07:31:18
|
| 110 |
+
URL: https://ctags.io/
|
| 111 |
+
Output version: 0.0
|
| 112 |
+
Optional compiled features: +wildcards, +regex, +gnulib_fnmatch, +gnulib_regex, +iconv, +option-directory, +xpath, +json, +interactive, +yaml, +case-insensitive-filenames, +packcc, +optscript, +pcre2
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
## Install PortAudio (optional)
|
| 116 |
+
|
| 117 |
+
Aider supports [coding with your voice](https://aider.chat/docs/voice.html)
|
| 118 |
+
using the in-chat `/voice` command.
|
| 119 |
+
Aider uses the [PortAudio](http://www.portaudio.com) library to
|
| 120 |
+
capture audio.
|
| 121 |
+
Installing PortAudio is completely optional, but can usually be accomplished like this:
|
| 122 |
+
|
| 123 |
+
- For Windows, there is no need to install PortAudio.
|
| 124 |
+
- For Mac, do `brew install portaudio`
|
| 125 |
+
- For Linux, do `sudo apt-get install libportaudio2`
|
| 126 |
+
|
| 127 |
+
## Add aider to your editor (optional)
|
| 128 |
+
|
| 129 |
+
[joshuavial](https://github.com/joshuavial) has been working on editor integrations.
|
| 130 |
+
|
| 131 |
+
### NeoVim
|
| 132 |
+
|
| 133 |
+
He provided a NeoVim plugin for aider:
|
| 134 |
+
|
| 135 |
+
[https://github.com/joshuavial/aider.nvim](https://github.com/joshuavial/aider.nvim)
|
| 136 |
+
|
| 137 |
+
### VS Code
|
| 138 |
+
|
| 139 |
+
He also confirmed that aider works inside a VS Code terminal window, but
|
| 140 |
+
found that you should
|
| 141 |
+
[run with `--no-pretty` to avoid flickering issues](https://github.com/paul-gauthier/aider/issues/68#issuecomment-1634985231).
|
| 142 |
+
|
| 143 |
+
### Other editors
|
| 144 |
+
|
| 145 |
+
If you are interested in creating an aider plugin for your favorite editor,
|
| 146 |
+
please let me know by opening a
|
| 147 |
+
[GitHub issue](https://github.com/paul-gauthier/aider/issues).
|
testbed/Aider-AI__aider/examples/pong.md
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Build pong with aider, gpt-4 and pygame.
|
| 3 |
+
|
| 4 |
+
In this chat transcript, the user asks to make a pong game using pygame.
|
| 5 |
+
After setting up a basic game, the user asks for some customization of the colors and game mechanics.
|
| 6 |
+
|
| 7 |
+
<div class="chat-transcript" markdown="1">
|
| 8 |
+
|
| 9 |
+
> $ aider
|
| 10 |
+
|
| 11 |
+
#### can you make a simple game of pong with pygame?
|
| 12 |
+
|
| 13 |
+
Sure, I can help you create a simple Pong game using Pygame. First, let's break down the steps needed to create the game:
|
| 14 |
+
|
| 15 |
+
1. Install Pygame library.
|
| 16 |
+
2. Initialize Pygame and create a game window.
|
| 17 |
+
3. Create Paddle and Ball classes.
|
| 18 |
+
4. Initialize the paddles and the ball.
|
| 19 |
+
5. Create the game loop.
|
| 20 |
+
6. Handle user input for paddle movement.
|
| 21 |
+
7. Update the ball position and check for collisions.
|
| 22 |
+
8. Draw the paddles and ball on the screen.
|
| 23 |
+
9. Check for scoring and update the score.
|
| 24 |
+
10. Display the score on the screen.
|
| 25 |
+
|
| 26 |
+
Now, let's start with the code. I'll provide you with the code changes in an *EDIT BLOCK*. Since we are creating a new file, I'll name it `pong_game.py`.
|
| 27 |
+
|
| 28 |
+
```python
|
| 29 |
+
pong_game.py
|
| 30 |
+
<<<<<<< ORIGINAL
|
| 31 |
+
=======
|
| 32 |
+
import pygame
|
| 33 |
+
import sys
|
| 34 |
+
|
| 35 |
+
# Initialize Pygame
|
| 36 |
+
pygame.init()
|
| 37 |
+
|
| 38 |
+
# Set up the game window
|
| 39 |
+
screen_width = 640
|
| 40 |
+
screen_height = 480
|
| 41 |
+
screen = pygame.display.set_mode((screen_width, screen_height))
|
| 42 |
+
pygame.display.set_caption("Pong")
|
| 43 |
+
|
| 44 |
+
# Game loop
|
| 45 |
+
running = True
|
| 46 |
+
while running:
|
| 47 |
+
for event in pygame.event.get():
|
| 48 |
+
if event.type == pygame.QUIT:
|
| 49 |
+
running = False
|
| 50 |
+
|
| 51 |
+
# Update game objects
|
| 52 |
+
|
| 53 |
+
# Draw game objects
|
| 54 |
+
|
| 55 |
+
# Update the display
|
| 56 |
+
pygame.display.flip()
|
| 57 |
+
|
| 58 |
+
# Quit Pygame
|
| 59 |
+
pygame.quit()
|
| 60 |
+
sys.exit()
|
| 61 |
+
>>>>>>> UPDATED
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
This is the basic structure of the game. Now, let's add the Paddle and Ball classes, handle user input, update the ball position, draw the objects, and handle scoring. I'll provide the code changes in the next message.
|
| 65 |
+
|
| 66 |
+
> Allow creation of new file pong_game.py? y
|
| 67 |
+
> Add pong_game.py to git? y
|
| 68 |
+
> Applied edit to pong_game.py
|
| 69 |
+
> Commit 14799cb aider: Added basic Pygame initialization and game loop structure to `pong_game.py`.
|
| 70 |
+
|
| 71 |
+
#### go ahead
|
| 72 |
+
|
| 73 |
+
Now, let's add the Paddle and Ball classes, handle user input, update the ball position, draw the objects, and handle scoring. I'll provide the code changes in an *EDIT BLOCK*.
|
| 74 |
+
|
| 75 |
+
```python
|
| 76 |
+
pong_game.py
|
| 77 |
+
<<<<<<< ORIGINAL
|
| 78 |
+
import pygame
|
| 79 |
+
import sys
|
| 80 |
+
|
| 81 |
+
# Initialize Pygame
|
| 82 |
+
pygame.init()
|
| 83 |
+
|
| 84 |
+
# Set up the game window
|
| 85 |
+
screen_width = 640
|
| 86 |
+
screen_height = 480
|
| 87 |
+
screen = pygame.display.set_mode((screen_width, screen_height))
|
| 88 |
+
pygame.display.set_caption("Pong")
|
| 89 |
+
=======
|
| 90 |
+
import pygame
|
| 91 |
+
import sys
|
| 92 |
+
import random
|
| 93 |
+
|
| 94 |
+
# Initialize Pygame
|
| 95 |
+
pygame.init()
|
| 96 |
+
|
| 97 |
+
# Set up the game window
|
| 98 |
+
screen_width = 640
|
| 99 |
+
screen_height = 480
|
| 100 |
+
screen = pygame.display.set_mode((screen_width, screen_height))
|
| 101 |
+
pygame.display.set_caption("Pong")
|
| 102 |
+
|
| 103 |
+
# Paddle and Ball classes
|
| 104 |
+
class Paddle(pygame.sprite.Sprite):
|
| 105 |
+
def __init__(self, x, y):
|
| 106 |
+
super().__init__()
|
| 107 |
+
self.width = 10
|
| 108 |
+
self.height = 60
|
| 109 |
+
self.image = pygame.Surface((self.width, self.height))
|
| 110 |
+
self.image.fill((255, 255, 255))
|
| 111 |
+
self.rect = self.image.get_rect()
|
| 112 |
+
self.rect.x = x
|
| 113 |
+
self.rect.y = y
|
| 114 |
+
|
| 115 |
+
def move(self, dy):
|
| 116 |
+
if self.rect.y + dy >= 0 and self.rect.y + dy <= screen_height - self.height:
|
| 117 |
+
self.rect.y += dy
|
| 118 |
+
|
| 119 |
+
class Ball(pygame.sprite.Sprite):
|
| 120 |
+
def __init__(self):
|
| 121 |
+
super().__init__()
|
| 122 |
+
self.width = 10
|
| 123 |
+
self.height = 10
|
| 124 |
+
self.image = pygame.Surface((self.width, self.height))
|
| 125 |
+
self.image.fill((255, 255, 255))
|
| 126 |
+
self.rect = self.image.get_rect()
|
| 127 |
+
self.rect.x = screen_width // 2 - self.width // 2
|
| 128 |
+
self.rect.y = screen_height // 2 - self.height // 2
|
| 129 |
+
self.dx = random.choice([-1, 1]) * 4
|
| 130 |
+
self.dy = random.choice([-1, 1]) * 4
|
| 131 |
+
|
| 132 |
+
def update(self):
|
| 133 |
+
self.rect.x += self.dx
|
| 134 |
+
self.rect.y += self.dy
|
| 135 |
+
|
| 136 |
+
# Collision with top and bottom
|
| 137 |
+
if self.rect.y <= 0 or self.rect.y >= screen_height - self.height:
|
| 138 |
+
self.dy = -self.dy
|
| 139 |
+
|
| 140 |
+
# Scoring
|
| 141 |
+
if self.rect.x <= 0 or self.rect.x >= screen_width - self.width:
|
| 142 |
+
self.reset()
|
| 143 |
+
|
| 144 |
+
def reset(self):
|
| 145 |
+
self.rect.x = screen_width // 2 - self.width // 2
|
| 146 |
+
self.rect.y = screen_height // 2 - self.height // 2
|
| 147 |
+
self.dx = random.choice([-1, 1]) * 4
|
| 148 |
+
self.dy = random.choice([-1, 1]) * 4
|
| 149 |
+
|
| 150 |
+
def collide_with(self, paddle):
|
| 151 |
+
if self.rect.colliderect(paddle.rect):
|
| 152 |
+
self.dx = -self.dx
|
| 153 |
+
>>>>>>> UPDATED
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
Now, let's initialize the paddles and the ball, handle user input, update the ball position, draw the objects, and handle scoring.
|
| 157 |
+
|
| 158 |
+
```python
|
| 159 |
+
pong_game.py
|
| 160 |
+
<<<<<<< ORIGINAL
|
| 161 |
+
# Game loop
|
| 162 |
+
running = True
|
| 163 |
+
while running:
|
| 164 |
+
for event in pygame.event.get():
|
| 165 |
+
if event.type == pygame.QUIT:
|
| 166 |
+
running = False
|
| 167 |
+
|
| 168 |
+
# Update game objects
|
| 169 |
+
|
| 170 |
+
# Draw game objects
|
| 171 |
+
|
| 172 |
+
# Update the display
|
| 173 |
+
pygame.display.flip()
|
| 174 |
+
=======
|
| 175 |
+
# Initialize paddles and ball
|
| 176 |
+
left_paddle = Paddle(10, screen_height // 2 - 30)
|
| 177 |
+
right_paddle = Paddle(screen_width - 20, screen_height // 2 - 30)
|
| 178 |
+
ball = Ball()
|
| 179 |
+
|
| 180 |
+
# Game loop
|
| 181 |
+
running = True
|
| 182 |
+
while running:
|
| 183 |
+
for event in pygame.event.get():
|
| 184 |
+
if event.type == pygame.QUIT:
|
| 185 |
+
running = False
|
| 186 |
+
|
| 187 |
+
# Handle user input
|
| 188 |
+
keys = pygame.key.get_pressed()
|
| 189 |
+
if keys[pygame.K_w]:
|
| 190 |
+
left_paddle.move(-5)
|
| 191 |
+
if keys[pygame.K_s]:
|
| 192 |
+
left_paddle.move(5)
|
| 193 |
+
if keys[pygame.K_UP]:
|
| 194 |
+
right_paddle.move(-5)
|
| 195 |
+
if keys[pygame.K_DOWN]:
|
| 196 |
+
right_paddle.move(5)
|
| 197 |
+
|
| 198 |
+
# Update game objects
|
| 199 |
+
ball.update()
|
| 200 |
+
ball.collide_with(left_paddle)
|
| 201 |
+
ball.collide_with(right_paddle)
|
| 202 |
+
|
| 203 |
+
# Draw game objects
|
| 204 |
+
screen.fill((0, 0, 0))
|
| 205 |
+
screen.blit(left_paddle.image, left_paddle.rect)
|
| 206 |
+
screen.blit(right_paddle.image, right_paddle.rect)
|
| 207 |
+
screen.blit(ball.image, ball.rect)
|
| 208 |
+
|
| 209 |
+
# Update the display
|
| 210 |
+
pygame.display.flip()
|
| 211 |
+
pygame.time.delay(16)
|
| 212 |
+
>>>>>>> UPDATED
|
| 213 |
+
```
|
| 214 |
+
|
| 215 |
+
Now, you should have a simple Pong game using Pygame. You can further improve the game by adding a scoring system and displaying the score on the screen.
|
| 216 |
+
|
| 217 |
+
> Applied edit to pong_game.py
|
| 218 |
+
> Applied edit to pong_game.py
|
| 219 |
+
> Commit b20bcee aider: Added Paddle and Ball classes, handled user input, updated ball position, drew objects, and handled scoring.
|
| 220 |
+
|
| 221 |
+
#### nice, it works. but the ball moves way too fast.
|
| 222 |
+
|
| 223 |
+
I'm glad it works! Let's slow down the ball by reducing its speed. We can do this by changing the values of `self.dx` and `self.dy` in the `Ball` class.
|
| 224 |
+
|
| 225 |
+
```python
|
| 226 |
+
pong_game.py
|
| 227 |
+
<<<<<<< ORIGINAL
|
| 228 |
+
self.dx = random.choice([-1, 1]) * 4
|
| 229 |
+
self.dy = random.choice([-1, 1]) * 4
|
| 230 |
+
=======
|
| 231 |
+
self.dx = random.choice([-1, 1]) * 2
|
| 232 |
+
self.dy = random.choice([-1, 1]) * 2
|
| 233 |
+
>>>>>>> UPDATED
|
| 234 |
+
```
|
| 235 |
+
|
| 236 |
+
This change will reduce the ball's speed by half. You can adjust the values further if you want the ball to move even slower.
|
| 237 |
+
|
| 238 |
+
> Applied edit to pong_game.py
|
| 239 |
+
> Commit f4ceed4 aider: Reduced ball speed by half.
|
| 240 |
+
|
| 241 |
+
#### can you make the paddles a bit bigger? and make one paddle red and one blue?
|
| 242 |
+
|
| 243 |
+
Sure, let's make the paddles bigger and change their colors. We can do this by modifying the `Paddle` class in the `pong_game.py` file.
|
| 244 |
+
|
| 245 |
+
```python
|
| 246 |
+
pong_game.py
|
| 247 |
+
<<<<<<< ORIGINAL
|
| 248 |
+
self.width = 10
|
| 249 |
+
self.height = 60
|
| 250 |
+
self.image = pygame.Surface((self.width, self.height))
|
| 251 |
+
self.image.fill((255, 255, 255))
|
| 252 |
+
=======
|
| 253 |
+
self.width = 15
|
| 254 |
+
self.height = 80
|
| 255 |
+
self.image = pygame.Surface((self.width, self.height))
|
| 256 |
+
self.color = (255, 255, 255) if x < screen_width // 2 else (0, 0, 255)
|
| 257 |
+
self.image.fill(self.color)
|
| 258 |
+
>>>>>>> UPDATED
|
| 259 |
+
```
|
| 260 |
+
|
| 261 |
+
Now, let's change the color of the left paddle to red.
|
| 262 |
+
|
| 263 |
+
```python
|
| 264 |
+
pong_game.py
|
| 265 |
+
<<<<<<< ORIGINAL
|
| 266 |
+
left_paddle = Paddle(10, screen_height // 2 - 30)
|
| 267 |
+
=======
|
| 268 |
+
left_paddle = Paddle(10, screen_height // 2 - 40)
|
| 269 |
+
left_paddle.color = (255, 0, 0)
|
| 270 |
+
left_paddle.image.fill(left_paddle.color)
|
| 271 |
+
>>>>>>> UPDATED
|
| 272 |
+
```
|
| 273 |
+
|
| 274 |
+
With these changes, the paddles will be larger, and the left paddle will be red while the right paddle will be blue.
|
| 275 |
+
|
| 276 |
+
> Applied edit to pong_game.py
|
| 277 |
+
> Applied edit to pong_game.py
|
| 278 |
+
> Commit 2c645c9 aider: Changed paddle size and color, and set left paddle to red.
|
| 279 |
+
|
| 280 |
+
#### each time the ball bounces off the paddle, can you make it go 10% faster?
|
| 281 |
+
|
| 282 |
+
Sure, let's increase the ball's speed by 10% each time it bounces off a paddle. We can do this by modifying the `collide_with` method in the `Ball` class.
|
| 283 |
+
|
| 284 |
+
```python
|
| 285 |
+
pong_game.py
|
| 286 |
+
<<<<<<< ORIGINAL
|
| 287 |
+
def collide_with(self, paddle):
|
| 288 |
+
if self.rect.colliderect(paddle.rect):
|
| 289 |
+
self.dx = -self.dx
|
| 290 |
+
=======
|
| 291 |
+
def collide_with(self, paddle):
|
| 292 |
+
if self.rect.colliderect(paddle.rect):
|
| 293 |
+
self.dx = -self.dx * 1.1
|
| 294 |
+
self.dy *= 1.1
|
| 295 |
+
>>>>>>> UPDATED
|
| 296 |
+
```
|
| 297 |
+
|
| 298 |
+
With this change, the ball's speed will increase by 10% in both the x and y directions each time it bounces off a paddle.
|
| 299 |
+
|
| 300 |
+
> Applied edit to pong_game.py
|
| 301 |
+
> Commit 693faf4 aider: Increased ball speed by 10% in both x and y directions each time it bounces off a paddle.
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
</div>
|
testbed/Aider-AI__aider/tests/test_coder.py
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tempfile
|
| 2 |
+
import unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from unittest.mock import MagicMock, patch
|
| 5 |
+
|
| 6 |
+
import git
|
| 7 |
+
import openai
|
| 8 |
+
|
| 9 |
+
from aider import models
|
| 10 |
+
from aider.coders import Coder
|
| 11 |
+
from aider.dump import dump # noqa: F401
|
| 12 |
+
from aider.io import InputOutput
|
| 13 |
+
from tests.utils import GitTemporaryDirectory
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class TestCoder(unittest.TestCase):
|
| 17 |
+
def setUp(self):
|
| 18 |
+
self.patcher = patch("aider.coders.base_coder.check_model_availability")
|
| 19 |
+
self.mock_check = self.patcher.start()
|
| 20 |
+
self.mock_check.return_value = True
|
| 21 |
+
|
| 22 |
+
def tearDown(self):
|
| 23 |
+
self.patcher.stop()
|
| 24 |
+
|
| 25 |
+
def test_new_file_commit_message(self):
|
| 26 |
+
with GitTemporaryDirectory():
|
| 27 |
+
repo = git.Repo()
|
| 28 |
+
fname = Path("foo.txt")
|
| 29 |
+
|
| 30 |
+
io = InputOutput(yes=True)
|
| 31 |
+
# Initialize the Coder object with the mocked IO and mocked repo
|
| 32 |
+
Coder.create(models.GPT4, None, io, fnames=[str(fname)])
|
| 33 |
+
|
| 34 |
+
self.assertTrue(fname.exists())
|
| 35 |
+
|
| 36 |
+
# Mock the get_commit_message method to return "I added str(fname)"
|
| 37 |
+
repo.get_commit_message = MagicMock(return_value=f"I added {str(fname)}")
|
| 38 |
+
# Get the latest commit message
|
| 39 |
+
commit_message = repo.get_commit_message()
|
| 40 |
+
# Check that the latest commit message is "I added str(fname)"
|
| 41 |
+
self.assertEqual(commit_message, f"I added {str(fname)}")
|
| 42 |
+
|
| 43 |
+
def test_allowed_to_edit(self):
|
| 44 |
+
with GitTemporaryDirectory():
|
| 45 |
+
repo = git.Repo(Path.cwd())
|
| 46 |
+
fname = Path("foo.txt")
|
| 47 |
+
fname.touch()
|
| 48 |
+
repo.git.add(str(fname))
|
| 49 |
+
repo.git.commit("-m", "init")
|
| 50 |
+
|
| 51 |
+
io = InputOutput(yes=True)
|
| 52 |
+
# Initialize the Coder object with the mocked IO and mocked repo
|
| 53 |
+
coder = Coder.create(models.GPT4, None, io, fnames=["foo.txt"])
|
| 54 |
+
|
| 55 |
+
self.assertTrue(coder.allowed_to_edit("foo.txt"))
|
| 56 |
+
self.assertTrue(coder.allowed_to_edit("new.txt"))
|
| 57 |
+
|
| 58 |
+
def test_allowed_to_edit_no(self):
|
| 59 |
+
with GitTemporaryDirectory():
|
| 60 |
+
repo = git.Repo(Path.cwd())
|
| 61 |
+
fname = Path("foo.txt")
|
| 62 |
+
fname.touch()
|
| 63 |
+
repo.git.add(str(fname))
|
| 64 |
+
repo.git.commit("-m", "init")
|
| 65 |
+
|
| 66 |
+
# say NO
|
| 67 |
+
io = InputOutput(yes=False)
|
| 68 |
+
|
| 69 |
+
coder = Coder.create(models.GPT4, None, io, fnames=["foo.txt"])
|
| 70 |
+
|
| 71 |
+
self.assertTrue(coder.allowed_to_edit("foo.txt"))
|
| 72 |
+
self.assertFalse(coder.allowed_to_edit("new.txt"))
|
| 73 |
+
|
| 74 |
+
def test_get_last_modified(self):
|
| 75 |
+
# Mock the IO object
|
| 76 |
+
mock_io = MagicMock()
|
| 77 |
+
|
| 78 |
+
with GitTemporaryDirectory():
|
| 79 |
+
repo = git.Repo(Path.cwd())
|
| 80 |
+
fname = Path("new.txt")
|
| 81 |
+
fname.touch()
|
| 82 |
+
repo.git.add(str(fname))
|
| 83 |
+
repo.git.commit("-m", "new")
|
| 84 |
+
|
| 85 |
+
# Initialize the Coder object with the mocked IO and mocked repo
|
| 86 |
+
coder = Coder.create(models.GPT4, None, mock_io)
|
| 87 |
+
|
| 88 |
+
mod = coder.get_last_modified()
|
| 89 |
+
|
| 90 |
+
fname.write_text("hi")
|
| 91 |
+
mod_newer = coder.get_last_modified()
|
| 92 |
+
self.assertLess(mod, mod_newer)
|
| 93 |
+
|
| 94 |
+
fname.unlink()
|
| 95 |
+
self.assertEqual(coder.get_last_modified(), 0)
|
| 96 |
+
|
| 97 |
+
def test_should_dirty_commit(self):
|
| 98 |
+
# Mock the IO object
|
| 99 |
+
mock_io = MagicMock()
|
| 100 |
+
|
| 101 |
+
with GitTemporaryDirectory():
|
| 102 |
+
repo = git.Repo(Path.cwd())
|
| 103 |
+
fname = Path("new.txt")
|
| 104 |
+
fname.touch()
|
| 105 |
+
repo.git.add(str(fname))
|
| 106 |
+
repo.git.commit("-m", "new")
|
| 107 |
+
|
| 108 |
+
# Initialize the Coder object with the mocked IO and mocked repo
|
| 109 |
+
coder = Coder.create(models.GPT4, None, mock_io)
|
| 110 |
+
|
| 111 |
+
fname.write_text("hi")
|
| 112 |
+
self.assertTrue(coder.should_dirty_commit("hi"))
|
| 113 |
+
|
| 114 |
+
self.assertFalse(coder.should_dirty_commit("/exit"))
|
| 115 |
+
self.assertFalse(coder.should_dirty_commit("/help"))
|
| 116 |
+
|
| 117 |
+
def test_check_for_file_mentions(self):
|
| 118 |
+
# Mock the IO object
|
| 119 |
+
mock_io = MagicMock()
|
| 120 |
+
|
| 121 |
+
# Initialize the Coder object with the mocked IO and mocked repo
|
| 122 |
+
coder = Coder.create(models.GPT4, None, mock_io)
|
| 123 |
+
|
| 124 |
+
# Mock the git repo
|
| 125 |
+
mock = MagicMock()
|
| 126 |
+
mock.return_value = set(["file1.txt", "file2.py"])
|
| 127 |
+
coder.repo.get_tracked_files = mock
|
| 128 |
+
|
| 129 |
+
# Call the check_for_file_mentions method
|
| 130 |
+
coder.check_for_file_mentions("Please check file1.txt and file2.py")
|
| 131 |
+
|
| 132 |
+
# Check if coder.abs_fnames contains both files
|
| 133 |
+
expected_files = set(
|
| 134 |
+
map(
|
| 135 |
+
str,
|
| 136 |
+
[
|
| 137 |
+
Path(coder.root) / "file1.txt",
|
| 138 |
+
Path(coder.root) / "file2.py",
|
| 139 |
+
],
|
| 140 |
+
)
|
| 141 |
+
)
|
| 142 |
+
self.assertEqual(coder.abs_fnames, expected_files)
|
| 143 |
+
|
| 144 |
+
def test_get_files_content(self):
|
| 145 |
+
tempdir = Path(tempfile.mkdtemp())
|
| 146 |
+
|
| 147 |
+
file1 = tempdir / "file1.txt"
|
| 148 |
+
file2 = tempdir / "file2.txt"
|
| 149 |
+
|
| 150 |
+
file1.touch()
|
| 151 |
+
file2.touch()
|
| 152 |
+
|
| 153 |
+
files = [file1, file2]
|
| 154 |
+
|
| 155 |
+
# Initialize the Coder object with the mocked IO and mocked repo
|
| 156 |
+
coder = Coder.create(models.GPT4, None, io=InputOutput(), fnames=files)
|
| 157 |
+
|
| 158 |
+
content = coder.get_files_content().splitlines()
|
| 159 |
+
self.assertIn("file1.txt", content)
|
| 160 |
+
self.assertIn("file2.txt", content)
|
| 161 |
+
|
| 162 |
+
def test_check_for_filename_mentions_of_longer_paths(self):
|
| 163 |
+
# Mock the IO object
|
| 164 |
+
mock_io = MagicMock()
|
| 165 |
+
|
| 166 |
+
# Initialize the Coder object with the mocked IO and mocked repo
|
| 167 |
+
coder = Coder.create(models.GPT4, None, mock_io)
|
| 168 |
+
|
| 169 |
+
mock = MagicMock()
|
| 170 |
+
mock.return_value = set(["file1.txt", "file2.py"])
|
| 171 |
+
coder.repo.get_tracked_files = mock
|
| 172 |
+
|
| 173 |
+
# Call the check_for_file_mentions method
|
| 174 |
+
coder.check_for_file_mentions("Please check file1.txt and file2.py")
|
| 175 |
+
|
| 176 |
+
# Check if coder.abs_fnames contains both files
|
| 177 |
+
expected_files = set(
|
| 178 |
+
map(
|
| 179 |
+
str,
|
| 180 |
+
[
|
| 181 |
+
Path(coder.root) / "file1.txt",
|
| 182 |
+
Path(coder.root) / "file2.py",
|
| 183 |
+
],
|
| 184 |
+
)
|
| 185 |
+
)
|
| 186 |
+
self.assertEqual(coder.abs_fnames, expected_files)
|
| 187 |
+
|
| 188 |
+
def test_check_for_ambiguous_filename_mentions_of_longer_paths(self):
|
| 189 |
+
with GitTemporaryDirectory():
|
| 190 |
+
io = InputOutput(pretty=False, yes=True)
|
| 191 |
+
coder = Coder.create(models.GPT4, None, io)
|
| 192 |
+
|
| 193 |
+
fname = Path("file1.txt")
|
| 194 |
+
fname.touch()
|
| 195 |
+
|
| 196 |
+
other_fname = Path("other") / "file1.txt"
|
| 197 |
+
other_fname.parent.mkdir(parents=True, exist_ok=True)
|
| 198 |
+
other_fname.touch()
|
| 199 |
+
|
| 200 |
+
mock = MagicMock()
|
| 201 |
+
mock.return_value = set([str(fname), str(other_fname)])
|
| 202 |
+
coder.repo.get_tracked_files = mock
|
| 203 |
+
|
| 204 |
+
# Call the check_for_file_mentions method
|
| 205 |
+
coder.check_for_file_mentions(f"Please check {fname}!")
|
| 206 |
+
|
| 207 |
+
self.assertEqual(coder.abs_fnames, set([str(fname.resolve())]))
|
| 208 |
+
|
| 209 |
+
def test_check_for_subdir_mention(self):
|
| 210 |
+
with GitTemporaryDirectory():
|
| 211 |
+
io = InputOutput(pretty=False, yes=True)
|
| 212 |
+
coder = Coder.create(models.GPT4, None, io)
|
| 213 |
+
|
| 214 |
+
fname = Path("other") / "file1.txt"
|
| 215 |
+
fname.parent.mkdir(parents=True, exist_ok=True)
|
| 216 |
+
fname.touch()
|
| 217 |
+
|
| 218 |
+
mock = MagicMock()
|
| 219 |
+
mock.return_value = set([str(fname)])
|
| 220 |
+
coder.repo.get_tracked_files = mock
|
| 221 |
+
|
| 222 |
+
dump(fname)
|
| 223 |
+
# Call the check_for_file_mentions method
|
| 224 |
+
coder.check_for_file_mentions(f"Please check `{fname}`")
|
| 225 |
+
|
| 226 |
+
self.assertEqual(coder.abs_fnames, set([str(fname.resolve())]))
|
| 227 |
+
|
| 228 |
+
def test_run_with_file_deletion(self):
|
| 229 |
+
# Create a few temporary files
|
| 230 |
+
|
| 231 |
+
tempdir = Path(tempfile.mkdtemp())
|
| 232 |
+
|
| 233 |
+
file1 = tempdir / "file1.txt"
|
| 234 |
+
file2 = tempdir / "file2.txt"
|
| 235 |
+
|
| 236 |
+
file1.touch()
|
| 237 |
+
file2.touch()
|
| 238 |
+
|
| 239 |
+
files = [file1, file2]
|
| 240 |
+
|
| 241 |
+
# Initialize the Coder object with the mocked IO and mocked repo
|
| 242 |
+
coder = Coder.create(models.GPT4, None, io=InputOutput(), fnames=files)
|
| 243 |
+
|
| 244 |
+
def mock_send(*args, **kwargs):
|
| 245 |
+
coder.partial_response_content = "ok"
|
| 246 |
+
coder.partial_response_function_call = dict()
|
| 247 |
+
|
| 248 |
+
coder.send = MagicMock(side_effect=mock_send)
|
| 249 |
+
|
| 250 |
+
# Call the run method with a message
|
| 251 |
+
coder.run(with_message="hi")
|
| 252 |
+
self.assertEqual(len(coder.abs_fnames), 2)
|
| 253 |
+
|
| 254 |
+
file1.unlink()
|
| 255 |
+
|
| 256 |
+
# Call the run method again with a message
|
| 257 |
+
coder.run(with_message="hi")
|
| 258 |
+
self.assertEqual(len(coder.abs_fnames), 1)
|
| 259 |
+
|
| 260 |
+
def test_run_with_file_unicode_error(self):
|
| 261 |
+
# Create a few temporary files
|
| 262 |
+
_, file1 = tempfile.mkstemp()
|
| 263 |
+
_, file2 = tempfile.mkstemp()
|
| 264 |
+
|
| 265 |
+
files = [file1, file2]
|
| 266 |
+
|
| 267 |
+
# Initialize the Coder object with the mocked IO and mocked repo
|
| 268 |
+
coder = Coder.create(models.GPT4, None, io=InputOutput(), fnames=files)
|
| 269 |
+
|
| 270 |
+
def mock_send(*args, **kwargs):
|
| 271 |
+
coder.partial_response_content = "ok"
|
| 272 |
+
coder.partial_response_function_call = dict()
|
| 273 |
+
|
| 274 |
+
coder.send = MagicMock(side_effect=mock_send)
|
| 275 |
+
|
| 276 |
+
# Call the run method with a message
|
| 277 |
+
coder.run(with_message="hi")
|
| 278 |
+
self.assertEqual(len(coder.abs_fnames), 2)
|
| 279 |
+
|
| 280 |
+
# Write some non-UTF8 text into the file
|
| 281 |
+
with open(file1, "wb") as f:
|
| 282 |
+
f.write(b"\x80abc")
|
| 283 |
+
|
| 284 |
+
# Call the run method again with a message
|
| 285 |
+
coder.run(with_message="hi")
|
| 286 |
+
self.assertEqual(len(coder.abs_fnames), 1)
|
| 287 |
+
|
| 288 |
+
def test_choose_fence(self):
|
| 289 |
+
# Create a few temporary files
|
| 290 |
+
_, file1 = tempfile.mkstemp()
|
| 291 |
+
|
| 292 |
+
with open(file1, "wb") as f:
|
| 293 |
+
f.write(b"this contains ``` backticks")
|
| 294 |
+
|
| 295 |
+
files = [file1]
|
| 296 |
+
|
| 297 |
+
# Initialize the Coder object with the mocked IO and mocked repo
|
| 298 |
+
coder = Coder.create(models.GPT4, None, io=InputOutput(), fnames=files)
|
| 299 |
+
|
| 300 |
+
def mock_send(*args, **kwargs):
|
| 301 |
+
coder.partial_response_content = "ok"
|
| 302 |
+
coder.partial_response_function_call = dict()
|
| 303 |
+
|
| 304 |
+
coder.send = MagicMock(side_effect=mock_send)
|
| 305 |
+
|
| 306 |
+
# Call the run method with a message
|
| 307 |
+
coder.run(with_message="hi")
|
| 308 |
+
|
| 309 |
+
self.assertNotEqual(coder.fence[0], "```")
|
| 310 |
+
|
| 311 |
+
def test_run_with_file_utf_unicode_error(self):
|
| 312 |
+
"make sure that we honor InputOutput(encoding) and don't just assume utf-8"
|
| 313 |
+
# Create a few temporary files
|
| 314 |
+
_, file1 = tempfile.mkstemp()
|
| 315 |
+
_, file2 = tempfile.mkstemp()
|
| 316 |
+
|
| 317 |
+
files = [file1, file2]
|
| 318 |
+
|
| 319 |
+
encoding = "utf-16"
|
| 320 |
+
|
| 321 |
+
# Initialize the Coder object with the mocked IO and mocked repo
|
| 322 |
+
coder = Coder.create(
|
| 323 |
+
models.GPT4,
|
| 324 |
+
None,
|
| 325 |
+
io=InputOutput(encoding=encoding),
|
| 326 |
+
fnames=files,
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
def mock_send(*args, **kwargs):
|
| 330 |
+
coder.partial_response_content = "ok"
|
| 331 |
+
coder.partial_response_function_call = dict()
|
| 332 |
+
|
| 333 |
+
coder.send = MagicMock(side_effect=mock_send)
|
| 334 |
+
|
| 335 |
+
# Call the run method with a message
|
| 336 |
+
coder.run(with_message="hi")
|
| 337 |
+
self.assertEqual(len(coder.abs_fnames), 2)
|
| 338 |
+
|
| 339 |
+
some_content_which_will_error_if_read_with_encoding_utf8 = "ÅÍÎÏ".encode(encoding)
|
| 340 |
+
with open(file1, "wb") as f:
|
| 341 |
+
f.write(some_content_which_will_error_if_read_with_encoding_utf8)
|
| 342 |
+
|
| 343 |
+
coder.run(with_message="hi")
|
| 344 |
+
|
| 345 |
+
# both files should still be here
|
| 346 |
+
self.assertEqual(len(coder.abs_fnames), 2)
|
| 347 |
+
|
| 348 |
+
@patch("aider.coders.base_coder.openai.ChatCompletion.create")
|
| 349 |
+
def test_run_with_invalid_request_error(self, mock_chat_completion_create):
|
| 350 |
+
# Mock the IO object
|
| 351 |
+
mock_io = MagicMock()
|
| 352 |
+
|
| 353 |
+
# Initialize the Coder object with the mocked IO and mocked repo
|
| 354 |
+
coder = Coder.create(models.GPT4, None, mock_io)
|
| 355 |
+
|
| 356 |
+
# Set up the mock to raise InvalidRequestError
|
| 357 |
+
mock_chat_completion_create.side_effect = openai.error.InvalidRequestError(
|
| 358 |
+
"Invalid request", "param"
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
# Call the run method and assert that InvalidRequestError is raised
|
| 362 |
+
with self.assertRaises(openai.error.InvalidRequestError):
|
| 363 |
+
coder.run(with_message="hi")
|
| 364 |
+
|
| 365 |
+
if __name__ == "__main__":
|
| 366 |
+
unittest.main()
|
testbed/Aider-AI__aider/tests/test_editblock.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
import tempfile
|
| 4 |
+
import unittest
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from unittest.mock import MagicMock, patch
|
| 7 |
+
|
| 8 |
+
from aider import models
|
| 9 |
+
from aider.coders import Coder
|
| 10 |
+
from aider.coders import editblock_coder as eb
|
| 11 |
+
from aider.dump import dump # noqa: F401
|
| 12 |
+
from aider.io import InputOutput
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class TestUtils(unittest.TestCase):
|
| 16 |
+
def setUp(self):
|
| 17 |
+
self.patcher = patch("aider.coders.base_coder.check_model_availability")
|
| 18 |
+
self.mock_check = self.patcher.start()
|
| 19 |
+
self.mock_check.return_value = True
|
| 20 |
+
|
| 21 |
+
def tearDown(self):
|
| 22 |
+
self.patcher.stop()
|
| 23 |
+
|
| 24 |
+
# fuzzy logic disabled v0.11.2-dev
|
| 25 |
+
def __test_replace_most_similar_chunk(self):
|
| 26 |
+
whole = "This is a sample text.\nAnother line of text.\nYet another line.\n"
|
| 27 |
+
part = "This is a sample text\n"
|
| 28 |
+
replace = "This is a replaced text.\n"
|
| 29 |
+
expected_output = "This is a replaced text.\nAnother line of text.\nYet another line.\n"
|
| 30 |
+
|
| 31 |
+
result = eb.replace_most_similar_chunk(whole, part, replace)
|
| 32 |
+
self.assertEqual(result, expected_output)
|
| 33 |
+
|
| 34 |
+
# fuzzy logic disabled v0.11.2-dev
|
| 35 |
+
def __test_replace_most_similar_chunk_not_perfect_match(self):
|
| 36 |
+
whole = "This is a sample text.\nAnother line of text.\nYet another line.\n"
|
| 37 |
+
part = "This was a sample text.\nAnother line of txt\n"
|
| 38 |
+
replace = "This is a replaced text.\nModified line of text.\n"
|
| 39 |
+
expected_output = "This is a replaced text.\nModified line of text.\nYet another line.\n"
|
| 40 |
+
|
| 41 |
+
result = eb.replace_most_similar_chunk(whole, part, replace)
|
| 42 |
+
self.assertEqual(result, expected_output)
|
| 43 |
+
|
| 44 |
+
def test_strip_quoted_wrapping(self):
|
| 45 |
+
input_text = (
|
| 46 |
+
"filename.ext\n```\nWe just want this content\nNot the filename and triple quotes\n```"
|
| 47 |
+
)
|
| 48 |
+
expected_output = "We just want this content\nNot the filename and triple quotes\n"
|
| 49 |
+
result = eb.strip_quoted_wrapping(input_text, "filename.ext")
|
| 50 |
+
self.assertEqual(result, expected_output)
|
| 51 |
+
|
| 52 |
+
def test_strip_quoted_wrapping_no_filename(self):
|
| 53 |
+
input_text = "```\nWe just want this content\nNot the triple quotes\n```"
|
| 54 |
+
expected_output = "We just want this content\nNot the triple quotes\n"
|
| 55 |
+
result = eb.strip_quoted_wrapping(input_text)
|
| 56 |
+
self.assertEqual(result, expected_output)
|
| 57 |
+
|
| 58 |
+
def test_strip_quoted_wrapping_no_wrapping(self):
|
| 59 |
+
input_text = "We just want this content\nNot the triple quotes\n"
|
| 60 |
+
expected_output = "We just want this content\nNot the triple quotes\n"
|
| 61 |
+
result = eb.strip_quoted_wrapping(input_text)
|
| 62 |
+
self.assertEqual(result, expected_output)
|
| 63 |
+
|
| 64 |
+
def test_find_original_update_blocks(self):
|
| 65 |
+
edit = """
|
| 66 |
+
Here's the change:
|
| 67 |
+
|
| 68 |
+
```text
|
| 69 |
+
foo.txt
|
| 70 |
+
<<<<<<< HEAD
|
| 71 |
+
Two
|
| 72 |
+
=======
|
| 73 |
+
Tooooo
|
| 74 |
+
>>>>>>> updated
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
Hope you like it!
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
edits = list(eb.find_original_update_blocks(edit))
|
| 81 |
+
self.assertEqual(edits, [("foo.txt", "Two\n", "Tooooo\n")])
|
| 82 |
+
|
| 83 |
+
def test_find_original_update_blocks_quote_below_filename(self):
|
| 84 |
+
edit = """
|
| 85 |
+
Here's the change:
|
| 86 |
+
|
| 87 |
+
foo.txt
|
| 88 |
+
```text
|
| 89 |
+
<<<<<<< HEAD
|
| 90 |
+
Two
|
| 91 |
+
=======
|
| 92 |
+
Tooooo
|
| 93 |
+
>>>>>>> updated
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
Hope you like it!
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
edits = list(eb.find_original_update_blocks(edit))
|
| 100 |
+
self.assertEqual(edits, [("foo.txt", "Two\n", "Tooooo\n")])
|
| 101 |
+
|
| 102 |
+
def test_find_original_update_blocks_unclosed(self):
|
| 103 |
+
edit = """
|
| 104 |
+
Here's the change:
|
| 105 |
+
|
| 106 |
+
```text
|
| 107 |
+
foo.txt
|
| 108 |
+
<<<<<<< HEAD
|
| 109 |
+
Two
|
| 110 |
+
=======
|
| 111 |
+
Tooooo
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
oops!
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
with self.assertRaises(ValueError) as cm:
|
| 118 |
+
list(eb.find_original_update_blocks(edit))
|
| 119 |
+
self.assertIn("Incomplete", str(cm.exception))
|
| 120 |
+
|
| 121 |
+
def test_find_original_update_blocks_missing_filename(self):
|
| 122 |
+
edit = """
|
| 123 |
+
Here's the change:
|
| 124 |
+
|
| 125 |
+
```text
|
| 126 |
+
<<<<<<< HEAD
|
| 127 |
+
Two
|
| 128 |
+
=======
|
| 129 |
+
Tooooo
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
oops!
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
with self.assertRaises(ValueError) as cm:
|
| 136 |
+
list(eb.find_original_update_blocks(edit))
|
| 137 |
+
self.assertIn("filename", str(cm.exception))
|
| 138 |
+
|
| 139 |
+
def test_find_original_update_blocks_no_final_newline(self):
|
| 140 |
+
edit = """
|
| 141 |
+
aider/coder.py
|
| 142 |
+
<<<<<<< HEAD
|
| 143 |
+
self.console.print("[red]^C again to quit")
|
| 144 |
+
=======
|
| 145 |
+
self.io.tool_error("^C again to quit")
|
| 146 |
+
>>>>>>> updated
|
| 147 |
+
|
| 148 |
+
aider/coder.py
|
| 149 |
+
<<<<<<< HEAD
|
| 150 |
+
self.io.tool_error("Malformed ORIGINAL/UPDATE blocks, retrying...")
|
| 151 |
+
self.io.tool_error(err)
|
| 152 |
+
=======
|
| 153 |
+
self.io.tool_error("Malformed ORIGINAL/UPDATE blocks, retrying...")
|
| 154 |
+
self.io.tool_error(str(err))
|
| 155 |
+
>>>>>>> updated
|
| 156 |
+
|
| 157 |
+
aider/coder.py
|
| 158 |
+
<<<<<<< HEAD
|
| 159 |
+
self.console.print("[red]Unable to get commit message from gpt-3.5-turbo. Use /commit to try again.\n")
|
| 160 |
+
=======
|
| 161 |
+
self.io.tool_error("Unable to get commit message from gpt-3.5-turbo. Use /commit to try again.")
|
| 162 |
+
>>>>>>> updated
|
| 163 |
+
|
| 164 |
+
aider/coder.py
|
| 165 |
+
<<<<<<< HEAD
|
| 166 |
+
self.console.print("[red]Skipped commmit.")
|
| 167 |
+
=======
|
| 168 |
+
self.io.tool_error("Skipped commmit.")
|
| 169 |
+
>>>>>>> updated"""
|
| 170 |
+
|
| 171 |
+
# Should not raise a ValueError
|
| 172 |
+
list(eb.find_original_update_blocks(edit))
|
| 173 |
+
|
| 174 |
+
def test_incomplete_edit_block_missing_filename(self):
|
| 175 |
+
edit = """
|
| 176 |
+
No problem! Here are the changes to patch `subprocess.check_output` instead of `subprocess.run` in both tests:
|
| 177 |
+
|
| 178 |
+
```python
|
| 179 |
+
tests/test_repomap.py
|
| 180 |
+
<<<<<<< HEAD
|
| 181 |
+
def test_check_for_ctags_failure(self):
|
| 182 |
+
with patch("subprocess.run") as mock_run:
|
| 183 |
+
mock_run.side_effect = Exception("ctags not found")
|
| 184 |
+
=======
|
| 185 |
+
def test_check_for_ctags_failure(self):
|
| 186 |
+
with patch("subprocess.check_output") as mock_check_output:
|
| 187 |
+
mock_check_output.side_effect = Exception("ctags not found")
|
| 188 |
+
>>>>>>> updated
|
| 189 |
+
|
| 190 |
+
<<<<<<< HEAD
|
| 191 |
+
def test_check_for_ctags_success(self):
|
| 192 |
+
with patch("subprocess.run") as mock_run:
|
| 193 |
+
mock_run.return_value = CompletedProcess(args=["ctags", "--version"], returncode=0, stdout='''{
|
| 194 |
+
"_type": "tag",
|
| 195 |
+
"name": "status",
|
| 196 |
+
"path": "aider/main.py",
|
| 197 |
+
"pattern": "/^ status = main()$/",
|
| 198 |
+
"kind": "variable"
|
| 199 |
+
}''')
|
| 200 |
+
=======
|
| 201 |
+
def test_check_for_ctags_success(self):
|
| 202 |
+
with patch("subprocess.check_output") as mock_check_output:
|
| 203 |
+
mock_check_output.return_value = '''{
|
| 204 |
+
"_type": "tag",
|
| 205 |
+
"name": "status",
|
| 206 |
+
"path": "aider/main.py",
|
| 207 |
+
"pattern": "/^ status = main()$/",
|
| 208 |
+
"kind": "variable"
|
| 209 |
+
}'''
|
| 210 |
+
>>>>>>> updated
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
These changes replace the `subprocess.run` patches with `subprocess.check_output` patches in both `test_check_for_ctags_failure` and `test_check_for_ctags_success` tests.
|
| 214 |
+
"""
|
| 215 |
+
edit_blocks = list(eb.find_original_update_blocks(edit))
|
| 216 |
+
self.assertEqual(len(edit_blocks), 2) # 2 edits
|
| 217 |
+
self.assertEqual(edit_blocks[0][0], "tests/test_repomap.py")
|
| 218 |
+
self.assertEqual(edit_blocks[1][0], "tests/test_repomap.py")
|
| 219 |
+
|
| 220 |
+
def test_replace_part_with_missing_varied_leading_whitespace(self):
|
| 221 |
+
whole = """
|
| 222 |
+
line1
|
| 223 |
+
line2
|
| 224 |
+
line3
|
| 225 |
+
line4
|
| 226 |
+
"""
|
| 227 |
+
|
| 228 |
+
part = "line2\n line3\n"
|
| 229 |
+
replace = "new_line2\n new_line3\n"
|
| 230 |
+
expected_output = """
|
| 231 |
+
line1
|
| 232 |
+
new_line2
|
| 233 |
+
new_line3
|
| 234 |
+
line4
|
| 235 |
+
"""
|
| 236 |
+
|
| 237 |
+
result = eb.replace_most_similar_chunk(whole, part, replace)
|
| 238 |
+
self.assertEqual(result, expected_output)
|
| 239 |
+
|
| 240 |
+
def test_replace_part_with_missing_leading_whitespace(self):
|
| 241 |
+
whole = " line1\n line2\n line3\n"
|
| 242 |
+
part = "line1\nline2\n"
|
| 243 |
+
replace = "new_line1\nnew_line2\n"
|
| 244 |
+
expected_output = " new_line1\n new_line2\n line3\n"
|
| 245 |
+
|
| 246 |
+
result = eb.replace_most_similar_chunk(whole, part, replace)
|
| 247 |
+
self.assertEqual(result, expected_output)
|
| 248 |
+
|
| 249 |
+
def test_replace_part_with_just_some_missing_leading_whitespace(self):
|
| 250 |
+
whole = " line1\n line2\n line3\n"
|
| 251 |
+
part = " line1\n line2\n"
|
| 252 |
+
replace = " new_line1\n new_line2\n"
|
| 253 |
+
expected_output = " new_line1\n new_line2\n line3\n"
|
| 254 |
+
|
| 255 |
+
result = eb.replace_most_similar_chunk(whole, part, replace)
|
| 256 |
+
self.assertEqual(result, expected_output)
|
| 257 |
+
|
| 258 |
+
def test_replace_part_with_missing_leading_whitespace_including_blank_line(self):
|
| 259 |
+
"""
|
| 260 |
+
The part has leading whitespace on all lines, so should be ignored.
|
| 261 |
+
But it has a *blank* line with no whitespace at all, which was causing a
|
| 262 |
+
bug per issue #25. Test case to repro and confirm fix.
|
| 263 |
+
"""
|
| 264 |
+
whole = " line1\n line2\n line3\n"
|
| 265 |
+
part = "\n line1\n line2\n"
|
| 266 |
+
replace = " new_line1\n new_line2\n"
|
| 267 |
+
expected_output = " new_line1\n new_line2\n line3\n"
|
| 268 |
+
|
| 269 |
+
result = eb.replace_most_similar_chunk(whole, part, replace)
|
| 270 |
+
self.assertEqual(result, expected_output)
|
| 271 |
+
|
| 272 |
+
def test_full_edit(self):
|
| 273 |
+
# Create a few temporary files
|
| 274 |
+
_, file1 = tempfile.mkstemp()
|
| 275 |
+
|
| 276 |
+
with open(file1, "w", encoding="utf-8") as f:
|
| 277 |
+
f.write("one\ntwo\nthree\n")
|
| 278 |
+
|
| 279 |
+
files = [file1]
|
| 280 |
+
|
| 281 |
+
# Initialize the Coder object with the mocked IO and mocked repo
|
| 282 |
+
coder = Coder.create(models.GPT4, "diff", io=InputOutput(), fnames=files)
|
| 283 |
+
|
| 284 |
+
def mock_send(*args, **kwargs):
|
| 285 |
+
coder.partial_response_content = f"""
|
| 286 |
+
Do this:
|
| 287 |
+
|
| 288 |
+
{Path(file1).name}
|
| 289 |
+
<<<<<<< HEAD
|
| 290 |
+
two
|
| 291 |
+
=======
|
| 292 |
+
new
|
| 293 |
+
>>>>>>> updated
|
| 294 |
+
|
| 295 |
+
"""
|
| 296 |
+
coder.partial_response_function_call = dict()
|
| 297 |
+
|
| 298 |
+
coder.send = MagicMock(side_effect=mock_send)
|
| 299 |
+
|
| 300 |
+
# Call the run method with a message
|
| 301 |
+
coder.run(with_message="hi")
|
| 302 |
+
|
| 303 |
+
content = Path(file1).read_text(encoding="utf-8")
|
| 304 |
+
self.assertEqual(content, "one\nnew\nthree\n")
|
| 305 |
+
|
| 306 |
+
def test_full_edit_dry_run(self):
|
| 307 |
+
# Create a few temporary files
|
| 308 |
+
_, file1 = tempfile.mkstemp()
|
| 309 |
+
|
| 310 |
+
orig_content = "one\ntwo\nthree\n"
|
| 311 |
+
|
| 312 |
+
with open(file1, "w", encoding="utf-8") as f:
|
| 313 |
+
f.write(orig_content)
|
| 314 |
+
|
| 315 |
+
files = [file1]
|
| 316 |
+
|
| 317 |
+
# Initialize the Coder object with the mocked IO and mocked repo
|
| 318 |
+
coder = Coder.create(
|
| 319 |
+
models.GPT4,
|
| 320 |
+
"diff",
|
| 321 |
+
io=InputOutput(dry_run=True),
|
| 322 |
+
fnames=files,
|
| 323 |
+
dry_run=True,
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
def mock_send(*args, **kwargs):
|
| 327 |
+
coder.partial_response_content = f"""
|
| 328 |
+
Do this:
|
| 329 |
+
|
| 330 |
+
{Path(file1).name}
|
| 331 |
+
<<<<<<< HEAD
|
| 332 |
+
two
|
| 333 |
+
=======
|
| 334 |
+
new
|
| 335 |
+
>>>>>>> updated
|
| 336 |
+
|
| 337 |
+
"""
|
| 338 |
+
coder.partial_response_function_call = dict()
|
| 339 |
+
|
| 340 |
+
coder.send = MagicMock(side_effect=mock_send)
|
| 341 |
+
|
| 342 |
+
# Call the run method with a message
|
| 343 |
+
coder.run(with_message="hi")
|
| 344 |
+
|
| 345 |
+
content = Path(file1).read_text(encoding="utf-8")
|
| 346 |
+
self.assertEqual(content, orig_content)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
if __name__ == "__main__":
|
| 350 |
+
unittest.main()
|
testbed/Aider-AI__aider/tests/test_io.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import unittest
|
| 3 |
+
from unittest.mock import patch
|
| 4 |
+
|
| 5 |
+
from aider.io import AutoCompleter, InputOutput
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TestInputOutput(unittest.TestCase):
|
| 9 |
+
def test_no_color_environment_variable(self):
|
| 10 |
+
with patch.dict(os.environ, {"NO_COLOR": "1"}):
|
| 11 |
+
io = InputOutput()
|
| 12 |
+
self.assertFalse(io.pretty)
|
| 13 |
+
|
| 14 |
+
def test_autocompleter_with_non_existent_file(self):
|
| 15 |
+
root = ""
|
| 16 |
+
rel_fnames = ["non_existent_file.txt"]
|
| 17 |
+
addable_rel_fnames = []
|
| 18 |
+
commands = None
|
| 19 |
+
autocompleter = AutoCompleter(root, rel_fnames, addable_rel_fnames, commands, "utf-8")
|
| 20 |
+
self.assertEqual(autocompleter.words, set(rel_fnames))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
if __name__ == "__main__":
|
| 24 |
+
unittest.main()
|
testbed/Aider-AI__aider/tests/test_main.py
ADDED
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
import subprocess
|
| 4 |
+
import tempfile
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from unittest import TestCase
|
| 7 |
+
from unittest.mock import patch
|
| 8 |
+
|
| 9 |
+
import git
|
| 10 |
+
from prompt_toolkit.input import DummyInput
|
| 11 |
+
from prompt_toolkit.output import DummyOutput
|
| 12 |
+
|
| 13 |
+
from aider.dump import dump # noqa: F401
|
| 14 |
+
from aider.io import InputOutput
|
| 15 |
+
from aider.main import check_gitignore, main, setup_git
|
| 16 |
+
from tests.utils import make_repo
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestMain(TestCase):
|
| 20 |
+
def setUp(self):
|
| 21 |
+
os.environ["OPENAI_API_KEY"] = "deadbeef"
|
| 22 |
+
self.original_cwd = os.getcwd()
|
| 23 |
+
self.tempdir = tempfile.mkdtemp()
|
| 24 |
+
os.chdir(self.tempdir)
|
| 25 |
+
self.patcher = patch("aider.coders.base_coder.check_model_availability")
|
| 26 |
+
self.mock_check = self.patcher.start()
|
| 27 |
+
self.mock_check.return_value = True
|
| 28 |
+
|
| 29 |
+
def tearDown(self):
|
| 30 |
+
os.chdir(self.original_cwd)
|
| 31 |
+
shutil.rmtree(self.tempdir, ignore_errors=True)
|
| 32 |
+
self.patcher.stop()
|
| 33 |
+
|
| 34 |
+
def test_main_with_empty_dir_no_files_on_command(self):
|
| 35 |
+
main(["--no-git"], input=DummyInput(), output=DummyOutput())
|
| 36 |
+
|
| 37 |
+
def test_main_with_empty_dir_new_file(self):
|
| 38 |
+
main(["foo.txt", "--yes", "--no-git"], input=DummyInput(), output=DummyOutput())
|
| 39 |
+
self.assertTrue(os.path.exists("foo.txt"))
|
| 40 |
+
|
| 41 |
+
@patch("aider.repo.GitRepo.get_commit_message", return_value="mock commit message")
|
| 42 |
+
def test_main_with_empty_git_dir_new_file(self, _):
|
| 43 |
+
make_repo()
|
| 44 |
+
main(["--yes", "foo.txt"], input=DummyInput(), output=DummyOutput())
|
| 45 |
+
self.assertTrue(os.path.exists("foo.txt"))
|
| 46 |
+
|
| 47 |
+
@patch("aider.repo.GitRepo.get_commit_message", return_value="mock commit message")
|
| 48 |
+
def test_main_with_empty_git_dir_new_files(self, _):
|
| 49 |
+
make_repo()
|
| 50 |
+
main(["--yes", "foo.txt", "bar.txt"], input=DummyInput(), output=DummyOutput())
|
| 51 |
+
self.assertTrue(os.path.exists("foo.txt"))
|
| 52 |
+
self.assertTrue(os.path.exists("bar.txt"))
|
| 53 |
+
|
| 54 |
+
def test_main_with_dname_and_fname(self):
|
| 55 |
+
subdir = Path("subdir")
|
| 56 |
+
subdir.mkdir()
|
| 57 |
+
make_repo(str(subdir))
|
| 58 |
+
res = main(["subdir", "foo.txt"], input=DummyInput(), output=DummyOutput())
|
| 59 |
+
self.assertNotEqual(res, None)
|
| 60 |
+
|
| 61 |
+
@patch("aider.repo.GitRepo.get_commit_message", return_value="mock commit message")
|
| 62 |
+
def test_main_with_subdir_repo_fnames(self, _):
|
| 63 |
+
subdir = Path("subdir")
|
| 64 |
+
subdir.mkdir()
|
| 65 |
+
make_repo(str(subdir))
|
| 66 |
+
main(
|
| 67 |
+
["--yes", str(subdir / "foo.txt"), str(subdir / "bar.txt")],
|
| 68 |
+
input=DummyInput(),
|
| 69 |
+
output=DummyOutput(),
|
| 70 |
+
)
|
| 71 |
+
self.assertTrue((subdir / "foo.txt").exists())
|
| 72 |
+
self.assertTrue((subdir / "bar.txt").exists())
|
| 73 |
+
|
| 74 |
+
def test_main_with_git_config_yml(self):
|
| 75 |
+
make_repo()
|
| 76 |
+
|
| 77 |
+
Path(".aider.conf.yml").write_text("no-auto-commits: true\n")
|
| 78 |
+
with patch("aider.main.Coder.create") as MockCoder:
|
| 79 |
+
main(["--yes"], input=DummyInput(), output=DummyOutput())
|
| 80 |
+
_, kwargs = MockCoder.call_args
|
| 81 |
+
assert kwargs["auto_commits"] is False
|
| 82 |
+
|
| 83 |
+
Path(".aider.conf.yml").write_text("auto-commits: true\n")
|
| 84 |
+
with patch("aider.main.Coder.create") as MockCoder:
|
| 85 |
+
main([], input=DummyInput(), output=DummyOutput())
|
| 86 |
+
_, kwargs = MockCoder.call_args
|
| 87 |
+
assert kwargs["auto_commits"] is True
|
| 88 |
+
|
| 89 |
+
def test_main_with_empty_git_dir_new_subdir_file(self):
|
| 90 |
+
make_repo()
|
| 91 |
+
subdir = Path("subdir")
|
| 92 |
+
subdir.mkdir()
|
| 93 |
+
fname = subdir / "foo.txt"
|
| 94 |
+
fname.touch()
|
| 95 |
+
subprocess.run(["git", "add", str(subdir)])
|
| 96 |
+
subprocess.run(["git", "commit", "-m", "added"])
|
| 97 |
+
|
| 98 |
+
# This will throw a git error on windows if get_tracked_files doesn't
|
| 99 |
+
# properly convert git/posix/paths to git\posix\paths.
|
| 100 |
+
# Because aider will try and `git add` a file that's already in the repo.
|
| 101 |
+
main(["--yes", str(fname)], input=DummyInput(), output=DummyOutput())
|
| 102 |
+
|
| 103 |
+
def test_setup_git(self):
|
| 104 |
+
io = InputOutput(pretty=False, yes=True)
|
| 105 |
+
git_root = setup_git(None, io)
|
| 106 |
+
git_root = Path(git_root).resolve()
|
| 107 |
+
self.assertEqual(git_root, Path(self.tempdir).resolve())
|
| 108 |
+
|
| 109 |
+
self.assertTrue(git.Repo(self.tempdir))
|
| 110 |
+
|
| 111 |
+
gitignore = Path.cwd() / ".gitignore"
|
| 112 |
+
self.assertTrue(gitignore.exists())
|
| 113 |
+
self.assertEqual(".aider*", gitignore.read_text().splitlines()[0])
|
| 114 |
+
|
| 115 |
+
def test_check_gitignore(self):
|
| 116 |
+
make_repo()
|
| 117 |
+
io = InputOutput(pretty=False, yes=True)
|
| 118 |
+
cwd = Path.cwd()
|
| 119 |
+
gitignore = cwd / ".gitignore"
|
| 120 |
+
|
| 121 |
+
self.assertFalse(gitignore.exists())
|
| 122 |
+
check_gitignore(cwd, io)
|
| 123 |
+
self.assertTrue(gitignore.exists())
|
| 124 |
+
|
| 125 |
+
self.assertEqual(".aider*", gitignore.read_text().splitlines()[0])
|
| 126 |
+
|
| 127 |
+
gitignore.write_text("one\ntwo\n")
|
| 128 |
+
check_gitignore(cwd, io)
|
| 129 |
+
self.assertEqual("one\ntwo\n.aider*\n", gitignore.read_text())
|
| 130 |
+
|
| 131 |
+
def test_main_git_ignore(self):
|
| 132 |
+
cwd = Path().cwd()
|
| 133 |
+
self.assertFalse((cwd / ".git").exists())
|
| 134 |
+
self.assertFalse((cwd / ".gitignore").exists())
|
| 135 |
+
|
| 136 |
+
with patch("aider.main.Coder.create"):
|
| 137 |
+
main(["--yes"], input=DummyInput())
|
| 138 |
+
|
| 139 |
+
self.assertTrue((cwd / ".git").exists())
|
| 140 |
+
self.assertTrue((cwd / ".gitignore").exists())
|
| 141 |
+
|
| 142 |
+
def test_main_args(self):
|
| 143 |
+
with patch("aider.main.Coder.create") as MockCoder:
|
| 144 |
+
# --yes will just ok the git repo without blocking on input
|
| 145 |
+
# following calls to main will see the new repo already
|
| 146 |
+
main(["--no-auto-commits", "--yes"], input=DummyInput())
|
| 147 |
+
_, kwargs = MockCoder.call_args
|
| 148 |
+
assert kwargs["auto_commits"] is False
|
| 149 |
+
|
| 150 |
+
with patch("aider.main.Coder.create") as MockCoder:
|
| 151 |
+
main(["--auto-commits"], input=DummyInput())
|
| 152 |
+
_, kwargs = MockCoder.call_args
|
| 153 |
+
assert kwargs["auto_commits"] is True
|
| 154 |
+
|
| 155 |
+
with patch("aider.main.Coder.create") as MockCoder:
|
| 156 |
+
main([], input=DummyInput())
|
| 157 |
+
_, kwargs = MockCoder.call_args
|
| 158 |
+
assert kwargs["dirty_commits"] is True
|
| 159 |
+
assert kwargs["auto_commits"] is True
|
| 160 |
+
assert kwargs["pretty"] is True
|
| 161 |
+
|
| 162 |
+
with patch("aider.main.Coder.create") as MockCoder:
|
| 163 |
+
main(["--no-pretty"], input=DummyInput())
|
| 164 |
+
_, kwargs = MockCoder.call_args
|
| 165 |
+
assert kwargs["pretty"] is False
|
| 166 |
+
|
| 167 |
+
with patch("aider.main.Coder.create") as MockCoder:
|
| 168 |
+
main(["--pretty"], input=DummyInput())
|
| 169 |
+
_, kwargs = MockCoder.call_args
|
| 170 |
+
assert kwargs["pretty"] is True
|
| 171 |
+
|
| 172 |
+
with patch("aider.main.Coder.create") as MockCoder:
|
| 173 |
+
main(["--no-dirty-commits"], input=DummyInput())
|
| 174 |
+
_, kwargs = MockCoder.call_args
|
| 175 |
+
assert kwargs["dirty_commits"] is False
|
| 176 |
+
|
| 177 |
+
with patch("aider.main.Coder.create") as MockCoder:
|
| 178 |
+
main(["--dirty-commits"], input=DummyInput())
|
| 179 |
+
_, kwargs = MockCoder.call_args
|
| 180 |
+
assert kwargs["dirty_commits"] is True
|
testbed/Aider-AI__aider/tests/test_repo.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
import unittest
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from unittest.mock import patch
|
| 6 |
+
|
| 7 |
+
import git
|
| 8 |
+
|
| 9 |
+
from aider.dump import dump # noqa: F401
|
| 10 |
+
from aider.io import InputOutput
|
| 11 |
+
from aider.repo import GitRepo
|
| 12 |
+
from tests.utils import GitTemporaryDirectory
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class TestRepo(unittest.TestCase):
|
| 16 |
+
def test_diffs_empty_repo(self):
|
| 17 |
+
with GitTemporaryDirectory():
|
| 18 |
+
repo = git.Repo()
|
| 19 |
+
|
| 20 |
+
# Add a change to the index
|
| 21 |
+
fname = Path("foo.txt")
|
| 22 |
+
fname.write_text("index\n")
|
| 23 |
+
repo.git.add(str(fname))
|
| 24 |
+
|
| 25 |
+
# Make a change in the working dir
|
| 26 |
+
fname.write_text("workingdir\n")
|
| 27 |
+
|
| 28 |
+
git_repo = GitRepo(InputOutput(), None, ".")
|
| 29 |
+
diffs = git_repo.get_diffs(False)
|
| 30 |
+
self.assertIn("index", diffs)
|
| 31 |
+
self.assertIn("workingdir", diffs)
|
| 32 |
+
|
| 33 |
+
def test_diffs_nonempty_repo(self):
|
| 34 |
+
with GitTemporaryDirectory():
|
| 35 |
+
repo = git.Repo()
|
| 36 |
+
fname = Path("foo.txt")
|
| 37 |
+
fname.touch()
|
| 38 |
+
repo.git.add(str(fname))
|
| 39 |
+
|
| 40 |
+
fname2 = Path("bar.txt")
|
| 41 |
+
fname2.touch()
|
| 42 |
+
repo.git.add(str(fname2))
|
| 43 |
+
|
| 44 |
+
repo.git.commit("-m", "initial")
|
| 45 |
+
|
| 46 |
+
fname.write_text("index\n")
|
| 47 |
+
repo.git.add(str(fname))
|
| 48 |
+
|
| 49 |
+
fname2.write_text("workingdir\n")
|
| 50 |
+
|
| 51 |
+
git_repo = GitRepo(InputOutput(), None, ".")
|
| 52 |
+
diffs = git_repo.get_diffs(False)
|
| 53 |
+
self.assertIn("index", diffs)
|
| 54 |
+
self.assertIn("workingdir", diffs)
|
| 55 |
+
|
| 56 |
+
def test_diffs_between_commits(self):
|
| 57 |
+
with GitTemporaryDirectory():
|
| 58 |
+
repo = git.Repo()
|
| 59 |
+
fname = Path("foo.txt")
|
| 60 |
+
|
| 61 |
+
fname.write_text("one\n")
|
| 62 |
+
repo.git.add(str(fname))
|
| 63 |
+
repo.git.commit("-m", "initial")
|
| 64 |
+
|
| 65 |
+
fname.write_text("two\n")
|
| 66 |
+
repo.git.add(str(fname))
|
| 67 |
+
repo.git.commit("-m", "second")
|
| 68 |
+
|
| 69 |
+
git_repo = GitRepo(InputOutput(), None, ".")
|
| 70 |
+
diffs = git_repo.get_diffs(False, ["HEAD~1", "HEAD"])
|
| 71 |
+
dump(diffs)
|
| 72 |
+
self.assertIn("two", diffs)
|
| 73 |
+
|
| 74 |
+
@patch("aider.repo.simple_send_with_retries")
|
| 75 |
+
def test_get_commit_message(self, mock_send):
|
| 76 |
+
mock_send.return_value = "a good commit message"
|
| 77 |
+
|
| 78 |
+
repo = GitRepo(InputOutput(), None, None)
|
| 79 |
+
# Call the get_commit_message method with dummy diff and context
|
| 80 |
+
result = repo.get_commit_message("dummy diff", "dummy context")
|
| 81 |
+
|
| 82 |
+
# Assert that the returned message is the expected one
|
| 83 |
+
self.assertEqual(result, "a good commit message")
|
| 84 |
+
|
| 85 |
+
@patch("aider.repo.simple_send_with_retries")
|
| 86 |
+
def test_get_commit_message_strip_quotes(self, mock_send):
|
| 87 |
+
mock_send.return_value = '"a good commit message"'
|
| 88 |
+
|
| 89 |
+
repo = GitRepo(InputOutput(), None, None)
|
| 90 |
+
# Call the get_commit_message method with dummy diff and context
|
| 91 |
+
result = repo.get_commit_message("dummy diff", "dummy context")
|
| 92 |
+
|
| 93 |
+
# Assert that the returned message is the expected one
|
| 94 |
+
self.assertEqual(result, "a good commit message")
|
| 95 |
+
|
| 96 |
+
@patch("aider.repo.simple_send_with_retries")
|
| 97 |
+
def test_get_commit_message_no_strip_unmatched_quotes(self, mock_send):
|
| 98 |
+
mock_send.return_value = 'a good "commit message"'
|
| 99 |
+
|
| 100 |
+
repo = GitRepo(InputOutput(), None, None)
|
| 101 |
+
# Call the get_commit_message method with dummy diff and context
|
| 102 |
+
result = repo.get_commit_message("dummy diff", "dummy context")
|
| 103 |
+
|
| 104 |
+
# Assert that the returned message is the expected one
|
| 105 |
+
self.assertEqual(result, 'a good "commit message"')
|
| 106 |
+
|
| 107 |
+
def test_get_tracked_files(self):
|
| 108 |
+
# Create a temporary directory
|
| 109 |
+
tempdir = Path(tempfile.mkdtemp())
|
| 110 |
+
|
| 111 |
+
# Initialize a git repository in the temporary directory and set user name and email
|
| 112 |
+
repo = git.Repo.init(tempdir)
|
| 113 |
+
repo.config_writer().set_value("user", "name", "Test User").release()
|
| 114 |
+
repo.config_writer().set_value("user", "email", "testuser@example.com").release()
|
| 115 |
+
|
| 116 |
+
# Create three empty files and add them to the git repository
|
| 117 |
+
filenames = ["README.md", "subdir/fänny.md", "systemüber/blick.md", 'file"with"quotes.txt']
|
| 118 |
+
created_files = []
|
| 119 |
+
for filename in filenames:
|
| 120 |
+
file_path = tempdir / filename
|
| 121 |
+
try:
|
| 122 |
+
file_path.parent.mkdir(parents=True, exist_ok=True)
|
| 123 |
+
file_path.touch()
|
| 124 |
+
repo.git.add(str(file_path))
|
| 125 |
+
created_files.append(Path(filename))
|
| 126 |
+
except OSError:
|
| 127 |
+
# windows won't allow files with quotes, that's ok
|
| 128 |
+
self.assertIn('"', filename)
|
| 129 |
+
self.assertEqual(os.name, "nt")
|
| 130 |
+
|
| 131 |
+
self.assertTrue(len(created_files) >= 3)
|
| 132 |
+
|
| 133 |
+
repo.git.commit("-m", "added")
|
| 134 |
+
|
| 135 |
+
tracked_files = GitRepo(InputOutput(), [tempdir], None).get_tracked_files()
|
| 136 |
+
|
| 137 |
+
# On windows, paths will come back \like\this, so normalize them back to Paths
|
| 138 |
+
tracked_files = [Path(fn) for fn in tracked_files]
|
| 139 |
+
|
| 140 |
+
# Assert that coder.get_tracked_files() returns the three filenames
|
| 141 |
+
self.assertEqual(set(tracked_files), set(created_files))
|
| 142 |
+
|
| 143 |
+
def test_get_tracked_files_with_new_staged_file(self):
|
| 144 |
+
with GitTemporaryDirectory():
|
| 145 |
+
# new repo
|
| 146 |
+
raw_repo = git.Repo()
|
| 147 |
+
|
| 148 |
+
# add it, but no commits at all in the raw_repo yet
|
| 149 |
+
fname = Path("new.txt")
|
| 150 |
+
fname.touch()
|
| 151 |
+
raw_repo.git.add(str(fname))
|
| 152 |
+
|
| 153 |
+
git_repo = GitRepo(InputOutput(), None, None)
|
| 154 |
+
|
| 155 |
+
# better be there
|
| 156 |
+
fnames = git_repo.get_tracked_files()
|
| 157 |
+
self.assertIn(str(fname), fnames)
|
| 158 |
+
|
| 159 |
+
# commit it, better still be there
|
| 160 |
+
raw_repo.git.commit("-m", "new")
|
| 161 |
+
fnames = git_repo.get_tracked_files()
|
| 162 |
+
self.assertIn(str(fname), fnames)
|
| 163 |
+
|
| 164 |
+
# new file, added but not committed
|
| 165 |
+
fname2 = Path("new2.txt")
|
| 166 |
+
fname2.touch()
|
| 167 |
+
raw_repo.git.add(str(fname2))
|
| 168 |
+
|
| 169 |
+
# both should be there
|
| 170 |
+
fnames = git_repo.get_tracked_files()
|
| 171 |
+
self.assertIn(str(fname), fnames)
|
| 172 |
+
self.assertIn(str(fname2), fnames)
|
| 173 |
+
|
| 174 |
+
def test_get_tracked_files_from_subdir(self):
|
| 175 |
+
with GitTemporaryDirectory():
|
| 176 |
+
# new repo
|
| 177 |
+
raw_repo = git.Repo()
|
| 178 |
+
|
| 179 |
+
# add it, but no commits at all in the raw_repo yet
|
| 180 |
+
fname = Path("subdir/new.txt")
|
| 181 |
+
fname.parent.mkdir()
|
| 182 |
+
fname.touch()
|
| 183 |
+
raw_repo.git.add(str(fname))
|
| 184 |
+
|
| 185 |
+
os.chdir(fname.parent)
|
| 186 |
+
|
| 187 |
+
git_repo = GitRepo(InputOutput(), None, None)
|
| 188 |
+
|
| 189 |
+
# better be there
|
| 190 |
+
fnames = git_repo.get_tracked_files()
|
| 191 |
+
self.assertIn(str(fname), fnames)
|
| 192 |
+
|
| 193 |
+
# commit it, better still be there
|
| 194 |
+
raw_repo.git.commit("-m", "new")
|
| 195 |
+
fnames = git_repo.get_tracked_files()
|
| 196 |
+
self.assertIn(str(fname), fnames)
|