Repository navigation
Expand file tree
/
Copy pathrepo.py
More file actions
259 lines (198 loc) · 7.46 KB
/
Copy pathrepo.py
File metadata and controls
259 lines (198 loc) · 7.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import os
from pathlib import Path, PurePosixPath
import git
import pathspec
from aider import prompts, utils
from aider.models import DEFAULT_WEAK_MODEL_NAME, Model
from aider.sendchat import simple_send_with_retries
from .dump import dump # noqa: F401
class GitRepo:
repo = None
aider_ignore_file = None
aider_ignore_spec = None
aider_ignore_ts = 0
def __init__(self, io, fnames, git_dname, aider_ignore_file=None, models=None):
self.io = io
if models:
self.models = models
else:
self.models = [
Model(
DEFAULT_WEAK_MODEL_NAME,
weak_model=False,
require_model_info=False,
)
]
if git_dname:
check_fnames = [git_dname]
elif fnames:
check_fnames = fnames
else:
check_fnames = ["."]
repo_paths = []
for fname in check_fnames:
fname = Path(fname)
fname = fname.resolve()
if not fname.exists() and fname.parent.exists():
fname = fname.parent
try:
repo_path = git.Repo(fname, search_parent_directories=True).working_dir
repo_path = utils.safe_abs_path(repo_path)
repo_paths.append(repo_path)
except git.exc.InvalidGitRepositoryError:
pass
except git.exc.NoSuchPathError:
pass
num_repos = len(set(repo_paths))
if num_repos == 0:
raise FileNotFoundError
if num_repos > 1:
self.io.tool_error("Files are in different git repos.")
raise FileNotFoundError
# https://github.com/gitpython-developers/GitPython/issues/427
self.repo = git.Repo(repo_paths.pop(), odbt=git.GitDB)
self.root = utils.safe_abs_path(self.repo.working_tree_dir)
if aider_ignore_file:
self.aider_ignore_file = Path(aider_ignore_file)
def commit(self, fnames=None, context=None, prefix=None, message=None):
if not fnames and not self.repo.is_dirty():
return
diffs = self.get_diffs(fnames)
if not diffs:
return
if message:
commit_message = message
else:
commit_message = self.get_commit_message(diffs, context)
if not commit_message:
commit_message = "(no commit message provided)"
if prefix:
commit_message = prefix + commit_message
full_commit_message = commit_message
if context:
full_commit_message += "\n\n# Aider chat conversation:\n\n" + context
cmd = ["-m", full_commit_message, "--no-verify"]
if fnames:
fnames = [str(self.abs_root_path(fn)) for fn in fnames]
for fname in fnames:
self.repo.git.add(fname)
cmd += ["--"] + fnames
else:
cmd += ["-a"]
self.repo.git.commit(cmd)
commit_hash = self.repo.head.commit.hexsha[:7]
self.io.tool_output(f"Commit {commit_hash} {commit_message}")
return commit_hash, commit_message
def get_rel_repo_dir(self):
try:
return os.path.relpath(self.repo.git_dir, os.getcwd())
except ValueError:
return self.repo.git_dir
def get_commit_message(self, diffs, context):
if len(diffs) >= 4 * 1024 * 4:
self.io.tool_error("Diff is too large to generate a commit message.")
return
diffs = "# Diffs:\n" + diffs
content = ""
if context:
content += context + "\n"
content += diffs
messages = [
dict(role="system", content=prompts.commit_system),
dict(role="user", content=content),
]
for model in self.models:
commit_message = simple_send_with_retries(model.name, messages)
if commit_message:
break
if not commit_message:
self.io.tool_error("Failed to generate commit message!")
return
commit_message = commit_message.strip()
if commit_message and commit_message[0] == '"' and commit_message[-1] == '"':
commit_message = commit_message[1:-1].strip()
return commit_message
def get_diffs(self, fnames=None):
# We always want diffs of index and working dir
current_branch_has_commits = False
try:
active_branch = self.repo.active_branch
try:
commits = self.repo.iter_commits(active_branch)
current_branch_has_commits = any(commits)
except git.exc.GitCommandError:
pass
except TypeError:
pass
if not fnames:
fnames = []
diffs = ""
for fname in fnames:
if not self.path_in_repo(fname):
diffs += f"Added {fname}\n"
if current_branch_has_commits:
args = ["HEAD", "--"] + list(fnames)
diffs += self.repo.git.diff(*args)
return diffs
wd_args = ["--"] + list(fnames)
index_args = ["--cached"] + wd_args
diffs += self.repo.git.diff(*index_args)
diffs += self.repo.git.diff(*wd_args)
return diffs
def diff_commits(self, pretty, from_commit, to_commit):
args = []
if pretty:
args += ["--color"]
args += [from_commit, to_commit]
diffs = self.repo.git.diff(*args)
return diffs
def get_tracked_files(self):
if not self.repo:
return []
try:
commit = self.repo.head.commit
except ValueError:
commit = None
files = []
if commit:
for blob in commit.tree.traverse():
if blob.type == "blob": # blob is a file
files.append(blob.path)
# Add staged files
index = self.repo.index
staged_files = [path for path, _ in index.entries.keys()]
files.extend(staged_files)
# convert to appropriate os.sep, since git always normalizes to /
res = set(self.normalize_path(path) for path in files)
res = [fname for fname in res if not self.ignored_file(fname)]
return res
def normalize_path(self, path):
return str(Path(PurePosixPath((Path(self.root) / path).relative_to(self.root))))
def ignored_file(self, fname):
if not self.aider_ignore_file or not self.aider_ignore_file.is_file():
return
try:
fname = self.normalize_path(fname)
except ValueError:
return
mtime = self.aider_ignore_file.stat().st_mtime
if mtime != self.aider_ignore_ts:
self.aider_ignore_ts = mtime
lines = self.aider_ignore_file.read_text().splitlines()
self.aider_ignore_spec = pathspec.PathSpec.from_lines(
pathspec.patterns.GitWildMatchPattern,
lines,
)
return self.aider_ignore_spec.match_file(fname)
def path_in_repo(self, path):
if not self.repo:
return
tracked_files = set(self.get_tracked_files())
return self.normalize_path(path) in tracked_files
def abs_root_path(self, path):
res = Path(self.root) / path
return utils.safe_abs_path(res)
def is_dirty(self, path=None):
if path and not self.path_in_repo(path):
return True
return self.repo.is_dirty(path=path)