Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 33 additions & 55 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,10 @@ import { isSubmodule } from './common/gitUtils';
import Logger from './common/logger';
import * as PersistentState from './common/persistentState';
import { parseRepositoryRemotes } from './common/remote';
import { AUTO_REPO_DETECTION, AutoRepoDetectionVariants, BRANCH_PUBLISH, EXPERIMENTAL_CHAT, FILE_LIST_LAYOUT, GIT, IGNORE_SUBMODULES, OPEN_DIFF_ON_CLICK, PR_SETTINGS_NAMESPACE, SHOW_INLINE_OPEN_FILE_ACTION } from './common/settingKeys';
import { BRANCH_PUBLISH, EXPERIMENTAL_CHAT, FILE_LIST_LAYOUT, GIT, IGNORE_SUBMODULES, OPEN_DIFF_ON_CLICK, PR_SETTINGS_NAMESPACE, SHOW_INLINE_OPEN_FILE_ACTION } from './common/settingKeys';
import { initBasedOnSettingChange } from './common/settingsUtils';
import { TemporaryState } from './common/temporaryState';
import { Schemes } from './common/uri';
import { isDescendant } from './common/utils';
import { EXTENSION_ID, FOCUS_REVIEW_MODE } from './constants';
import { createExperimentationService, ExperimentationTelemetry } from './experimentationService';
import { CopilotRemoteAgentManager } from './github/copilotRemoteAgent';
Expand All @@ -31,6 +30,7 @@ import { IssueOverviewPanel } from './github/issueOverview';
import { OverviewRestorer } from './github/overviewRestorer';
import { PullRequestOverviewPanel } from './github/pullRequestOverview';
import { RepositoriesManager } from './github/repositoriesManager';
import { detectRepositories } from './github/repositoryDetection';
import { registerBuiltinGitProvider, registerLiveShareGitProvider } from './gitProviders/api';
import { GitHubContactServiceProvider } from './gitProviders/GitHubContactServiceProvider';
import { GitLensIntegration } from './integrations/gitlens/gitlensImpl';
Expand Down Expand Up @@ -198,61 +198,39 @@ async function init(
reviewsManager.reviewManagers.forEach(reviewManager => reviewManager.updateState(true));
});

git.onDidOpenRepository(repo => {
function addRepo() {
// Make sure we don't already have a folder manager for this repo.
const existing = reposManager.folderManagers.find(manager => manager.repository.rootUri.toString() === repo.rootUri.toString());
if (existing) {
Logger.appendLine(`Repo ${repo.rootUri} has already been setup.`, ACTIVATION);
return;
}

// Check if submodules should be ignored
const ignoreSubmodules = vscode.workspace.getConfiguration(PR_SETTINGS_NAMESPACE).get<boolean>(IGNORE_SUBMODULES, false);
if (ignoreSubmodules && isSubmodule(repo, git)) {
Logger.appendLine(`Repo ${repo.rootUri} is a submodule and will be ignored due to ${IGNORE_SUBMODULES} setting.`, ACTIVATION);
return;
}

const newFolderManager = new FolderRepositoryManager(reposManager.folderManagers.length, context, repo, telemetry, git, credentialStore, createPrHelper, themeWatcher);
reposManager.insertFolderManager(newFolderManager);
const newReviewManager = new ReviewManager(
reviewManagerIndex++,
context,
newFolderManager.repository,
newFolderManager,
telemetry,
changesTree,
tree,
showPRController,
activePrViewCoordinator,
createPrHelper,
git
);
reviewsManager.addReviewManager(newReviewManager);
const addRepository = (repo: Repository) => {
// Make sure we don't already have a folder manager for this repo.
const existing = reposManager.folderManagers.find(manager => manager.repository.rootUri.toString() === repo.rootUri.toString());
if (existing) {
Logger.appendLine(`Repo ${repo.rootUri} has already been setup.`, ACTIVATION);
return;
}

const detectionMode = vscode.workspace.getConfiguration(PR_SETTINGS_NAMESPACE).get<AutoRepoDetectionVariants>(AUTO_REPO_DETECTION, 'workspace');
const shouldFilterByWorkspace = detectionMode === 'workspace';

if (shouldFilterByWorkspace) {
Logger.debug(`Checking if repo ${repo.rootUri.fsPath} is in a workspace folder.`, ACTIVATION);
Logger.debug(`Workspace folders: ${workspaceFolders?.map(folder => folder.uri.fsPath).join(', ')}`, ACTIVATION);
if (workspaceFolders && !workspaceFolders.some(folder => isDescendant(folder.uri.fsPath, repo.rootUri.fsPath, true) || isDescendant(repo.rootUri.fsPath, folder.uri.fsPath, true))) {
Logger.appendLine(`Repo ${repo.rootUri} is not in a workspace folder, ignoring.`, ACTIVATION);
return;
}
} else {
Logger.debug(`Auto-detection is enabled for all Git repositories.`, ACTIVATION);
// Check if submodules should be ignored
const ignoreSubmodules = vscode.workspace.getConfiguration(PR_SETTINGS_NAMESPACE).get<boolean>(IGNORE_SUBMODULES, false);
if (ignoreSubmodules && isSubmodule(repo, git)) {
Logger.appendLine(`Repo ${repo.rootUri} is a submodule and will be ignored due to ${IGNORE_SUBMODULES} setting.`, ACTIVATION);
return;
}

addRepo();
const disposable = repo.state.onDidChange(() => {
Logger.appendLine(`Repo state for ${repo.rootUri} changed.`, ACTIVATION);
addRepo();
disposable.dispose();
});
});
const newFolderManager = new FolderRepositoryManager(reposManager.folderManagers.length, context, repo, telemetry, git, credentialStore, createPrHelper, themeWatcher);
reposManager.insertFolderManager(newFolderManager);
const newReviewManager = new ReviewManager(
reviewManagerIndex++,
context,
newFolderManager.repository,
newFolderManager,
telemetry,
changesTree,
tree,
showPRController,
activePrViewCoordinator,
createPrHelper,
git
);
reviewsManager.addReviewManager(newReviewManager);
};
context.subscriptions.push(detectRepositories(git, reposManager, addRepository));

git.onDidCloseRepository(repo => {
reposManager.removeRepo(repo);
Expand Down Expand Up @@ -297,11 +275,11 @@ async function init(
notificationsManager.refresh();
}));

const pullRequestContextProvider = new PullRequestContextProvider(prsTreeModel, reposManager, context);
const pullRequestContextProvider = new PullRequestContextProvider(prsTreeModel, reposManager, folderRepositoryManagerResolver, credentialStore, context);
context.subscriptions.push(pullRequestContextProvider);
context.subscriptions.push(vscode.chat.registerChatAttachContextProvider('githubpr', pullRequestContextProvider));
context.subscriptions.push(vscode.chat.registerChatTabContextProvider({ uri: { scheme: 'webview-panel', pattern: '**/webview-PullRequestOverview**' } }, 'githubpr', pullRequestContextProvider));
const issueContextProvider = new IssueContextProvider(issueStateManager, reposManager, context);
const issueContextProvider = new IssueContextProvider(issueStateManager, reposManager, folderRepositoryManagerResolver, credentialStore, context);
context.subscriptions.push(vscode.chat.registerChatAttachContextProvider('githubissue', issueContextProvider));
context.subscriptions.push(vscode.chat.registerChatTabContextProvider({ uri: { scheme: 'webview-panel', pattern: '**/webview-IssueOverview**' } }, 'githubissue', issueContextProvider));

Expand Down
60 changes: 60 additions & 0 deletions src/github/repositoryDetection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import * as vscode from 'vscode';
import { RepositoriesManager } from './repositoriesManager';
import { Repository } from '../api/api';
import { GitApiImpl } from '../api/api1';
import Logger from '../common/logger';
import { AUTO_REPO_DETECTION, AutoRepoDetectionVariants, PR_SETTINGS_NAMESPACE } from '../common/settingKeys';
import { isDescendant } from '../common/utils';

const ACTIVATION = 'Activation';

function isRepositoryInFolders(repo: Repository, folders: readonly vscode.WorkspaceFolder[]): boolean {
return folders.some(folder => isDescendant(folder.uri.fsPath, repo.rootUri.fsPath, true) || isDescendant(repo.rootUri.fsPath, folder.uri.fsPath, true));
}

/**
* Calls `addRepository` for the repositories that git opens, which the `autoRepoDetection` setting limits to those in
* the workspace folders by default. The workspace folders can change, such as in the agents window, where they follow
* the active session, so a repository that git opened before its folder was added is added with its folder.
*/
export function detectRepositories(git: GitApiImpl, reposManager: RepositoriesManager, addRepository: (repo: Repository) => void): vscode.Disposable {
const onRepositoryOpened = (repo: Repository) => {
const detectionMode = vscode.workspace.getConfiguration(PR_SETTINGS_NAMESPACE).get<AutoRepoDetectionVariants>(AUTO_REPO_DETECTION, 'workspace');
if (detectionMode === 'workspace') {
const workspaceFolders = vscode.workspace.workspaceFolders;
Logger.debug(`Checking if repo ${repo.rootUri.fsPath} is in a workspace folder.`, ACTIVATION);
Logger.debug(`Workspace folders: ${workspaceFolders?.map(folder => folder.uri.fsPath).join(', ')}`, ACTIVATION);
if (workspaceFolders && !isRepositoryInFolders(repo, workspaceFolders)) {
Logger.appendLine(`Repo ${repo.rootUri} is not in a workspace folder, ignoring.`, ACTIVATION);
return;
}
} else {
Logger.debug(`Auto-detection is enabled for all Git repositories.`, ACTIVATION);
}

addRepository(repo);
const disposable = repo.state.onDidChange(() => {
Logger.appendLine(`Repo state for ${repo.rootUri} changed.`, ACTIVATION);
addRepository(repo);
disposable.dispose();
});
};

return vscode.Disposable.from(
git.onDidOpenRepository(onRepositoryOpened),
// Git doesn't open a repository again when its folder is added.
vscode.workspace.onDidChangeWorkspaceFolders(e => {
for (const repo of git.repositories) {
const isManaged = reposManager.folderManagers.some(manager => manager.repository.rootUri.toString() === repo.rootUri.toString());
if (!isManaged && isRepositoryInFolders(repo, e.added)) {
onRepositoryOpened(repo);
}
}
}),
);
}
35 changes: 26 additions & 9 deletions src/issues/stateManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ export class StateManager {
public readonly onDidChangeCurrentIssue: vscode.Event<void> = this._onDidChangeCurrentIssue.event;
private initializePromise: Promise<void> | undefined;
private statusBarItem?: vscode.StatusBarItem;
private readonly _foldersRefreshingWhenRepositoriesAdded = new WeakSet<FolderRepositoryManager>();

getIssueCollection(uri: vscode.Uri): Map<string, Promise<IssueQueryResult>> {
let collection = this._singleRepoStates.get(uri.path)?.issueCollection;
Expand Down Expand Up @@ -266,16 +267,15 @@ export class StateManager {
}),
);

for (const folderManager of this.manager.folderManagers) {
this.context.subscriptions.push(folderManager.onDidChangeRepositories(async (e) => {
if (e.added) {
const state = this.getOrCreateSingleRepoState(folderManager.repository.rootUri);
// Repositories can also be opened after initialization, such as when the agents window shows the folder of another session.
this.context.subscriptions.push(this.manager.onDidChangeFolderRepositories(e => {
if (e.added) {
this.refreshWhenRepositoriesAdded(e.added);
}
}));

if (state && ((state.issueCollection.size === 0) || (await Promise.all(state.issueCollection.values())).some(collection => collection.issues === undefined))) {
this.refresh(folderManager);
}
}
}));
for (const folderManager of this.manager.folderManagers) {
this.refreshWhenRepositoriesAdded(folderManager);

const singleRepoState: SingleRepoState | undefined = this.getOrCreateSingleRepoState(
folderManager.repository.rootUri,
Expand All @@ -295,6 +295,23 @@ export class StateManager {
}
}

/** Refreshes the issues of a folder once its GitHub repositories are added, if they were queried before. */
private refreshWhenRepositoriesAdded(folderManager: FolderRepositoryManager) {
if (this._foldersRefreshingWhenRepositoriesAdded.has(folderManager)) {
return;
}
this._foldersRefreshingWhenRepositoriesAdded.add(folderManager);
this.context.subscriptions.push(folderManager.onDidChangeRepositories(async (e) => {
if (e.added) {
const state = this.getOrCreateSingleRepoState(folderManager.repository.rootUri);

if (state && ((state.issueCollection.size === 0) || (await Promise.all(state.issueCollection.values())).some(collection => collection.issues === undefined))) {
this.refresh(folderManager);
}
}
}));
}

private cleanIssueState() {
const stateString: string | undefined = this.context.workspaceState.get(ISSUES_KEY);
const state: IssuesState = stateString ? JSON.parse(stateString) : { issues: [], branches: [] };
Expand Down
82 changes: 82 additions & 0 deletions src/lm/chatContextScope.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import * as vscode from 'vscode';
import { AuthProvider } from '../common/authentication';
import Logger from '../common/logger';
import { Protocol } from '../common/protocol';
import { formatError, isDescendant } from '../common/utils';
import { CredentialStore } from '../github/credentials';
import { FolderRepositoryManager } from '../github/folderRepositoryManager';
import { IssueModel } from '../github/issueModel';
import { RepositoriesManager } from '../github/repositoriesManager';

const ID = 'ChatContext';
const SEARCH_RESULT_LIMIT = 50;

/** An issue or pull request found by search, which is only fetched when it is attached. */
export interface IssueOrPullRequestReference {
readonly owner: string;
readonly repo: string;
readonly number: number;
readonly title: string;
}

/**
* The folder managers whose GitHub issues and pull requests can be attached as context. The folders of an
* agent-managed workspace follow the active session, or the folder chosen for a new session, so a repository
* that was opened for another session isn't one the user is working in.
*/
export function getFolderManagersInScope(reposManager: RepositoriesManager): FolderRepositoryManager[] {
const folderManagers = reposManager.folderManagers.filter(folderManager => folderManager.gitHubRepositories.length > 0);
if (!vscode.workspace.isAgentManaged) {
return folderManagers;
}
const workspaceFolders = vscode.workspace.workspaceFolders ?? [];
return folderManagers.filter(folderManager => {
const root = folderManager.repository.rootUri.fsPath;
return workspaceFolders.some(folder => isDescendant(folder.uri.fsPath, root, true) || isDescendant(root, folder.uri.fsPath, true));
});
}

/**
* Whether no folder is open, such as for a chat without a folder in the agents window. Without a folder there is no
* repository to list issues and pull requests of, so those involving the user are listed instead.
*/
export function hasNoWorkspaceFolder(): boolean {
return !vscode.workspace.workspaceFolders?.length;
}

/** Identifies an issue or pull request, so that one listed by several folders or queries is offered once. */
export function getIssueOrPullRequestKey(item: IssueModel): string {
// A repository on GitHub.com and one on GitHub Enterprise can have the same owner and name.
return `${item.remote.normalizedHost}/${item.remote.owner}/${item.remote.repositoryName}#${item.number}`.toLowerCase();
}

/** Searches GitHub.com for the open issues or pull requests that involve the signed in user. */
export async function searchInvolvingCurrentUser(credentialStore: CredentialStore, type: 'issue' | 'pr'): Promise<IssueOrPullRequestReference[]> {
const hub = credentialStore.getHub(AuthProvider.github);
if (!hub) {
// GitHub Enterprise isn't searched: its results would also need their server to be fetched.
Logger.appendLine(`Not searching for ${type === 'pr' ? 'pull requests' : 'issues'} involving the current user: not signed in to GitHub.com.`, ID);
return [];
}
try {
const { data } = await hub.octokit.call(hub.octokit.api.search.issuesAndPullRequests, {
q: `is:open is:${type} involves:@me archived:false`,
sort: 'updated',
order: 'desc',
per_page: SEARCH_RESULT_LIMIT,
advanced_search: 'true',
});
return data.items.map(item => {
const repository = new Protocol(item.repository_url);
return { owner: repository.owner, repo: repository.repositoryName, number: item.number, title: item.title };
});
} catch (e) {
Logger.error(`Failed to search for ${type === 'pr' ? 'pull requests' : 'issues'} involving the current user: ${formatError(e)}`, ID);
return [];
}
}
Loading
Loading