Skip to content

Commit a0f5309

Browse files
committed
Renames generate rebase prompt templates and removes unused code
1 parent d548f26 commit a0f5309

File tree

6 files changed

+22
-245
lines changed

6 files changed

+22
-245
lines changed

src/commands/generateRebase.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ export async function generateRebase(
166166
options?: { cancellation?: CancellationToken; progress?: ProgressOptions },
167167
): Promise<void> {
168168
const repo = svc.getRepository()!;
169-
const result = await container.ai.generateRebaseV2(repo, base.ref, head.ref, source, options);
169+
const result = await container.ai.generateRebase(repo, base.ref, head.ref, source, options);
170170
if (result == null) return;
171171

172172
try {

src/features.ts

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -86,12 +86,7 @@ export type ProAIFeatures =
8686
| 'generate-stashMessage';
8787

8888
export type AdvancedFeatures = AdvancedAIFeatures;
89-
export type AdvancedAIFeatures =
90-
| 'generate-changelog'
91-
| 'generate-create-pullRequest'
92-
| 'generate-rebase'
93-
| 'generate-rebase-multi-step1'
94-
| 'generate-rebase-multi-step2';
89+
export type AdvancedAIFeatures = 'generate-changelog' | 'generate-create-pullRequest' | 'generate-rebase';
9590

9691
export type AIFeatures = 'generate-commitMessage' | ProAIFeatures | AdvancedAIFeatures;
9792

src/plus/ai/aiProviderService.ts

Lines changed: 3 additions & 148 deletions
Original file line numberDiff line numberDiff line change
@@ -852,133 +852,7 @@ export class AIProviderService implements Disposable {
852852
return result != null ? { ...result } : undefined;
853853
}
854854

855-
// Step 1: Get a patch containing the combined diff of all the changes within the branch input
856-
// Step 2: Prompt the AI agent to output an array with the reorganized commits and their commit messages.
857-
// Accept as context:
858-
// 1. The combined diff
859-
// 2. Optional list of original commits and messages
860-
// Take as output:
861-
// An array of commit objects with the properties:
862-
// 'message': The commit message as a string
863-
// 'explanation': A more detailed explanation of the changes in the commit as a string
864-
// 'changes': The changes of the commit as a formatted diff
865-
// Step 3: Create a new branch at the same branching point as the input branch with name <originalbranch>-recomposed
866-
// Step 4: Iteratively apply the diffs from the array as commits using the message and changes properties of each object
867-
// Step 5: ???
868-
869-
async generateRebaseV1(
870-
repo: Repository,
871-
baseRef: string,
872-
headRef: string,
873-
source: Source,
874-
options?: {
875-
cancellation?: CancellationToken;
876-
context?: string;
877-
generating?: Deferred<AIModel>;
878-
progress?: ProgressOptions;
879-
},
880-
): Promise<AIRebaseResult | undefined> {
881-
const result: Mutable<AIRebaseResult> = {
882-
diff: undefined!,
883-
explanation: undefined!,
884-
hunkMap: [],
885-
commits: [],
886-
} as unknown as AIRebaseResult;
887-
888-
const rq = await this.sendRequest(
889-
'generate-rebase',
890-
async (model, reporting, cancellation, maxInputTokens, retries) => {
891-
const [diffResult, logResult] = await Promise.allSettled([
892-
repo.git.diff.getDiff?.(headRef, baseRef, { notation: '...' }),
893-
repo.git.commits.getLog(`${baseRef}..${headRef}`),
894-
]);
895-
896-
const diff = getSettledValue(diffResult);
897-
const log = getSettledValue(logResult);
898-
899-
if (!diff?.contents || !log?.commits?.size) {
900-
throw new AINoRequestDataError('No changes found to generate a rebase from.');
901-
}
902-
if (cancellation.isCancellationRequested) throw new CancellationError();
903-
904-
result.diff = diff.contents;
905-
906-
const hunkMap: { index: number; hunkHeader: string }[] = [];
907-
let counter = 0;
908-
//const filesDiffs = await repo.git.diff().getDiffFiles!(diff.contents)!;
909-
//for (const f of filesDiffs!.files)
910-
//for (const hunk of parsedDiff.hunks) {
911-
// hunkMap.push({ index: ++counter, hunkHeader: hunk.contents.split('\n', 1)[0] });
912-
//}
913-
914-
// let hunksByNumber= '';
915-
916-
for (const hunkHeader of diff.contents.matchAll(/@@ -\d+,\d+ \+\d+,\d+ @@(.*)$/gm)) {
917-
hunkMap.push({ index: ++counter, hunkHeader: hunkHeader[0] });
918-
}
919-
920-
result.hunkMap = hunkMap;
921-
// const hunkNumber = `hunk-${counter++}`;
922-
// hunksByNumber += `${hunkNumber}: ${hunk[0]}\n`;
923-
// }
924-
925-
// const commits: { diff: string; message: string }[] = [];
926-
// for (const commit of [...log.commits.values()].sort((a, b) => a.date.getTime() - b.date.getTime())) {
927-
// const diff = await repo.git.diff().getDiff?.(commit.ref);
928-
// commits.push({ message: commit.message ?? commit.summary, diff: diff?.contents ?? '' });
929-
930-
// if (cancellation.isCancellationRequested) throw new CancellationError();
931-
// }
932-
933-
const { prompt } = await this.getPrompt(
934-
'generate-rebase',
935-
model,
936-
{
937-
diff: diff.contents,
938-
// commits: JSON.stringify(commits),
939-
data: JSON.stringify(hunkMap),
940-
context: options?.context,
941-
// instructions: configuration.get('ai.generateRebase.customInstructions'),
942-
},
943-
maxInputTokens,
944-
retries,
945-
reporting,
946-
);
947-
if (cancellation.isCancellationRequested) throw new CancellationError();
948-
949-
const messages: AIChatMessage[] = [{ role: 'user', content: prompt }];
950-
return messages;
951-
},
952-
m => `Generating rebase with ${m.name}...`,
953-
source,
954-
m => ({
955-
key: 'ai/generate',
956-
data: {
957-
type: 'rebase',
958-
'model.id': m.id,
959-
'model.provider.id': m.provider.id,
960-
'model.provider.name': m.provider.name,
961-
'retry.count': 0,
962-
},
963-
}),
964-
options,
965-
);
966-
967-
// if it is wrapped in markdown, we need to strip it
968-
const content = rq!.content.replace(/^\s*```json\s*/, '').replace(/\s*```$/, '');
969-
970-
try {
971-
// Parse the JSON content from the result
972-
result.commits = JSON.parse(content) as AIRebaseResult['commits'];
973-
} catch {
974-
debugger;
975-
throw new Error('Unable to parse rebase result');
976-
}
977-
978-
return result;
979-
}
980-
981-
async generateRebaseV2(
855+
async generateRebase(
982856
repo: Repository,
983857
baseRef: string,
984858
headRef: string,
@@ -1013,7 +887,7 @@ export class AIProviderService implements Disposable {
1013887
result.diff = diff.contents;
1014888

1015889
const { prompt } = await this.getPrompt(
1016-
'generate-rebase-multi-step1',
890+
'generate-rebase-explanation',
1017891
model,
1018892
{
1019893
diff: diff.contents,
@@ -1055,43 +929,24 @@ export class AIProviderService implements Disposable {
1055929
const req2 = await this.sendRequest(
1056930
'generate-rebase',
1057931
async (model, reporting, cancellation, maxInputTokens, retries) => {
1058-
// const [diffResult, logResult] = await Promise.allSettled([
1059-
// repo.git.diff().getDiff?.(headRef, baseRef, { notation: '...' }),
1060-
// repo.git.commits().getLog(`${baseRef}..${headRef}`),
1061-
// ]);
1062-
1063-
// const diff = getSettledValue(diffResult);
1064-
// const log = getSettledValue(logResult);
1065-
1066932
const diff = await lazyDiff.value;
1067933
if (!diff?.contents) {
1068934
throw new AINoRequestDataError('No changes found to generate a rebase from.');
1069935
}
1070936
if (cancellation.isCancellationRequested) throw new CancellationError();
1071937

1072-
// result.diff = diff.contents;
1073-
1074938
const hunkMap: { index: number; hunkHeader: string }[] = [];
1075939
let counter = 0;
1076-
// const filesDiffs = parseGitDiff(diff.contents, true);
1077-
// for (const f of filesDiffs.files) {
1078-
// for (const hunk of f.hunks) {
1079-
// hunkMap.push({ index: ++counter, hunkHeader: hunk.contents.split('\n', 1)[0] });
1080-
// }
1081-
// }
1082-
1083940
for (const hunkHeader of diff.contents.matchAll(/@@ -\d+,\d+ \+\d+,\d+ @@(.*)$/gm)) {
1084941
hunkMap.push({ index: ++counter, hunkHeader: hunkHeader[0] });
1085942
}
1086943

1087944
result.hunkMap = hunkMap;
1088945

1089946
const { prompt } = await this.getPrompt(
1090-
'generate-rebase-multi-step2',
947+
'generate-rebase-commits',
1091948
model,
1092949
{
1093-
// diff: diff.contents,
1094-
// commits: JSON.stringify(commits),
1095950
data: JSON.stringify(hunkMap),
1096951
context: options?.context,
1097952
// instructions: configuration.get('ai.generateRebase.customInstructions'),

src/plus/ai/models/promptTemplates.ts

Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -28,22 +28,14 @@ interface CreatePullRequestPromptTemplateContext {
2828
instructions?: string;
2929
}
3030

31-
interface RebasePromptTemplateContext {
31+
interface RebaseExplanationPromptTemplateContext {
3232
diff: string;
33-
data?: string;
3433
commits?: string;
3534
context?: string;
3635
instructions?: string;
3736
}
3837

39-
interface RebaseMultiStep1PromptTemplateContext {
40-
diff: string;
41-
commits?: string;
42-
context?: string;
43-
instructions?: string;
44-
}
45-
46-
interface RebaseMultiStep2PromptTemplateContext {
38+
interface RebaseCommitsPromptTemplateContext {
4739
data: string;
4840
context?: string;
4941
instructions?: string;
@@ -66,9 +58,7 @@ export type PromptTemplateType =
6658
| 'generate-stashMessage'
6759
| 'generate-changelog'
6860
| `generate-create-${'cloudPatch' | 'codeSuggestion' | 'pullRequest'}`
69-
| 'generate-rebase'
70-
| 'generate-rebase-multi-step1'
71-
| 'generate-rebase-multi-step2'
61+
| `generate-rebase-${'explanation' | 'commits'}`
7262
| 'explain-changes';
7363

7464
type PromptTemplateVersions = '' | '_v2';
@@ -86,12 +76,10 @@ export type PromptTemplateContext<T extends PromptTemplateType> = T extends 'gen
8676
? CreatePullRequestPromptTemplateContext
8777
: T extends 'generate-changelog'
8878
? ChangelogPromptTemplateContext
89-
: T extends 'generate-rebase'
90-
? RebasePromptTemplateContext
91-
: T extends 'generate-rebase-multi-step1'
92-
? RebaseMultiStep1PromptTemplateContext
93-
: T extends 'generate-rebase-multi-step2'
94-
? RebaseMultiStep2PromptTemplateContext
79+
: T extends 'generate-rebase-explanation'
80+
? RebaseExplanationPromptTemplateContext
81+
: T extends 'generate-rebase-commits'
82+
? RebaseCommitsPromptTemplateContext
9583
: T extends 'explain-changes'
9684
? ExplainChangesPromptTemplateContext
9785
: never;

src/plus/ai/prompts.ts

Lines changed: 4 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -339,66 +339,8 @@ Example output structure:
339339
Based on the provided commit messages and associated issues, create a set of markdown changelog entries following the instructions above. Do not include any explanatory text or metadata`,
340340
};
341341

342-
export const generateRebaseUserPromptV3: PromptTemplate<'generate-rebase'> = {
343-
id: 'generate-rebase',
344-
variables: ['diff', 'commits', 'data', 'context', 'instructions'],
345-
template: `You are an advanced AI programming assistant tasked with organizing code changes into commits. Your goal is to create a new set of commits that are related, grouped logically, atomic, and easy to review. You will be working with code changes provided in a unified diff format.
346-
347-
First, examine the following unified Git diff of code changes:
348-
349-
<unified_diff>
350-
\${diff}
351-
</unified_diff>
352-
353-
Next, examine the following JSON array which represents a mapping of index to hunk headers in the unified_diff to be used later when mapping hunks to commits:
354-
<hunk_map>
355-
\${data}
356-
</hunk_map>
357-
358-
359-
Your task is to group the hunks in unified_diff into a set of commits, ordered into a commit history as an array. Follow these guidelines:
360-
361-
1. Only organize the hunks themselves, not individual lines within hunks.
362-
2. Group hunks into logical units that make sense together and can be applied atomically.
363-
3. Ensure each commit is self-contained and only depends on commits that come before it in the new history.
364-
4. Write meaningful commit messages that accurately describe the changes in each commit.
365-
5. Provide a detailed explanation of the changes in each commit.
366-
6. Make sure the new commit history is easy to review and understand.
367-
368-
Output your new commit history as a JSON array. Each commit in the array should be an object representing a grouping of hunks forming that commit, with the following properties:
369-
- "message": A string containing the commit message.
370-
- "explanation": A string with a detailed explanation of the changes in the commit. Write the explanation as if you were explaining the changes to a reviewer who is familiar with the codebase but not the specific changes. Walk through the changes and make references to specific changes where needed, explaining how they achieve the objective of the commit.
371-
- "hunks": An array of objects, each representing a hunk in the commit. Each hunk object should have:
372-
- "hunk": The hunk index (number) from the hunk_map, matching the equivalent hunk you chose from the unified_diff.
373-
374-
Once you've completed your analysis, generate the JSON output following the specified format.
375-
376-
Here's an example of the expected JSON structure (note that this is just a structural example and does not reflect the actual content you should produce):
377-
378-
[
379-
{
380-
"message": "Example commit message",
381-
"explanation": "Detailed explanation of the changes in this commit",
382-
"hunks": [
383-
{
384-
"hunk": 2
385-
},
386-
{
387-
"hunk": 7
388-
}
389-
]
390-
}
391-
]
392-
393-
Remember to base your organization of commits solely on the provided unified_diff and hunk_map. Do not introduce any new changes or modify the content of the hunks. Your task is to organize the existing hunks in a logical and reviewable manner.
394-
395-
\${instructions}
396-
397-
Now, proceed with your analysis and organization of the commits. Output only the JSON array containing the commits, and nothing else.`,
398-
};
399-
400-
export const generateRebaseMultiStep1UserPrompt: PromptTemplate<'generate-rebase-multi-step1'> = {
401-
id: 'generate-rebase-multi-step1',
342+
export const generateRebaseExplanation: PromptTemplate<'generate-rebase-explanation'> = {
343+
id: 'generate-rebase-explanation',
402344
variables: ['diff', 'context', 'instructions'],
403345
template: `You are an advanced AI programming assistant tasked with explaining code changes and how they would be best organized into commits. Your goal is to examine a unified diff of the code changes and explain the changes and how they should be grouped into a set of commits.
404346
@@ -424,8 +366,8 @@ Remember to base your organization of commits solely on the provided unified_dif
424366
Now, proceed with your analysis and explanation. Output only the explanation you have generated, and nothing else.`,
425367
};
426368

427-
export const generateRebaseMultiStep2UserPrompt: PromptTemplate<'generate-rebase-multi-step2'> = {
428-
id: 'generate-rebase-multi-step2',
369+
export const generateRebaseCommits: PromptTemplate<'generate-rebase-commits'> = {
370+
id: 'generate-rebase-commits',
429371
variables: ['data', 'context', 'instructions'],
430372
template: `Using the plan you provided in the previous step, your goal now is use it to create that new set of commits, ensuring that ALL the changes in the unified diff are included in the new set of commits.
431373

src/plus/ai/utils/-webview/prompt.utils.ts

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,8 @@ import {
1313
generateCreateCloudPatch,
1414
generateCreateCodeSuggest,
1515
generateCreatePullRequest,
16-
generateRebaseMultiStep1UserPrompt,
17-
generateRebaseMultiStep2UserPrompt,
18-
generateRebaseUserPromptV3,
16+
generateRebaseCommits,
17+
generateRebaseExplanation,
1918
generateStashMessage,
2019
} from '../../prompts';
2120
import { estimatedCharactersPerToken, showLargePromptWarning, showPromptTruncationWarning } from './ai.utils';
@@ -37,12 +36,10 @@ export function getLocalPromptTemplate<T extends PromptTemplateType>(
3736
return generateCreateCodeSuggest as PromptTemplate<T>;
3837
case 'generate-create-pullRequest':
3938
return generateCreatePullRequest as PromptTemplate<T>;
40-
case 'generate-rebase':
41-
return generateRebaseUserPromptV3 as PromptTemplate<T>;
42-
case 'generate-rebase-multi-step1':
43-
return generateRebaseMultiStep1UserPrompt as PromptTemplate<T>;
44-
case 'generate-rebase-multi-step2':
45-
return generateRebaseMultiStep2UserPrompt as PromptTemplate<T>;
39+
case 'generate-rebase-explanation':
40+
return generateRebaseExplanation as PromptTemplate<T>;
41+
case 'generate-rebase-commits':
42+
return generateRebaseCommits as PromptTemplate<T>;
4643
case 'explain-changes':
4744
return explainChanges as PromptTemplate<T>;
4845
default:

0 commit comments

Comments
 (0)