-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathauto_commit.rs
More file actions
304 lines (277 loc) · 9.96 KB
/
auto_commit.rs
File metadata and controls
304 lines (277 loc) · 9.96 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
use std::path::Path;
use bstr::BString;
use but_core::sync::RepoExclusiveGuard;
use but_ctx::ProjectHandleOrLegacyProjectId;
use but_hunk_assignment::{CommitMap, convert_assignments_to_diff_specs};
use but_workspace::commit_engine;
use serde::Serialize;
type AutoCommitEmitter = dyn Fn(&str, serde_json::Value) + Send + Sync + 'static;
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "export-ts", derive(ts_rs::TS))]
#[serde(tag = "type", rename_all = "camelCase")]
#[cfg_attr(
feature = "export-ts",
ts(export, export_to = "./action/autoCommit.ts")
)]
enum AutoCommitEvent {
/// Emitted when the auto-commit process has started.
///
/// `steps_length`: The total number of steps in the auto-commit process.
Started { steps_length: usize },
/// Emitted when a commit message is being generated.
///
/// `parent_commit_id`: The ID of the parent commit for which the message is being generated.
/// `token`: A token representing the progress of the commit message generation.
CommitGeneration {
#[cfg_attr(feature = "export-ts", ts(type = "string"))]
#[serde(with = "but_serde::object_id")]
parent_commit_id: gix::ObjectId,
token: String,
},
/// Emitted when a commit has been successfully created.
///
/// `commit_id`: The ID of the newly created commit.
CommitSuccess {
#[cfg_attr(feature = "export-ts", ts(type = "string"))]
#[serde(with = "but_serde::object_id")]
commit_id: gix::ObjectId,
},
/// Emitted when an error occurs during the auto-commit process.
///
/// `error_message`: A message describing the error.
CommitError { error_message: String },
/// Emitted when the auto-commit process has completed.
Completed,
}
impl AutoCommitEvent {
fn event_name(&self, project_id: &ProjectHandleOrLegacyProjectId) -> String {
format!("project://{project_id}/auto-commit")
}
fn emit_payload(&self) -> serde_json::Value {
serde_json::to_value(self).unwrap_or_else(
|e| serde_json::json!({"error": format!("Failed to serialize event payload: {}", e)}),
)
}
}
#[expect(clippy::too_many_arguments)]
pub(crate) fn auto_commit(
project_id: ProjectHandleOrLegacyProjectId,
repo: &gix::Repository,
project_data_dir: &Path,
context_lines: u32,
llm: Option<&but_llm::LLMProvider>,
emitter: impl Fn(&str, serde_json::Value) + Send + Sync + 'static,
absorption_plan: Vec<but_hunk_assignment::CommitAbsorption>,
guard: &mut RepoExclusiveGuard,
) -> anyhow::Result<usize> {
let commit_map = CommitMap::default();
let emitter: std::sync::Arc<AutoCommitEmitter> = std::sync::Arc::new(emitter);
// Emit the started event
let event = AutoCommitEvent::Started {
steps_length: absorption_plan.len(),
};
let event_name = event.event_name(&project_id);
emitter(&event_name, event.emit_payload());
match apply_commit_changes(
Some(project_id.clone()),
repo,
project_data_dir,
context_lines,
llm,
absorption_plan,
guard,
commit_map,
Some(emitter.clone()),
) {
Err(e) => {
tracing::error!("Auto-commit failed: {}", e);
let event = AutoCommitEvent::CommitError {
error_message: e.to_string(),
};
let event_name = event.event_name(&project_id);
let emitter = emitter.clone();
emitter(&event_name, event.emit_payload());
Err(e)
}
Ok(number_of_rejections) => {
let event = AutoCommitEvent::Completed;
let event_name = event.event_name(&project_id);
let emitter = emitter.clone();
emitter(&event_name, event.emit_payload());
Ok(number_of_rejections)
}
}
}
pub(crate) fn auto_commit_simple(
repo: &gix::Repository,
project_data_dir: &Path,
context_lines: u32,
llm: Option<&but_llm::LLMProvider>,
absorption_plan: Vec<but_hunk_assignment::CommitAbsorption>,
guard: &mut RepoExclusiveGuard,
) -> anyhow::Result<usize> {
let commit_map = CommitMap::default();
apply_commit_changes(
None,
repo,
project_data_dir,
context_lines,
llm,
absorption_plan,
guard,
commit_map,
None,
)
}
#[expect(clippy::too_many_arguments)]
fn apply_commit_changes(
project_id: Option<ProjectHandleOrLegacyProjectId>,
repo: &gix::Repository,
project_data_dir: &Path,
context_lines: u32,
llm: Option<&but_llm::LLMProvider>,
absorption_plan: Vec<but_hunk_assignment::CommitAbsorption>,
guard: &mut RepoExclusiveGuard,
mut commit_map: CommitMap,
emitter: Option<std::sync::Arc<AutoCommitEmitter>>,
) -> anyhow::Result<usize> {
let mut total_rejected = 0;
for absorption in absorption_plan {
let diff_specs = convert_assignments_to_diff_specs(
&absorption
.files
.iter()
.map(|f| f.assignment.clone())
.collect::<Vec<_>>(),
)?;
let diff_infos = absorption_files_to_diff_infos(&absorption.files);
let commit_id = commit_map.find_mapped_id(absorption.commit_id);
let stack_id = absorption.stack_id;
let commit_message = commit_message_generation(
project_id.as_ref(),
commit_id,
llm,
emitter.as_ref(),
&diff_infos,
)?;
let outcome =
but_workspace::legacy::commit_engine::create_commit_and_update_refs_with_project(
repo,
project_data_dir,
Some(stack_id),
commit_engine::Destination::NewCommit {
message: commit_message,
parent_commit_id: Some(commit_id),
stack_segment: None,
},
diff_specs,
context_lines,
guard.write_permission(),
)?;
if let Some(new_commit_id) = outcome.new_commit
&& let Some(project_id) = project_id.as_ref()
&& let Some(emitter) = &emitter
{
let event = AutoCommitEvent::CommitSuccess {
commit_id: new_commit_id,
};
let event_name = event.event_name(project_id);
emitter(&event_name, event.emit_payload());
}
if let Some(rebase_output) = &outcome.rebase_output {
for mapping in &rebase_output.commit_mapping {
commit_map.add_mapping(mapping.1, mapping.2);
}
}
total_rejected += outcome.rejected_specs.len();
}
Ok(total_rejected)
}
#[derive(Debug, Clone)]
struct DiffInfo {
/// The file path of the diff.
path: String,
/// The diff content.
diff: BString,
}
impl std::fmt::Display for DiffInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "file: {}\n{}", self.path, self.diff)
}
}
fn absorption_files_to_diff_infos(
absorption_files: &[but_hunk_assignment::FileAbsorption],
) -> Vec<DiffInfo> {
absorption_files
.iter()
.filter_map(|f| {
f.assignment.diff.as_ref().map(|diff| DiffInfo {
path: f.path.clone(),
diff: diff.clone(),
})
})
.collect()
}
/// Generate a commit message using the LLM provider, if available.
///
/// If no project and no emitter are provided, the function will not stream tokens.
fn commit_message_generation(
project_id: Option<&ProjectHandleOrLegacyProjectId>,
parent_commit_id: gix::ObjectId,
llm: Option<&but_llm::LLMProvider>,
emitter: Option<&std::sync::Arc<AutoCommitEmitter>>,
hunk_diffs: &[DiffInfo],
) -> anyhow::Result<String> {
if let Some(llm) = llm
&& let Some(model) = llm.model()
{
let system_message = "
<tone>
You are an expert git commit message generator.
Your task is to create clear, concise, and descriptive commit messages (title and body) based on the provided diffs.
The response is intended to be used directly as a git commit message.
</tone>
<instructions>
- Summarize the changes made in the diff.
- Use imperative mood (e.g., 'Fix bug', 'Add feature').
- Generate a title and a body if necessary.
- Keep the message title concise, ideally under 50 characters for the subject line.
- The body should provide additional context, but not be overly verbose.
- If multiple changes are present, provide a brief overview.
</instructions>
<format>
- Return only the commit message text without any additional formatting or explanations.
- Ensure the title and body are separated by a blank line.
</format>
";
let changes = hunk_diffs
.iter()
.map(|diff| diff.to_string())
.collect::<Vec<_>>();
let prompt = format!(
"Please generate a concise and descriptive git commit message for the following changes:\n\n{}",
changes.join("\n")
);
let commit_message = match (project_id, emitter) {
(Some(project_id), Some(emitter)) => {
llm.stream_response(system_message, vec![prompt.into()], &model, {
let emitter = std::sync::Arc::clone(emitter);
let project_id = project_id.clone();
move |token| {
let event = AutoCommitEvent::CommitGeneration {
parent_commit_id,
token: token.to_string(),
};
let event_name = event.event_name(&project_id);
emitter(&event_name, event.emit_payload());
}
})?
}
_ => llm.response(system_message, vec![prompt.into()], &model)?,
};
if let Some(message) = commit_message {
return Ok(message);
}
}
Ok("[AUTO-COMMIT] Generated commit message".to_string())
}