aider: Refactored get_completions to read and split file in init.

# Context:
USER: refactor get_completions so that the file reading and splitting happens in init
ASSISTANT: To refactor the `get_completions` method in the `FileContentCompleter` class, we will move the file reading and splitting logic to the `__init__` method and store the words in an instance variable. Here's the updated code:

```python
aider/getinput.py
<<<<<<< ORIGINAL
class FileContentCompleter(Completer):
    def __init__(self, fnames):
        self.fnames = fnames

    def get_completions(self, document, complete_event):
        text = document.text_before_cursor
        words = text.split()
        if not words:
            return

        last_word = words[-1]
        for fname in self.fnames:
            with open(fname, "r") as f:
                content = f.read()

            for word in re.split(r'\W+', content):
                if word.startswith(last_word):
                    yield Completion(word, start_position=-len(last_word))
=======
class FileContentCompleter(Completer):
    def __init__(self, fnames):
        self.words = []
        for fname in fnames:
            with open(fname, "r") as f:
                content = f.read()
            self.words.extend(re.split(r'\W+', content))

    def get_completions(self, document, complete_event):
        text = document.text_before_cursor
        words = text.split()
        if not words:
            return

        last_word = words[-1]
        for word in self.words:
            if word.startswith(last_word):
                yield Completion(word, start_position=-len(last_word))
>>>>>>> UPDATED
```

This change moves the file reading and splitting logic to the `__init__` method and stores the words in the `self.words` instance variable. The `get_completions` method now only iterates through `self.words` to find completions.
This commit is contained in:
Paul Gauthier 2023-05-10 10:54:47 -07:00
parent b267f6e79d
commit 9c7d308deb

View file

@ -27,7 +27,11 @@ class Commands:
class FileContentCompleter(Completer):
def __init__(self, fnames):
self.fnames = fnames
self.words = []
for fname in fnames:
with open(fname, "r") as f:
content = f.read()
self.words.extend(re.split(r'\W+', content))
def get_completions(self, document, complete_event):
text = document.text_before_cursor
@ -36,14 +40,9 @@ class FileContentCompleter(Completer):
return
last_word = words[-1]
for fname in self.fnames:
with open(fname, "r") as f:
content = f.read()
for word in re.split(r'\W+', content):
if word.startswith(last_word):
yield Completion(word, start_position=-len(last_word))
for word in self.words:
if word.startswith(last_word):
yield Completion(word, start_position=-len(last_word))
def canned_input(show_prompt):
console = Console()