diff --git a/.github/workflows/javascript.yml b/.github/workflows/javascript.yml
index fa1c947..191a360 100644
--- a/.github/workflows/javascript.yml
+++ b/.github/workflows/javascript.yml
@@ -68,7 +68,10 @@ jobs:
test:
strategy:
matrix:
- os: [macos-latest, ubuntu-latest, windows-latest]
+ include:
+ - { os: macos-latest, target: darwin-arm64 }
+ - { os: ubuntu-latest, target: linux-x64 }
+ - { os: windows-latest, target: win32-x64 }
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
@@ -81,6 +84,12 @@ jobs:
node-version-file: "package.json"
- name: Install dependencies
run: npm ci
+ - name: Download gh-codeowners
+ shell: bash
+ run: ./s/download-server "$TARGET"
+ env:
+ TARGET: ${{ matrix.target }}
+ GH_TOKEN: ${{ github.token }}
- name: Run tests ${{ matrix.os }}
if: runner.os == 'Linux'
run: xvfb-run -a npm test
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 6aa76d4..a15bc47 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -7,8 +7,24 @@ on:
permissions: {}
jobs:
+ # A build for each platform bundles gh-codeowners as the language server.
+ # The universal build has no binary, for other platforms, and falls back to
+ # the built-in features.
publish:
if: ${{ !github.event.release.prerelease }}
+ strategy:
+ fail-fast: false
+ matrix:
+ target:
+ - darwin-arm64
+ - darwin-x64
+ - linux-x64
+ - linux-arm64
+ - alpine-x64
+ - alpine-arm64
+ - win32-x64
+ - win32-arm64
+ - universal
runs-on: ubuntu-latest
environment: marketplace
permissions:
@@ -28,5 +44,18 @@ jobs:
run: test "$GITHUB_REF_NAME" = "v$(node -p "require('./package.json').version")"
- name: Install dependencies
run: npm ci
+ - name: Download gh-codeowners
+ if: matrix.target != 'universal'
+ run: ./s/download-server "$TARGET"
+ env:
+ TARGET: ${{ matrix.target }}
+ GH_TOKEN: ${{ github.token }}
- name: Publish to Visual Studio Marketplace
- run: npx --no-install vsce publish --oidc
+ run: |
+ if [[ "$TARGET" == universal ]]; then
+ npx --no-install vsce publish --oidc
+ else
+ npx --no-install vsce publish --oidc --target "$TARGET"
+ fi
+ env:
+ TARGET: ${{ matrix.target }}
diff --git a/.gitignore b/.gitignore
index 1148ef3..7f675ab 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,3 +2,4 @@ node_modules
*.vsix
out
.vscode-test
+/bin
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 99380b6..2d4d1d3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+## 5.0.0 - 2026-11-07
+
+### Changed
+
+- Use the gh-codeowners language server for errors and file counts (#42).
+
## 4.3.0 - 2026-11-04
### Changed
diff --git a/README.md b/README.md
index 27b274b..3af09ac 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,9 @@
-# [github-code-owners](https://github.com/chdsbd/vscode-github-code-owners) [](https://marketplace.visualstudio.com/items?itemName=chdsbd.github-code-owners) [](https://marketplace.visualstudio.com/items?itemName=chdsbd.github-code-owners)
+# GitHub Code Owners
A VS Code extension to display the GitHub Code Owners for the current file, as defined in the [CODEOWNERS](https://help.github.com/articles/about-codeowners/) file.
+[Install on the Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=chdsbd.github-code-owners)
+
## Features
### Status bar
@@ -12,6 +14,22 @@ Shows the first code owner. Click to see matching line in CODEOWNERS file.
### Language support
+The extension uses [gh-codeowners](https://github.com/chdsbd/gh-codeowners) to count file matches and warn about unused or malformed rules.
+
+#### Counts for matching rules
+
+
+
+#### Warning for unused rules
+
+
+
+#### Quick fixes for invalid patterns
+
+
+
+
+
#### Link usernames to GitHub
diff --git a/images/invalid-pattern.png b/images/invalid-pattern.png
new file mode 100644
index 0000000..ee68cde
Binary files /dev/null and b/images/invalid-pattern.png differ
diff --git a/images/no-files-match.png b/images/no-files-match.png
new file mode 100644
index 0000000..dbe626c
Binary files /dev/null and b/images/no-files-match.png differ
diff --git a/images/owns-4-files.png b/images/owns-4-files.png
new file mode 100644
index 0000000..f166ba1
Binary files /dev/null and b/images/owns-4-files.png differ
diff --git a/images/quick-fix.png b/images/quick-fix.png
new file mode 100644
index 0000000..9cf22b6
Binary files /dev/null and b/images/quick-fix.png differ
diff --git a/package-lock.json b/package-lock.json
index 7f8a9c7..36fa89b 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,22 +1,23 @@
{
"name": "github-code-owners",
- "version": "4.3.0",
+ "version": "5.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "github-code-owners",
- "version": "4.3.0",
+ "version": "5.0.0",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@snyk/github-codeowners": "github:chdsbd/github-codeowners#bb24c2adb022a88e03f25a3680a23934a281a5c3",
- "lodash": "^4.17.21"
+ "lodash": "^4.17.21",
+ "vscode-languageclient": "11.0.0"
},
"devDependencies": {
"@types/lodash": "^4.14.195",
"@types/mocha": "^10.0.4",
"@types/node": "^24.19.2",
- "@types/vscode": "^1.53.0",
+ "@types/vscode": "1.91.0",
"@typescript-eslint/eslint-plugin": "^5.54.1",
"@typescript-eslint/parser": "^5.54.1",
"@vscode/test-cli": "^0.0.9",
@@ -1284,10 +1285,11 @@
"dev": true
},
"node_modules/@types/vscode": {
- "version": "1.53.0",
- "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.53.0.tgz",
- "integrity": "sha512-XjFWbSPOM0EKIT2XhhYm3D3cx3nn3lshMUcWNy1eqefk+oqRuBq8unVb6BYIZqXy9lQZyeUl7eaBCOZWv+LcXQ==",
- "dev": true
+ "version": "1.91.0",
+ "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.91.0.tgz",
+ "integrity": "sha512-PgPr+bUODjG3y+ozWUCyzttqR9EHny9sPAfJagddQjDwdtf66y2sDKJMnFZRuzBA2YtBGASqJGPil8VDUPvO6A==",
+ "dev": true,
+ "license": "MIT"
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "5.54.1",
@@ -5690,7 +5692,6 @@
"version": "7.8.5",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
- "dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
@@ -6459,6 +6460,88 @@
"url": "https://bevry.me/fund"
}
},
+ "node_modules/vscode-jsonrpc": {
+ "version": "10.0.0",
+ "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-10.0.0.tgz",
+ "integrity": "sha512-USSfxg0vDIpTQqlQBGxF3mBARyoS8cU7LHLpbYNh6dOJt32dlskxPWB0Irrh5TllTmyf7oNLAvqDqzklbwwnpA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.17.0"
+ }
+ },
+ "node_modules/vscode-languageclient": {
+ "version": "11.0.0",
+ "resolved": "https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-11.0.0.tgz",
+ "integrity": "sha512-kVyeGLfyd1M74PbMNPfFkgRnhMYgnt6YGc5uXr/tNMzCpfZ0wFtfiqmqX1M05kkdNgV0HSozEUPvgggJbyIAYw==",
+ "license": "MIT",
+ "dependencies": {
+ "minimatch": "^10.2.6",
+ "semver": "^7.8.1",
+ "vscode-languageserver-protocol": "3.18.5",
+ "vscode-languageserver-textdocument": "1.0.16"
+ },
+ "engines": {
+ "vscode": "^1.91.0"
+ }
+ },
+ "node_modules/vscode-languageclient/node_modules/balanced-match": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
+ "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
+ "license": "MIT",
+ "engines": {
+ "node": "18 || 20 || >=22"
+ }
+ },
+ "node_modules/vscode-languageclient/node_modules/brace-expansion": {
+ "version": "5.0.12",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
+ "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^4.0.2"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ }
+ },
+ "node_modules/vscode-languageclient/node_modules/minimatch": {
+ "version": "10.2.6",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
+ "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "brace-expansion": "^5.0.8"
+ },
+ "engines": {
+ "node": "18 || 20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/vscode-languageserver-protocol": {
+ "version": "3.18.5",
+ "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.18.5.tgz",
+ "integrity": "sha512-FW4fBMzZ99N8xeob4py0l050wgCoRgTpEq5Xcsb9lM1bc29UKGR/wSV+4knaqFxssFHajy7OzNiKP/m3U1ZEuA==",
+ "license": "MIT",
+ "dependencies": {
+ "vscode-jsonrpc": "10.0.0",
+ "vscode-languageserver-types": "3.18.5"
+ }
+ },
+ "node_modules/vscode-languageserver-textdocument": {
+ "version": "1.0.16",
+ "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.16.tgz",
+ "integrity": "sha512-qeNEuOi9a3qkqRf7Gfez2WL2VwlBTLCNekHBGO9kxPVUp9XuY15yfTJ9jwvOwKI0I2MhUUfZq95NSp+LK1CLQg==",
+ "license": "MIT"
+ },
+ "node_modules/vscode-languageserver-types": {
+ "version": "3.18.5",
+ "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.18.5.tgz",
+ "integrity": "sha512-kPd6+JQNz3HMJvjKlqUxERSlZHAntl/aGpsk7ImwIh0ewDKDcjgAEyVSYciPiOJD3ftbK9IrfiqUeTZLSbCizw==",
+ "license": "MIT"
+ },
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
diff --git a/package.json b/package.json
index b2f354a..a56274b 100644
--- a/package.json
+++ b/package.json
@@ -4,7 +4,7 @@
"description": "Quickly see GitHub Code Owners for the current file. Add syntax highlighting for CODEOWNERS files.",
"publisher": "chdsbd",
"license": "SEE LICENSE IN LICENSE",
- "version": "4.3.0",
+ "version": "5.0.0",
"icon": "images/logo256.png",
"homepage": "https://github.com/chdsbd/vscode-github-code-owners/blob/master/README.md",
"keywords": [
@@ -21,7 +21,7 @@
"url": "https://github.com/chdsbd/vscode-github-code-owners/issues"
},
"engines": {
- "vscode": "^1.53.0"
+ "vscode": "^1.91.0"
},
"categories": [
"Programming Languages",
@@ -29,7 +29,8 @@
"Other"
],
"activationEvents": [
- "workspaceContains:**/CODEOWNERS"
+ "workspaceContains:**/CODEOWNERS",
+ "onLanguage:codeowners"
],
"main": "./out/extension.js",
"contributes": {
@@ -75,6 +76,25 @@
"order": 2,
"description": "Space offset to use from the longest file pattern the first code owner when aligning."
},
+ "githubCodeOwners.fileCounts.enabled": {
+ "order": 6,
+ "type": "boolean",
+ "default": true,
+ "description": "Show how many files each rule owns at the end of its line."
+ },
+ "githubCodeOwners.languageServer.enabled": {
+ "order": 4,
+ "type": "boolean",
+ "default": true,
+ "markdownDescription": "Run [gh-codeowners](https://github.com/chdsbd/gh-codeowners) as a language server for errors, unused rules, file counts and owners. When disabled, the extension uses its simpler built-in checks."
+ },
+ "githubCodeOwners.languageServer.path": {
+ "order": 5,
+ "type": "string",
+ "default": "",
+ "scope": "machine",
+ "markdownDescription": "Path to a [gh-codeowners](https://github.com/chdsbd/gh-codeowners) binary to run as the language server, instead of the one bundled with the extension."
+ },
"githubCodeOwners.teamMapping.slack": {
"order": 3,
"type": "array",
@@ -215,7 +235,7 @@
"@types/lodash": "^4.14.195",
"@types/mocha": "^10.0.4",
"@types/node": "^24.19.2",
- "@types/vscode": "^1.53.0",
+ "@types/vscode": "^1.91.0",
"@typescript-eslint/eslint-plugin": "^5.54.1",
"@typescript-eslint/parser": "^5.54.1",
"@vscode/test-cli": "^0.0.9",
@@ -231,7 +251,8 @@
},
"dependencies": {
"@snyk/github-codeowners": "github:chdsbd/github-codeowners#bb24c2adb022a88e03f25a3680a23934a281a5c3",
- "lodash": "^4.17.21"
+ "lodash": "^4.17.21",
+ "vscode-languageclient": "^11.0.0"
},
"volta": {
"node": "24.22.1"
diff --git a/s/download-server b/s/download-server
new file mode 100755
index 0000000..7b0eab0
--- /dev/null
+++ b/s/download-server
@@ -0,0 +1,40 @@
+#!/usr/bin/env bash
+# s/download-server
+#
+# Download the gh-codeowners binary for a VS Code platform, like
+# darwin-arm64, into bin/, where the extension looks for its language server.
+set -euo pipefail
+
+GH_CODEOWNERS_VERSION=v0.2.0
+
+target=$1
+case "$target" in
+ darwin-arm64) asset=gh-codeowners-darwin-arm64 ;;
+ darwin-x64) asset=gh-codeowners-darwin-amd64 ;;
+ # The Linux binaries are static, so they run on Alpine too.
+ linux-x64 | alpine-x64) asset=gh-codeowners-linux-amd64 ;;
+ linux-arm64 | alpine-arm64) asset=gh-codeowners-linux-arm64 ;;
+ win32-x64) asset=gh-codeowners-windows-amd64.exe ;;
+ win32-arm64) asset=gh-codeowners-windows-arm64.exe ;;
+ *)
+ echo "No gh-codeowners binary for $target" >&2
+ exit 1
+ ;;
+esac
+
+exe=""
+if [[ "$asset" == *.exe ]]; then
+ exe=.exe
+fi
+
+cd "$(dirname "$0")/.."
+rm -rf bin
+mkdir bin
+gh release download "$GH_CODEOWNERS_VERSION" \
+ --repo chdsbd/gh-codeowners \
+ --pattern "$asset" \
+ --output "bin/gh-codeowners$exe"
+# The release is immutable, so GitHub's attestation lists each binary's digest.
+gh release verify-asset "$GH_CODEOWNERS_VERSION" "bin/gh-codeowners$exe" \
+ --repo chdsbd/gh-codeowners
+chmod +x "bin/gh-codeowners$exe"
diff --git a/src/configuration.ts b/src/configuration.ts
index c258f46..6e9d5d6 100644
--- a/src/configuration.ts
+++ b/src/configuration.ts
@@ -72,3 +72,25 @@ export function getTeamMappingSlack(): Array {
) ?? []
)
}
+
+export function getLanguageServerPath(): string | null {
+ const setting = vscode.workspace
+ .getConfiguration()
+ .get(`${LANGUAGE_SERVER}.path`)
+ return setting || null
+}
+
+export const FILE_COUNTS_ENABLED = "githubCodeOwners.fileCounts.enabled"
+
+export function isFileCountsEnabled(): boolean {
+ return vscode.workspace.getConfiguration().get(FILE_COUNTS_ENABLED) !== false
+}
+
+export const LANGUAGE_SERVER = "githubCodeOwners.languageServer"
+
+export function isLanguageServerEnabled(): boolean {
+ return (
+ vscode.workspace.getConfiguration().get(`${LANGUAGE_SERVER}.enabled`) !==
+ false
+ )
+}
diff --git a/src/extension.ts b/src/extension.ts
index 648ff96..c12913e 100644
--- a/src/extension.ts
+++ b/src/extension.ts
@@ -8,14 +8,25 @@ import { CodeownersHoverProvider } from "./codeowners-hover-provider"
import { statusBarTextEditorListener } from "./status-bar-text-editor-listener"
import { AlignOwnersFormattingProvider } from "./align-codeowners"
import { registerCodeownersDiagnostics } from "./codeowners-diagnostic-provider"
+import { CodeownersLanguageServer } from "./language-server"
+import { LANGUAGE_SERVER } from "./configuration"
const COMMAND_ID = "github-code-owners.show-owners"
const STATUS_BAR_PRIORITY = 100
-export function activate(context: vscode.ExtensionContext) {
+export async function activate(context: vscode.ExtensionContext) {
console.log("CODEOWNERS: activated")
- const outputChannel = vscode.window.createOutputChannel("Github Code Owners")
+ const outputChannel = vscode.window.createOutputChannel(
+ "Github Code Owners",
+ {
+ log: true,
+ },
+ )
+ // Diagnostics, hovers, file counts and owners come from gh-codeowners'
+ // language server, when this platform has it.
+ const server = await CodeownersLanguageServer.start(context, outputChannel)
+ const getServer = () => server
const CODEOWNERS_SELECTOR: vscode.DocumentSelector = {
language: "codeowners",
@@ -37,7 +48,7 @@ export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand(
COMMAND_ID,
- showOwnersCommandHandler(outputChannel),
+ showOwnersCommandHandler(outputChannel, getServer),
),
)
@@ -55,12 +66,15 @@ export function activate(context: vscode.ExtensionContext) {
"/",
),
)
- context.subscriptions.push(
- vscode.languages.registerHoverProvider(
- CODEOWNERS_SELECTOR,
- new CodeownersHoverProvider(),
- ),
- )
+ if (server == null) {
+ context.subscriptions.push(
+ vscode.languages.registerHoverProvider(
+ CODEOWNERS_SELECTOR,
+ new CodeownersHoverProvider(),
+ ),
+ )
+ registerCodeownersDiagnostics(context)
+ }
const statusBarItem = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Right,
@@ -69,13 +83,32 @@ export function activate(context: vscode.ExtensionContext) {
statusBarItem.command = COMMAND_ID
context.subscriptions.push(statusBarItem)
+ const updateStatusBar = statusBarTextEditorListener(
+ statusBarItem,
+ outputChannel,
+ getServer,
+ )
context.subscriptions.push(
- vscode.window.onDidChangeActiveTextEditor(
- statusBarTextEditorListener(statusBarItem, outputChannel),
- ),
+ vscode.window.onDidChangeActiveTextEditor(updateStatusBar),
)
+ void updateStatusBar()
- registerCodeownersDiagnostics(context)
+ // The built-in features replace the server's only at activation.
+ context.subscriptions.push(
+ vscode.workspace.onDidChangeConfiguration(async (e) => {
+ if (!e.affectsConfiguration(LANGUAGE_SERVER)) {
+ return
+ }
+ const reload = "Reload Window"
+ const choice = await vscode.window.showInformationMessage(
+ "Reload the window to apply the GitHub Code Owners language server setting.",
+ reload,
+ )
+ if (choice === reload) {
+ await vscode.commands.executeCommand("workbench.action.reloadWindow")
+ }
+ }),
+ )
vscode.workspace.onDidChangeConfiguration(() => {
outputChannel.appendLine("Configuration changed: Reloading link provider")
diff --git a/src/language-server.ts b/src/language-server.ts
new file mode 100644
index 0000000..29964aa
--- /dev/null
+++ b/src/language-server.ts
@@ -0,0 +1,138 @@
+import fs from "fs"
+import vscode from "vscode"
+import {
+ InlayHintRequest,
+ LanguageClient,
+ TransportKind,
+ type LanguageClientOptions,
+ type ServerOptions,
+} from "vscode-languageclient/node"
+
+import {
+ FILE_COUNTS_ENABLED,
+ getLanguageServerPath,
+ isFileCountsEnabled,
+ isLanguageServerEnabled,
+} from "./configuration"
+
+/** The rule that owns a file, from the `gh-codeowners/owner` request. */
+type OwnerResult = {
+ path: string
+ codeowners: string
+ rule: {
+ range: {
+ start: { line: number; character: number }
+ end: { line: number; character: number }
+ }
+ pattern: string
+ owners: string[]
+ } | null
+}
+
+export type Owner = {
+ codeowners: vscode.Uri
+ rule: { range: vscode.Range; owners: string[] } | null
+}
+
+/**
+ * The gh-codeowners binary: the one in the settings, or the one bundled with
+ * this platform's build of the extension.
+ */
+function serverPath(context: vscode.ExtensionContext): string | null {
+ const configured = getLanguageServerPath()
+ if (configured) {
+ return configured
+ }
+ const exe = process.platform === "win32" ? ".exe" : ""
+ const bundled = context.asAbsolutePath(`bin/gh-codeowners${exe}`)
+ return fs.existsSync(bundled) ? bundled : null
+}
+
+export class CodeownersLanguageServer {
+ private constructor(private readonly client: LanguageClient) {}
+
+ /**
+ * Start gh-codeowners' language server, or return null if it's disabled
+ * or there's no binary for this platform.
+ */
+ static async start(
+ context: vscode.ExtensionContext,
+ outputChannel: vscode.LogOutputChannel,
+ ): Promise {
+ if (!isLanguageServerEnabled()) {
+ outputChannel.appendLine(
+ "The language server is disabled: using the built-in features",
+ )
+ return null
+ }
+ const command = serverPath(context)
+ if (command == null) {
+ outputChannel.appendLine(
+ "No gh-codeowners binary for this platform: using the built-in features",
+ )
+ return null
+ }
+ const serverOptions: ServerOptions = {
+ command,
+ args: ["lsp"],
+ transport: TransportKind.stdio,
+ }
+ const clientOptions: LanguageClientOptions = {
+ documentSelector: [
+ { language: "codeowners", scheme: "file" },
+ { language: "codeowners", scheme: "untitled" },
+ ],
+ outputChannel,
+ middleware: {
+ provideInlayHints: (document, viewPort, token, next) =>
+ isFileCountsEnabled() ? next(document, viewPort, token) : [],
+ },
+ }
+ const client = new LanguageClient(
+ "githubCodeOwners",
+ "GitHub Code Owners",
+ serverOptions,
+ clientOptions,
+ )
+ try {
+ await client.start()
+ } catch (e) {
+ outputChannel.appendLine(
+ `Couldn't start ${command}: ${e}. Using the built-in features.`,
+ )
+ return null
+ }
+ context.subscriptions.push(
+ client,
+ vscode.workspace.onDidChangeConfiguration((e) => {
+ if (!e.affectsConfiguration(FILE_COUNTS_ENABLED)) {
+ return
+ }
+ const feature = client.getFeature(InlayHintRequest.method)
+ for (const document of vscode.workspace.textDocuments) {
+ feature.getProvider(document)?.onDidChangeInlayHints.fire()
+ }
+ }),
+ )
+ return new CodeownersLanguageServer(client)
+ }
+
+ /** The rule that owns `uri`, or null outside a repository with CODEOWNERS. */
+ async owner(uri: vscode.Uri): Promise {
+ const result = await this.client.sendRequest(
+ "gh-codeowners/owner",
+ { uri: this.client.code2ProtocolConverter.asUri(uri) },
+ )
+ if (result == null) {
+ return null
+ }
+ const p2c = this.client.protocol2CodeConverter
+ return {
+ codeowners: p2c.asUri(result.codeowners),
+ rule: result.rule && {
+ range: p2c.asRange(result.rule.range),
+ owners: result.rule.owners,
+ },
+ }
+ }
+}
diff --git a/src/show-owners-command.ts b/src/show-owners-command.ts
index ad848ff..224740e 100644
--- a/src/show-owners-command.ts
+++ b/src/show-owners-command.ts
@@ -2,10 +2,17 @@ import vscode from "vscode"
import path from "path"
import { OwnershipEngine } from "@snyk/github-codeowners/dist/lib/ownership"
+import type { CodeownersLanguageServer } from "./language-server"
+
+export type Ownership = {
+ codeowners: vscode.Uri
+ /** The owning rule, or null if no rule owns the file. */
+ rule: { range: vscode.Range; owners: string[] } | null
+}
async function fileExists(path: string): Promise {
try {
- await vscode.workspace.fs.stat(vscode.Uri.parse(path))
+ await vscode.workspace.fs.stat(vscode.Uri.file(path))
return true
} catch (e: unknown) {
// @ts-expect-error we should see this error.
@@ -29,23 +36,12 @@ async function findCodeOwnersFile(
return null
}
-export async function getOwnership(
+/** Find the owner without the language server. */
+async function getBuiltInOwnership(
+ document: vscode.TextDocument,
outputChannel: vscode.OutputChannel,
-): Promise<
- | {
- kind: "match"
- owners: string[]
- lineno: number
- filePath: string
- }
- | { kind: "no-match"; filePath: string; owners: []; lineno: 0 }
- | null
-> {
- if (!vscode.window.activeTextEditor) {
- return null
- }
-
- const { fileName, uri } = vscode.window.activeTextEditor.document
+): Promise {
+ const { fileName, uri } = document
const workspaceFolder = vscode.workspace.getWorkspaceFolder(uri)
@@ -70,45 +66,60 @@ export async function getOwnership(
const codeOwners = OwnershipEngine.FromCodeownersFile(codeownersFilePath)
const res = codeOwners.calcFileOwnership(file)
+ const codeowners = vscode.Uri.file(codeownersFilePath)
if (res == null) {
outputChannel.appendLine(`No owners for file: ${file}`)
- return {
- kind: "no-match",
- filePath: codeownersFilePath,
- owners: [],
- lineno: 0,
- }
+ return { codeowners, rule: null }
}
- outputChannel.appendLine(`Found code owners for file: ${workspacePath}`)
-
+ const codeownersDocument = await vscode.workspace.openTextDocument(codeowners)
return {
- ...res,
- kind: "match",
- owners: res.owners.map((x) => x.replace(/^@/, "")),
- filePath: codeownersFilePath,
+ codeowners,
+ rule: {
+ range: codeownersDocument.lineAt(res.lineno).range,
+ owners: res.owners,
+ },
}
}
-export function showOwnersCommandHandler(outputChannel: vscode.OutputChannel) {
+export async function getOwnership(
+ outputChannel: vscode.OutputChannel,
+ server: CodeownersLanguageServer | null,
+): Promise {
+ const document = vscode.window.activeTextEditor?.document
+ if (document == null) {
+ return null
+ }
+ if (server == null) {
+ return getBuiltInOwnership(document, outputChannel)
+ }
+ if (document.uri.scheme !== "file") {
+ return null
+ }
+ try {
+ return await server.owner(document.uri)
+ } catch (e) {
+ outputChannel.appendLine(`Could not find owners of ${document.uri}: ${e}`)
+ return null
+ }
+}
+
+export function showOwnersCommandHandler(
+ outputChannel: vscode.OutputChannel,
+ getServer: () => CodeownersLanguageServer | null,
+) {
return async () => {
- const ownership = await getOwnership(outputChannel)
+ const ownership = await getOwnership(outputChannel, getServer())
if (ownership == null) {
return
}
- const doc = await vscode.workspace.openTextDocument(ownership.filePath)
- if (ownership.kind === "match") {
+ const doc = await vscode.workspace.openTextDocument(ownership.codeowners)
+ if (ownership.rule != null) {
+ const { range } = ownership.rule
const textEditor = await vscode.window.showTextDocument(doc)
- const line = doc.lineAt(ownership.lineno)
-
- // select the line.
- textEditor.selection = new vscode.Selection(
- line.range.start,
- line.range.end,
- )
- // scroll the line into focus.
- textEditor.revealRange(line.range, vscode.TextEditorRevealType.InCenter)
+ textEditor.selection = new vscode.Selection(range.start, range.end)
+ textEditor.revealRange(range, vscode.TextEditorRevealType.InCenter)
}
}
}
diff --git a/src/status-bar-text-editor-listener.ts b/src/status-bar-text-editor-listener.ts
index 869a2bb..e75a3d9 100644
--- a/src/status-bar-text-editor-listener.ts
+++ b/src/status-bar-text-editor-listener.ts
@@ -1,5 +1,6 @@
import vscode from "vscode"
-import { getOwnership } from "./show-owners-command"
+import { getOwnership, type Ownership } from "./show-owners-command"
+import type { CodeownersLanguageServer } from "./language-server"
function formatNames(owners: string[]): string {
if (owners.length > 2) {
@@ -13,16 +14,11 @@ function formatNames(owners: string[]): string {
}
}
-function formatToolTip({
- owners,
- lineno,
-}: {
- owners: string[]
- lineno: number
-}): string {
- if (owners.length === 0) {
+function formatToolTip({ rule }: Ownership, owners: string[]): string {
+ if (rule == null || owners.length === 0) {
return "No Owners"
}
+ const lineno = rule.range.start.line + 1
if (owners.length <= 2) {
return `Owned by ${owners.join(" and ")}\n(from CODEOWNERS line ${lineno})`
@@ -36,18 +32,20 @@ function formatToolTip({
export function statusBarTextEditorListener(
statusBarItem: vscode.StatusBarItem,
outputChannel: vscode.OutputChannel,
+ getServer: () => CodeownersLanguageServer | null,
) {
return async () => {
- const res = await getOwnership(outputChannel)
+ const res = await getOwnership(outputChannel, getServer())
if (!res) {
statusBarItem.hide()
return
}
- statusBarItem.text = `$(shield) ${formatNames(res.owners)}`
+ const owners = (res.rule?.owners ?? []).map((x) => x.replace(/^@/, ""))
+ statusBarItem.text = `$(shield) ${formatNames(owners)}`
- statusBarItem.tooltip = formatToolTip(res)
+ statusBarItem.tooltip = formatToolTip(res, owners)
statusBarItem.show()
}
}
diff --git a/test/suite/language-server.test.ts b/test/suite/language-server.test.ts
new file mode 100644
index 0000000..0ee2af0
--- /dev/null
+++ b/test/suite/language-server.test.ts
@@ -0,0 +1,137 @@
+import assert from "assert"
+import { execFileSync } from "child_process"
+import fs from "fs"
+import os from "os"
+import path from "path"
+import vscode from "vscode"
+
+const repoRoot = path.resolve(__dirname, "../../..")
+const exe = process.platform === "win32" ? ".exe" : ""
+const bundled = path.join(repoRoot, "bin", `gh-codeowners${exe}`)
+
+async function waitFor(
+ get: () => T | Thenable,
+ done: (value: T) => boolean,
+): Promise {
+ const deadline = Date.now() + 10000
+ for (;;) {
+ const value = await get()
+ if (done(value) || Date.now() > deadline) {
+ return value
+ }
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ }
+}
+
+suite("language server", function () {
+ // `s/download-server ` puts a binary in bin/.
+ if (!fs.existsSync(bundled)) {
+ return
+ }
+
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "codeowners-test-"))
+ fs.mkdirSync(path.join(dir, "src"))
+ fs.writeFileSync(path.join(dir, "src", "a.ts"), "")
+ fs.writeFileSync(path.join(dir, "src", "b.ts"), "")
+ fs.writeFileSync(
+ path.join(dir, "CODEOWNERS"),
+ "/src/ @acme/web\n/docs/ @acme/docs\n/app/[id]/ @acme/web\n",
+ )
+ execFileSync("git", ["init", "-q"], { cwd: dir })
+ execFileSync("git", ["add", "."], { cwd: dir })
+ const codeowners = vscode.Uri.file(path.join(dir, "CODEOWNERS"))
+ const owned = vscode.Uri.file(path.join(dir, "src", "a.ts"))
+
+ test("marks broken and unused rules", async () => {
+ const document = await vscode.workspace.openTextDocument(codeowners)
+ await vscode.window.showTextDocument(document)
+ const diagnostics = await waitFor(
+ () => vscode.languages.getDiagnostics(codeowners),
+ (d) => d.length >= 2,
+ )
+ const broken = diagnostics.find(
+ (d) => d.severity === vscode.DiagnosticSeverity.Error,
+ )
+ assert.strictEqual(broken?.range.start.line, 2)
+ const unused = diagnostics.find((d) =>
+ d.tags?.includes(vscode.DiagnosticTag.Unnecessary),
+ )
+ assert.strictEqual(unused?.range.start.line, 1)
+ })
+
+ test("shows each rule's file count", async () => {
+ const document = await vscode.workspace.openTextDocument(codeowners)
+ const hints = await waitFor(
+ () =>
+ vscode.commands.executeCommand(
+ "vscode.executeInlayHintProvider",
+ codeowners,
+ new vscode.Range(0, 0, document.lineCount, 0),
+ ),
+ (h) => h.length > 0,
+ )
+ assert.deepStrictEqual(
+ hints.map((h) => [h.position.line, h.label]),
+ [
+ [0, "2 files"],
+ [1, "0 files"],
+ [2, "0 files"],
+ ],
+ )
+ })
+
+ test("offers to escape brackets", async () => {
+ const actions = await waitFor(
+ () =>
+ vscode.commands.executeCommand(
+ "vscode.executeCodeActionProvider",
+ codeowners,
+ new vscode.Range(2, 1, 2, 1),
+ vscode.CodeActionKind.QuickFix.value,
+ ),
+ (a) => a.length > 0,
+ )
+ // VS Code adds its own AI actions, which have no edit.
+ const fixes = actions.filter((a) => a.edit != null)
+ assert.deepStrictEqual(
+ fixes.map((a) => a.title),
+ ["Replace with `/app/\\[id\\]/`"],
+ )
+ const [edit] = fixes[0].edit?.get(codeowners) ?? []
+ assert.strictEqual(edit?.newText, "/app/\\[id\\]/")
+ })
+
+ test("hides file counts when they're disabled", async () => {
+ const config = vscode.workspace.getConfiguration("githubCodeOwners")
+ await config.update(
+ "fileCounts.enabled",
+ false,
+ vscode.ConfigurationTarget.Global,
+ )
+ try {
+ const hints = await vscode.commands.executeCommand(
+ "vscode.executeInlayHintProvider",
+ codeowners,
+ new vscode.Range(0, 0, 3, 0),
+ )
+ assert.deepStrictEqual(hints, [])
+ } finally {
+ await config.update(
+ "fileCounts.enabled",
+ undefined,
+ vscode.ConfigurationTarget.Global,
+ )
+ }
+ })
+
+ test("opens the rule that owns a file", async () => {
+ await vscode.window.showTextDocument(owned)
+ await vscode.commands.executeCommand("github-code-owners.show-owners")
+ const editor = vscode.window.activeTextEditor
+ assert.strictEqual(editor?.document.uri.fsPath, codeowners.fsPath)
+ assert.deepStrictEqual(
+ editor.selection,
+ new vscode.Selection(0, 0, 0, "/src/".length),
+ )
+ })
+})
diff --git a/tsconfig.json b/tsconfig.json
index e3f0e95..1001877 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,6 +1,7 @@
{
"compilerOptions": {
- "module": "commonjs",
+ "module": "node16",
+ "moduleResolution": "node16",
"target": "es6",
"outDir": "out",
"lib": ["es6"],