SCM - cleanup SourceControlHistoryProvider api (#227376)

* Remove provideHistoryItemSummary

* Remove resolveHistoryItemGroupCommonAncestor

* Remove provideHistoryItems

* Rename methods and remove unused code

* Remove duplicated code
This commit is contained in:
Ladislau Szomoru
2024-09-02 15:52:05 +02:00
committed by GitHub
parent 322f345106
commit a3aedeae3e
10 changed files with 30 additions and 202 deletions

View File

@@ -224,12 +224,12 @@ class GitIncomingChangesFileDecorationProvider implements FileDecorationProvider
return [];
}
const ancestor = await historyProvider.resolveHistoryItemGroupCommonAncestor(currentHistoryItemGroup.id, currentHistoryItemGroup.remote.id);
const ancestor = await historyProvider.resolveHistoryItemGroupCommonAncestor([currentHistoryItemGroup.id, currentHistoryItemGroup.remote.id]);
if (!ancestor) {
return [];
}
const changes = await this.repository.diffBetween(ancestor.id, currentHistoryItemGroup.remote.id);
const changes = await this.repository.diffBetween(ancestor, currentHistoryItemGroup.remote.id);
return changes;
} catch (err) {
return [];

View File

@@ -2647,7 +2647,7 @@ export class Repository {
async getDefaultBranch(): Promise<Branch> {
const result = await this.exec(['symbolic-ref', '--short', 'refs/remotes/origin/HEAD']);
if (!result.stdout) {
if (!result.stdout || result.stderr) {
throw new Error('No default branch');
}
@@ -2714,24 +2714,6 @@ export class Repository {
return commits[0];
}
async getCommitFiles(ref: string): Promise<string[]> {
const result = await this.exec(['diff-tree', '--no-commit-id', '--name-only', '-r', ref]);
return result.stdout.split('\n').filter(l => !!l);
}
async getCommitCount(range: string): Promise<{ ahead: number; behind: number }> {
const args = ['rev-list', '--count', '--left-right', range];
if (isWindows) {
args.splice(0, 0, '-c', 'core.longpaths=true');
}
const result = await this.exec(args);
const [ahead, behind] = result.stdout.trim().split('\t');
return { ahead: Number(ahead) || 0, behind: Number(behind) || 0 };
}
async revParse(ref: string): Promise<string | undefined> {
try {
const result = await fs.readFile(path.join(this.dotGit.path, ref), 'utf8');

View File

@@ -8,7 +8,7 @@ import { Disposable, Event, EventEmitter, FileDecoration, FileDecorationProvider
import { Repository, Resource } from './repository';
import { IDisposable, dispose } from './util';
import { toGitUri } from './uri';
import { Branch, LogOptions, RefType, UpstreamRef } from './api/git';
import { Branch, LogOptions, RefType } from './api/git';
import { emojify, ensureEmojis } from './emoji';
import { Commit } from './git';
@@ -97,42 +97,7 @@ export class GitHistoryProvider implements SourceControlHistoryProvider, FileDec
this.logger.trace(`[GitHistoryProvider][onDidRunGitStatus] currentHistoryItemGroup: ${JSON.stringify(this.currentHistoryItemGroup)}`);
}
async provideHistoryItems(historyItemGroupId: string, options: SourceControlHistoryOptions): Promise<SourceControlHistoryItem[]> {
//TODO@lszomoru - support limit and cursor
if (typeof options.limit === 'number') {
throw new Error('Unsupported options.');
}
if (typeof options.limit?.id !== 'string') {
throw new Error('Unsupported options.');
}
const refParentId = options.limit.id;
const refId = await this.repository.revParse(historyItemGroupId) ?? '';
const historyItems: SourceControlHistoryItem[] = [];
const commits = await this.repository.log({ range: `${refParentId}..${refId}`, shortStats: true, sortByAuthorDate: true });
await ensureEmojis();
historyItems.push(...commits.map(commit => {
const newLineIndex = commit.message.indexOf('\n');
const subject = newLineIndex !== -1 ? commit.message.substring(0, newLineIndex) : commit.message;
return {
id: commit.hash,
parentIds: commit.parents,
message: emojify(subject),
author: commit.authorName,
icon: new ThemeIcon('git-commit'),
timestamp: commit.authorDate?.getTime(),
statistics: commit.shortStat ?? { files: 0, insertions: 0, deletions: 0 },
};
}));
return historyItems;
}
async provideHistoryItems2(options: SourceControlHistoryOptions): Promise<SourceControlHistoryItem[]> {
async provideHistoryItems(options: SourceControlHistoryOptions): Promise<SourceControlHistoryItem[]> {
if (!this.currentHistoryItemGroup || !options.historyItemGroupIds) {
return [];
}
@@ -180,18 +145,11 @@ export class GitHistoryProvider implements SourceControlHistoryProvider, FileDec
};
});
} catch (err) {
this.logger.error(`[GitHistoryProvider][provideHistoryItems2] Failed to get history items with options '${JSON.stringify(options)}': ${err}`);
this.logger.error(`[GitHistoryProvider][provideHistoryItems] Failed to get history items with options '${JSON.stringify(options)}': ${err}`);
return [];
}
}
async provideHistoryItemSummary(historyItemId: string, historyItemParentId: string | undefined): Promise<SourceControlHistoryItem> {
historyItemParentId = historyItemParentId ?? await this.repository.getEmptyTree();
const allChanges = await this.repository.diffBetweenShortStat(historyItemParentId, historyItemId);
return { id: historyItemId, parentIds: [historyItemParentId], message: '', statistics: allChanges };
}
async provideHistoryItemChanges(historyItemId: string, historyItemParentId: string | undefined): Promise<SourceControlHistoryItemChange[]> {
historyItemParentId = historyItemParentId ?? await this.repository.getEmptyTree();
@@ -226,35 +184,7 @@ export class GitHistoryProvider implements SourceControlHistoryProvider, FileDec
return historyItemChanges;
}
async resolveHistoryItemGroupCommonAncestor(historyItemId1: string, historyItemId2: string | undefined): Promise<{ id: string; ahead: number; behind: number } | undefined> {
if (!historyItemId2) {
const upstreamRef = await this.resolveHistoryItemGroupMergeBase(historyItemId1);
if (!upstreamRef) {
this.logger.info(`[GitHistoryProvider][resolveHistoryItemGroupCommonAncestor] Failed to resolve history item group base for '${historyItemId1}'`);
return undefined;
}
historyItemId2 = `refs/remotes/${upstreamRef.remote}/${upstreamRef.name}`;
}
const ancestor = await this.repository.getMergeBase(historyItemId1, historyItemId2);
if (!ancestor) {
this.logger.info(`[GitHistoryProvider][resolveHistoryItemGroupCommonAncestor] Failed to resolve common ancestor for '${historyItemId1}' and '${historyItemId2}'`);
return undefined;
}
try {
const commitCount = await this.repository.getCommitCount(`${historyItemId1}...${historyItemId2}`);
this.logger.trace(`[GitHistoryProvider][resolveHistoryItemGroupCommonAncestor] Resolved common ancestor for '${historyItemId1}' and '${historyItemId2}': ${JSON.stringify({ id: ancestor, ahead: commitCount.ahead, behind: commitCount.behind })}`);
return { id: ancestor, ahead: commitCount.ahead, behind: commitCount.behind };
} catch (err) {
this.logger.error(`[GitHistoryProvider][resolveHistoryItemGroupCommonAncestor] Failed to get ahead/behind for '${historyItemId1}...${historyItemId2}': ${err.message}`);
}
return undefined;
}
async resolveHistoryItemGroupCommonAncestor2(historyItemGroupIds: string[]): Promise<string | undefined> {
async resolveHistoryItemGroupCommonAncestor(historyItemGroupIds: string[]): Promise<string | undefined> {
try {
if (historyItemGroupIds.length === 0) {
// TODO@lszomoru - log
@@ -283,7 +213,7 @@ export class GitHistoryProvider implements SourceControlHistoryProvider, FileDec
}
}
catch (err) {
this.logger.error(`[GitHistoryProvider][resolveHistoryItemGroupCommonAncestor2] Failed to resolve common ancestor for ${historyItemGroupIds.join(',')}: ${err}`);
this.logger.error(`[GitHistoryProvider][resolveHistoryItemGroupCommonAncestor] Failed to resolve common ancestor for ${historyItemGroupIds.join(',')}: ${err}`);
}
return undefined;
@@ -311,34 +241,6 @@ export class GitHistoryProvider implements SourceControlHistoryProvider, FileDec
return labels;
}
private async resolveHistoryItemGroupMergeBase(historyItemId: string): Promise<UpstreamRef | undefined> {
try {
// Upstream
const branch = await this.repository.getBranch(historyItemId);
if (branch.upstream) {
return branch.upstream;
}
// Base (config -> reflog -> default)
const remoteBranch = await this.repository.getBranchBase(historyItemId);
if (!remoteBranch?.remote || !remoteBranch?.name || !remoteBranch?.commit || remoteBranch?.type !== RefType.RemoteHead) {
this.logger.info(`[GitHistoryProvider][resolveHistoryItemGroupUpstreamOrBase] Failed to resolve history item group base for '${historyItemId}'`);
return undefined;
}
return {
name: remoteBranch.name,
remote: remoteBranch.remote,
commit: remoteBranch.commit
};
}
catch (err) {
this.logger.error(`[GitHistoryProvider][resolveHistoryItemGroupUpstreamOrBase] Failed to get branch base for '${historyItemId}': ${err.message}`);
}
return undefined;
}
private async resolveHEADMergeBase(): Promise<Branch | undefined> {
if (this.repository.HEAD?.type !== RefType.Head || !this.repository.HEAD?.name) {
return undefined;

View File

@@ -1508,16 +1508,13 @@ export class Repository implements Disposable {
private async getDefaultBranch(): Promise<Branch | undefined> {
try {
const defaultBranchResult = await this.repository.exec(['symbolic-ref', '--short', 'refs/remotes/origin/HEAD']);
if (defaultBranchResult.stdout.trim() === '' || defaultBranchResult.stderr) {
return undefined;
}
return this.getBranch(defaultBranchResult.stdout.trim());
const defaultBranch = await this.repository.getDefaultBranch();
return defaultBranch;
}
catch (err) {
this.logger.warn(`[Repository][getDefaultBranch] Failed to get default branch details: ${err.message}.`);
return undefined;
}
catch (err) { }
return undefined;
}
private async getUpstreamBranch(branch: Branch): Promise<Branch | undefined> {
@@ -1618,14 +1615,6 @@ export class Repository implements Disposable {
return this._EMPTY_TREE;
}
async getCommitCount(range: string): Promise<{ ahead: number; behind: number }> {
return await this.run(Operation.RevList, () => this.repository.getCommitCount(range));
}
async revParse(ref: string): Promise<string | undefined> {
return await this.run(Operation.RevParse, () => this.repository.revParse(ref));
}
async reset(treeish: string, hard?: boolean): Promise<void> {
await this.run(Operation.Reset, () => this.repository.reset(treeish, hard));
}