Skip to content
This repository was archived by the owner on Aug 1, 2025. It is now read-only.

Commit 2fc9def

Browse files
committed
Implement exclude patterns from workspace settings
1 parent 8d59866 commit 2fc9def

8 files changed

Lines changed: 215 additions & 67 deletions

File tree

.sourcegraph/ignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
recordings/

lib/shared/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
"lexical": "^0.17.0",
3636
"lodash": "^4.17.21",
3737
"lru-cache": "^10.0.0",
38+
"minimatch": "^9.0.3",
3839
"ollama": "^0.5.1",
3940
"re2js": "^0.4.1",
4041
"semver": "^7.5.4",

lib/shared/src/cody-ignore/context-filters-provider.ts

Lines changed: 61 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { isError } from 'lodash'
22
import isEqual from 'lodash/isEqual'
33
import { LRUCache } from 'lru-cache'
4+
import { minimatch } from 'minimatch'
45
import type { Observable } from 'observable-fns'
56
import { RE2JS as RE2 } from 're2js'
67
import type * as vscode from 'vscode'
@@ -22,6 +23,8 @@ import {
2223
import { wrapInActiveSpan } from '../tracing'
2324
import { createSubscriber } from '../utils'
2425

26+
type GetExcludePattern = (workspaceFolder: vscode.WorkspaceFolder | null) => Promise<string>
27+
2528
interface ParsedContextFilters {
2629
include: null | ParsedContextFilterItem[]
2730
exclude: null | ParsedContextFilterItem[]
@@ -32,13 +35,21 @@ interface ParsedContextFilterItem {
3235
filePathPatterns?: RE2[]
3336
}
3437

38+
enum ContextFiltersProviderError {
39+
NoRepoFound = 'no-repo-found',
40+
NonFileUri = 'non-file-uri',
41+
HasIgnoreEverythingFilters = 'has-ignore-everything-filters',
42+
ExcludePatternMatch = 'exclude-pattern-match',
43+
}
44+
3545
// Note: This can not be an empty string to make all non `false` values truthy.
3646
export type IsIgnored =
3747
| false
3848
| Error
39-
| 'has-ignore-everything-filters'
40-
| 'non-file-uri'
41-
| 'no-repo-found'
49+
| ContextFiltersProviderError.NoRepoFound
50+
| ContextFiltersProviderError.NonFileUri
51+
| ContextFiltersProviderError.HasIgnoreEverythingFilters
52+
| ContextFiltersProviderError.ExcludePatternMatch
4253
| `repo:${string}`
4354

4455
export type GetRepoNamesContainingUri = (
@@ -92,6 +103,11 @@ export class ContextFiltersProvider implements vscode.Disposable {
92103
private readonly contextFiltersSubscriber = createSubscriber<ContextFilters | Error>()
93104
public readonly onContextFiltersChanged = this.contextFiltersSubscriber.subscribe
94105

106+
static excludePatternGetter: {
107+
getExcludePattern: GetExcludePattern
108+
getWorkspaceFolder: (uri: vscode.Uri) => vscode.WorkspaceFolder | null
109+
}
110+
95111
// Fetches context filters and updates the cached filter results
96112
private async fetchContextFilters(): Promise<RefetchIntervalHint> {
97113
try {
@@ -223,12 +239,19 @@ export class ContextFiltersProvider implements vscode.Disposable {
223239

224240
await this.fetchIfNeeded()
225241

242+
// Check VS Code exclude patterns
243+
if (ContextFiltersProvider.excludePatternGetter) {
244+
if (await this.isExcludedByPatterns(uri)) {
245+
return ContextFiltersProviderError.ExcludePatternMatch
246+
}
247+
}
248+
226249
if (this.hasAllowEverythingFilters()) {
227250
return false
228251
}
229252

230253
if (this.hasIgnoreEverythingFilters()) {
231-
return 'has-ignore-everything-filters'
254+
return ContextFiltersProviderError.HasIgnoreEverythingFilters
232255
}
233256

234257
const maybeError = this.lastContextFiltersResponse
@@ -239,7 +262,7 @@ export class ContextFiltersProvider implements vscode.Disposable {
239262
// TODO: process non-file URIs https://github.com/sourcegraph/cody/issues/3893
240263
if (!isFileURI(uri)) {
241264
logDebug('ContextFiltersProvider', 'isUriIgnored', `non-file URI ${uri.scheme}`)
242-
return 'non-file-uri'
265+
return ContextFiltersProviderError.NonFileUri
243266
}
244267

245268
if (!ContextFiltersProvider.repoNameResolver) {
@@ -254,7 +277,7 @@ export class ContextFiltersProvider implements vscode.Disposable {
254277
)
255278

256279
if (!repoNames?.length) {
257-
return 'no-repo-found'
280+
return ContextFiltersProviderError.NoRepoFound
258281
}
259282

260283
const ignoredRepo = repoNames.find(repoName => this.isRepoNameIgnored__noFetch(repoName))
@@ -265,6 +288,38 @@ export class ContextFiltersProvider implements vscode.Disposable {
265288
return false
266289
}
267290

291+
private async isExcludedByPatterns(uri: vscode.Uri): Promise<boolean> {
292+
try {
293+
const workspaceFolder = ContextFiltersProvider.excludePatternGetter.getWorkspaceFolder(uri)
294+
const excludePatternString =
295+
await ContextFiltersProvider.excludePatternGetter.getExcludePattern(workspaceFolder)
296+
297+
// Parse the pattern string {pattern1,pattern2,...} into individual patterns
298+
const patterns = this.parseExcludePatternString(excludePatternString)
299+
300+
// Get the relative path from workspace folder
301+
const relativePath = workspaceFolder
302+
? uri.fsPath.substring(workspaceFolder.uri.fsPath.length + 1)
303+
: uri.fsPath
304+
305+
// Check if any pattern matches the file path
306+
return patterns.some(pattern => minimatch(relativePath, pattern, { dot: true }))
307+
} catch (error) {
308+
logDebug('ContextFiltersProvider', 'isExcludedByPatterns error', { error })
309+
return false
310+
}
311+
}
312+
313+
private parseExcludePatternString(patternString: string): string[] {
314+
// Check if pattern string has the expected format {pattern1,pattern2,...}
315+
if (!patternString.startsWith('{') || !patternString.endsWith('}')) {
316+
return []
317+
}
318+
// Remove the surrounding braces and split by comma
319+
const content = patternString.slice(1, -1)
320+
return content ? content.split(',') : []
321+
}
322+
268323
private reset(): void {
269324
this.lastFetchTimestamp = 0
270325
this.lastResultLifetime = Promise.resolve(TRANSIENT_REFETCH_INTERVAL_HINT)

pnpm-lock.yaml

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

vscode/src/editor/utils/findWorkspaceFiles.test.ts renamed to vscode/src/cody-ignore/context-filter.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ vi.mock('vscode', () => ({
1313
}))
1414

1515
import * as vscode from 'vscode'
16-
import { readIgnoreFile } from './findWorkspaceFiles'
16+
import { readIgnoreFile } from './context-filter'
1717

1818
describe('readIgnoreFile', () => {
1919
it('parses basic gitignore patterns', async () => {

vscode/src/cody-ignore/context-filter.ts

Lines changed: 144 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,98 @@
1-
import { type IsIgnored, contextFiltersProvider } from '@sourcegraph/cody-shared'
2-
import type * as vscode from 'vscode'
1+
import { ContextFiltersProvider, type IsIgnored, contextFiltersProvider } from '@sourcegraph/cody-shared'
2+
import * as vscode from 'vscode'
33
import { type CodyIgnoreFeature, showCodyIgnoreNotification } from './notification'
44

5+
type IgnoreRecord = Record<string, boolean>
6+
7+
const excludeCache = new Map<string, IgnoreRecord>()
8+
const fileWatchers = new Map<string, vscode.FileSystemWatcher>()
9+
10+
function getCacheKey(workspaceFolder: vscode.WorkspaceFolder | null): string {
11+
return workspaceFolder?.uri.toString() ?? 'no-workspace'
12+
}
13+
14+
export async function initializeCache(workspaceFolder: vscode.WorkspaceFolder | null): Promise<void> {
15+
const cacheKey = getCacheKey(workspaceFolder)
16+
if (excludeCache.has(cacheKey)) {
17+
return
18+
}
19+
20+
const useIgnoreFiles = vscode.workspace
21+
.getConfiguration('', workspaceFolder)
22+
.get<boolean>('search.useIgnoreFiles')
23+
24+
let sgignoreExclude: IgnoreRecord = {}
25+
26+
if (useIgnoreFiles && workspaceFolder) {
27+
sgignoreExclude = await readIgnoreFile(
28+
vscode.Uri.joinPath(workspaceFolder.uri, '.sourcegraph', 'ignore')
29+
)
30+
31+
setupFileWatcher(workspaceFolder, '.sourcegraph/ignore')
32+
}
33+
34+
excludeCache.set(cacheKey, sgignoreExclude)
35+
}
36+
37+
function setupFileWatcher(workspaceFolder: vscode.WorkspaceFolder, filename: string): void {
38+
const watcherKey = `${workspaceFolder.uri.toString()}:${filename}`
39+
if (fileWatchers.has(watcherKey)) {
40+
return
41+
}
42+
43+
const pattern = new vscode.RelativePattern(workspaceFolder, filename)
44+
const watcher = vscode.workspace.createFileSystemWatcher(pattern)
45+
46+
const updateCache = async () => {
47+
const cacheKey = getCacheKey(workspaceFolder)
48+
const cached = excludeCache.get(cacheKey)
49+
if (!cached) return
50+
51+
const fileUri = vscode.Uri.joinPath(workspaceFolder.uri, filename)
52+
const ignoreData = await readIgnoreFile(fileUri)
53+
54+
if (filename === '.sourcegraph/ignore') {
55+
excludeCache.set(cacheKey, ignoreData)
56+
}
57+
}
58+
59+
watcher.onDidChange(updateCache)
60+
watcher.onDidCreate(updateCache)
61+
watcher.onDidDelete(() => {
62+
const cacheKey = getCacheKey(workspaceFolder)
63+
const cached = excludeCache.get(cacheKey)
64+
if (!cached) return
65+
66+
if (filename === '.sourcegraph/ignore') {
67+
excludeCache.delete(cacheKey)
68+
}
69+
})
70+
71+
fileWatchers.set(watcherKey, watcher)
72+
}
73+
74+
export async function getExcludePattern(
75+
workspaceFolder: vscode.WorkspaceFolder | null
76+
): Promise<string> {
77+
await initializeCache(workspaceFolder)
78+
79+
const cacheKey = getCacheKey(workspaceFolder)
80+
const cached = excludeCache.get(cacheKey)
81+
const excludePatterns = Object.keys(cached ?? {}).filter(key => cached?.[key] === true)
82+
return `{${excludePatterns.join(',')}}`
83+
}
84+
85+
/**
86+
* Dispose all file watchers and clear caches. Call this when the extension is deactivated.
87+
*/
88+
function disposeFileWatchers(): void {
89+
for (const watcher of fileWatchers.values()) {
90+
watcher.dispose()
91+
}
92+
fileWatchers.clear()
93+
excludeCache.clear()
94+
}
95+
596
export async function isUriIgnoredByContextFilterWithNotification(
697
uri: vscode.Uri,
798
feature: CodyIgnoreFeature
@@ -12,3 +103,54 @@ export async function isUriIgnoredByContextFilterWithNotification(
12103
}
13104
return isIgnored
14105
}
106+
107+
/**
108+
* Initialize the ContextFiltersProvider with exclude pattern getter.
109+
* Returns a disposable that cleans up the configuration when disposed.
110+
*/
111+
export function initializeContextFiltersProvider(): vscode.Disposable {
112+
// Set up exclude pattern getter for ContextFiltersProvider
113+
ContextFiltersProvider.excludePatternGetter = {
114+
getExcludePattern,
115+
getWorkspaceFolder: (uri: vscode.Uri) => vscode.workspace.getWorkspaceFolder(uri) ?? null,
116+
}
117+
118+
// Return disposable that cleans up the configuration
119+
return {
120+
dispose: disposeFileWatchers,
121+
}
122+
}
123+
124+
export async function readIgnoreFile(uri: vscode.Uri): Promise<IgnoreRecord> {
125+
const ignore: IgnoreRecord = {}
126+
try {
127+
const data = await vscode.workspace.fs.readFile(uri)
128+
for (let line of Buffer.from(data).toString('utf-8').split('\n')) {
129+
if (line.startsWith('!')) {
130+
continue
131+
}
132+
133+
// Strip comment and whitespace.
134+
line = line.replace(/\s*(#.*)?$/, '').trim()
135+
136+
if (line === '') {
137+
continue
138+
}
139+
140+
// Replace , with . that contain commas to avoid typos for entries such as
141+
// *,something
142+
if (line.includes(',')) {
143+
line = line.replace(',', '.')
144+
}
145+
146+
if (line.endsWith('/')) {
147+
line = line.slice(0, -1)
148+
}
149+
if (!line.startsWith('/') && !line.startsWith('**/')) {
150+
line = `**/${line}`
151+
}
152+
ignore[line] = true
153+
}
154+
} catch {}
155+
return ignore
156+
}
Lines changed: 1 addition & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as vscode from 'vscode'
2+
import { getExcludePattern } from '../../cody-ignore/context-filter'
23

34
/**
45
* Find all files in all workspace folders, respecting the user's `files.exclude`, `search.exclude`,
@@ -14,61 +15,3 @@ export async function findWorkspaceFiles(): Promise<ReadonlyArray<vscode.Uri>> {
1415

1516
return vscode.workspace.findFiles('**/*', `{${excludePatterns.join(',')}}`)
1617
}
17-
18-
type IgnoreRecord = Record<string, boolean>
19-
20-
async function getExcludePattern(workspaceFolder: vscode.WorkspaceFolder | null): Promise<string[]> {
21-
const config = vscode.workspace.getConfiguration('', workspaceFolder)
22-
const filesExclude = config.get<IgnoreRecord>('files.exclude', {})
23-
const searchExclude = config.get<IgnoreRecord>('search.exclude', {})
24-
const useIgnoreFiles = config.get<boolean>('search.useIgnoreFiles')
25-
const gitignoreExclude =
26-
useIgnoreFiles && workspaceFolder
27-
? await readIgnoreFile(vscode.Uri.joinPath(workspaceFolder.uri, '.gitignore'))
28-
: {}
29-
const ignoreExclude =
30-
useIgnoreFiles && workspaceFolder
31-
? await readIgnoreFile(vscode.Uri.joinPath(workspaceFolder.uri, '.ignore'))
32-
: {}
33-
const mergedExclude: IgnoreRecord = {
34-
...filesExclude,
35-
...searchExclude,
36-
...gitignoreExclude,
37-
...ignoreExclude,
38-
}
39-
return Object.keys(mergedExclude).filter(key => mergedExclude[key] === true)
40-
}
41-
42-
export async function readIgnoreFile(uri: vscode.Uri): Promise<IgnoreRecord> {
43-
const ignore: IgnoreRecord = {}
44-
try {
45-
const data = await vscode.workspace.fs.readFile(uri)
46-
for (let line of Buffer.from(data).toString('utf-8').split('\n')) {
47-
if (line.startsWith('!')) {
48-
continue
49-
}
50-
51-
// Strip comment and whitespace.
52-
line = line.replace(/\s*(#.*)?$/, '').trim()
53-
54-
if (line === '') {
55-
continue
56-
}
57-
58-
// Replace , with . that contain commas to avoid typos for entries such as
59-
// *,something
60-
if (line.includes(',')) {
61-
line = line.replace(',', '.')
62-
}
63-
64-
if (line.endsWith('/')) {
65-
line = line.slice(0, -1)
66-
}
67-
if (!line.startsWith('/') && !line.startsWith('**/')) {
68-
line = `**/${line}`
69-
}
70-
ignore[line] = true
71-
}
72-
} catch {}
73-
return ignore
74-
}

0 commit comments

Comments
 (0)