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

Commit a022afd

Browse files
committed
Implement exclude patterns from workspace settings
1 parent d91e8e4 commit a022afd

File tree

7 files changed

+241
-68
lines changed

7 files changed

+241
-68
lines changed

.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: 57 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,34 @@ 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+
// Remove the surrounding braces and split by comma
315+
const content = patternString.slice(1, -1)
316+
return content ? content.split(',') : []
317+
}
318+
268319
private reset(): void {
269320
this.lastFetchTimestamp = 0
270321
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/cody-ignore/context-filter.ts

Lines changed: 173 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,161 @@
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+
interface CachedExcludeData {
8+
gitignoreExclude: IgnoreRecord
9+
ignoreExclude: IgnoreRecord
10+
sgignoreExclude: IgnoreRecord
11+
}
12+
13+
const excludeCache = new Map<string, CachedExcludeData>()
14+
const fileWatchers = new Map<string, vscode.FileSystemWatcher>()
15+
16+
function getCacheKey(workspaceFolder: vscode.WorkspaceFolder | null): string {
17+
return workspaceFolder?.uri.toString() ?? 'no-workspace'
18+
}
19+
20+
export async function initializeCache(workspaceFolder: vscode.WorkspaceFolder | null): Promise<void> {
21+
const cacheKey = getCacheKey(workspaceFolder)
22+
if (excludeCache.has(cacheKey)) {
23+
return
24+
}
25+
26+
const useIgnoreFiles = vscode.workspace
27+
.getConfiguration('', workspaceFolder)
28+
.get<boolean>('search.useIgnoreFiles')
29+
30+
let gitignoreExclude: IgnoreRecord = {}
31+
let ignoreExclude: IgnoreRecord = {}
32+
let sgignoreExclude: IgnoreRecord = {}
33+
34+
if (useIgnoreFiles && workspaceFolder) {
35+
gitignoreExclude = await readIgnoreFile(vscode.Uri.joinPath(workspaceFolder.uri, '.gitignore'))
36+
ignoreExclude = await readIgnoreFile(vscode.Uri.joinPath(workspaceFolder.uri, '.ignore'))
37+
sgignoreExclude = await readIgnoreFile(
38+
vscode.Uri.joinPath(workspaceFolder.uri, '.sourcegraph', '.ignore')
39+
)
40+
41+
setupFileWatcher(workspaceFolder, '.gitignore')
42+
setupFileWatcher(workspaceFolder, '.ignore')
43+
setupFileWatcher(workspaceFolder, '.sourcegraph/.ignore')
44+
}
45+
46+
excludeCache.set(cacheKey, { gitignoreExclude, ignoreExclude, sgignoreExclude })
47+
}
48+
49+
function setupFileWatcher(workspaceFolder: vscode.WorkspaceFolder, filename: string): void {
50+
const watcherKey = `${workspaceFolder.uri.toString()}:${filename}`
51+
if (fileWatchers.has(watcherKey)) {
52+
return
53+
}
54+
55+
const pattern = new vscode.RelativePattern(workspaceFolder, filename)
56+
const watcher = vscode.workspace.createFileSystemWatcher(pattern)
57+
58+
const updateCache = async () => {
59+
const cacheKey = getCacheKey(workspaceFolder)
60+
const cached = excludeCache.get(cacheKey)
61+
if (!cached) return
62+
63+
const fileUri = vscode.Uri.joinPath(workspaceFolder.uri, filename)
64+
const ignoreData = await readIgnoreFile(fileUri)
65+
66+
if (filename === '.gitignore') {
67+
cached.gitignoreExclude = ignoreData
68+
} else if (filename === '.ignore') {
69+
cached.ignoreExclude = ignoreData
70+
} else if (filename === '.sourcegraph/.ignore') {
71+
cached.sgignoreExclude = ignoreData
72+
}
73+
}
74+
75+
watcher.onDidChange(updateCache)
76+
watcher.onDidCreate(updateCache)
77+
watcher.onDidDelete(() => {
78+
const cacheKey = getCacheKey(workspaceFolder)
79+
const cached = excludeCache.get(cacheKey)
80+
if (!cached) return
81+
82+
if (filename === '.gitignore') {
83+
cached.gitignoreExclude = {}
84+
} else if (filename === '.ignore') {
85+
cached.ignoreExclude = {}
86+
} else if (filename === '.sourcegraph/.ignore') {
87+
cached.sgignoreExclude = {}
88+
}
89+
})
90+
91+
fileWatchers.set(watcherKey, watcher)
92+
}
93+
94+
export async function getExcludePattern(
95+
workspaceFolder: vscode.WorkspaceFolder | null
96+
): Promise<string> {
97+
await initializeCache(workspaceFolder)
98+
99+
const config = vscode.workspace.getConfiguration('', workspaceFolder)
100+
const filesExclude = config.get<IgnoreRecord>('files.exclude', {})
101+
const searchExclude = config.get<IgnoreRecord>('search.exclude', {})
102+
103+
const cacheKey = getCacheKey(workspaceFolder)
104+
const cached = excludeCache.get(cacheKey)
105+
const gitignoreExclude = cached?.gitignoreExclude ?? {}
106+
const ignoreExclude = cached?.ignoreExclude ?? {}
107+
const sgignoreExclude = cached?.sgignoreExclude ?? {}
108+
109+
const mergedExclude: IgnoreRecord = {
110+
...filesExclude,
111+
...searchExclude,
112+
...gitignoreExclude,
113+
...ignoreExclude,
114+
...sgignoreExclude,
115+
}
116+
const excludePatterns = Object.keys(mergedExclude).filter(key => mergedExclude[key] === true)
117+
return `{${excludePatterns.join(',')}}`
118+
}
119+
120+
async function readIgnoreFile(uri: vscode.Uri): Promise<IgnoreRecord> {
121+
const ignore: IgnoreRecord = {}
122+
try {
123+
const data = await vscode.workspace.fs.readFile(uri)
124+
for (let line of Buffer.from(data).toString('utf-8').split('\n')) {
125+
if (line.startsWith('!')) {
126+
continue
127+
}
128+
129+
// Strip comment and trailing whitespace.
130+
line = line.replace(/\s*(#.*)?$/, '')
131+
132+
if (line === '') {
133+
continue
134+
}
135+
136+
if (line.endsWith('/')) {
137+
line = line.slice(0, -1)
138+
}
139+
if (!line.startsWith('/') && !line.startsWith('**/')) {
140+
line = `**/${line}`
141+
}
142+
ignore[line] = true
143+
}
144+
} catch {}
145+
return ignore
146+
}
147+
148+
/**
149+
* Dispose all file watchers and clear caches. Call this when the extension is deactivated.
150+
*/
151+
function disposeFileWatchers(): void {
152+
for (const watcher of fileWatchers.values()) {
153+
watcher.dispose()
154+
}
155+
fileWatchers.clear()
156+
excludeCache.clear()
157+
}
158+
5159
export async function isUriIgnoredByContextFilterWithNotification(
6160
uri: vscode.Uri,
7161
feature: CodyIgnoreFeature
@@ -12,3 +166,20 @@ export async function isUriIgnoredByContextFilterWithNotification(
12166
}
13167
return isIgnored
14168
}
169+
170+
/**
171+
* Initialize the ContextFiltersProvider with exclude pattern getter.
172+
* Returns a disposable that cleans up the configuration when disposed.
173+
*/
174+
export function initializeContextFiltersProvider(): vscode.Disposable {
175+
// Set up exclude pattern getter for ContextFiltersProvider
176+
ContextFiltersProvider.excludePatternGetter = {
177+
getExcludePattern,
178+
getWorkspaceFolder: (uri: vscode.Uri) => vscode.workspace.getWorkspaceFolder(uri) ?? null,
179+
}
180+
181+
// Return disposable that cleans up the configuration
182+
return {
183+
dispose: disposeFileWatchers,
184+
}
185+
}

0 commit comments

Comments
 (0)