Skip to content
Draft
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- Describe patterns correctly when hovering, following GitHub's matching rules. Lines GitHub skips or never matches now say so.

## 4.3.0 - 2026-11-04

### Changed
Expand Down
169 changes: 130 additions & 39 deletions src/codeowners-hover-provider.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,144 @@
import vscode from "vscode"
import { dirname } from "path"
import fs from "fs"

/**
* The pattern on a CODEOWNERS line, ending at the first unescaped whitespace
* or `#`. Null for blank lines and comments.
*/
export function parsePattern(
line: string,
): { pattern: string; start: number } | null {
const start = line.search(/\S/)
if (start === -1) {
return null
}
let end = start
while (end < line.length && !/[\s#]/.test(line.charAt(end))) {
end += line.charAt(end) === "\\" ? 2 : 1
}
end = Math.min(end, line.length)
return end === start ? null : { pattern: line.slice(start, end), start }
}

function invalidReason(pattern: string): string | null {
const escapes = pattern.match(/\\./g) ?? []
if (escapes.some((escape) => !" \t#[]\\".includes(escape.charAt(1)))) {
return "A `\\` can only escape a space, a tab, `#`, `[`, `]` or `\\`."
}
if (/[[\]]/.test(pattern.replace(/\\./g, ""))) {
return "`[` and `]` must be escaped as `\\[` and `\\]`."
}
if (pattern.includes("***")) {
return "A pattern can't have three or more `*`s in a row."
}
return null
}

function neverMatchesReason(pattern: string): string | null {
if (/^\/*$/.test(dropTrailingEscape(pattern))) {
return "The pattern has no path to match."
}
const escapes = pattern.match(/\\./g) ?? []
const opening = escapes.filter((escape) => escape === "\\[").length
const closing = escapes.filter((escape) => escape === "\\]").length
if (opening !== closing) {
return "It has a different number of `\\[`s and `\\]`s."
}
if (pattern.split("/").some((part) => part === "." || part === "..")) {
return "Paths in git never have `.` or `..` segments."
}
if (pattern.startsWith("\\[") && !pattern.includes("/")) {
return "It starts with `\\[` and has no slash. Start it with `**/` instead."
}
return null
}

/** Drops a `\` at the end of a pattern, which escapes nothing. */
function dropTrailingEscape(pattern: string): string {
return pattern.replace(/\\.?/g, (m) => (m === "\\" ? "" : m))
}

function describePath(path: string): string {
const anchored = path.replace(/\/$/, "").includes("/")
const relative = path.replace(/^\//, "")
// `/**` and `/**/` at the end both mean everything in the directory.
const body = relative
.replace(/^(\*\*\/)+/, "")
.replace(/(^|\/)\*\*\/?$/, "$1")
const anyDepth = !anchored || relative.startsWith("**/")

if (body === "" || (body === "*" && anyDepth)) {
return "Matches every file."
}
if (body === "*") {
return "Matches files at the root of the repository, but not in subdirectories."
}

const where = anyDepth ? "at any depth" : "starting at the repository root"
const noun = (name: string) =>
anyDepth && !name.replace(/\/$/, "").includes("/") ? "name" : "path"

if (body.endsWith("/*")) {
const directory = body.slice(0, -"/*".length)
return `Matches files directly in directories with this ${noun(
directory,
)} ${where}, but not in their subdirectories.`
}
if (body.endsWith("/")) {
return `Matches everything in directories with this ${noun(body)} ${where}.`
}
return `Matches files and directories with this ${noun(
body,
)} ${where}, including everything in those directories.`
}

/** What a pattern matches on GitHub, following gh-codeowners' SPECIFICATION.md. */
export function describePattern(pattern: string): string {
const invalid = invalidReason(pattern)
if (invalid != null) {
return `Invalid: GitHub skips this line. ${invalid}`
}
// `!` is an ordinary character in a pattern with a slash.
const negated = pattern.startsWith("!") && !pattern.includes("/")
const name = negated ? pattern.slice(1) : pattern
const neverMatches = neverMatchesReason(name)
if (neverMatches != null) {
return `Never matches: GitHub accepts this line, but it owns nothing. ${neverMatches}`
}

const path = dropTrailingEscape(name)
const notes = [negated ? describeNegated(path) : describePath(path)]
if (path.replace(/\\./g, "").includes("?")) {
notes.push("`?` matches one byte of the UTF-8 path, not one character.")
}
return notes.join(" ")
}

function describeNegated(name: string): string {
const matches = /^\*+$/.test(name)
? "Matches every file."
: "Matches files with this name at any depth, but not directories."
return `${matches} \`!\` doesn't negate on GitHub.`
}

export class CodeownersHoverProvider implements vscode.HoverProvider {
provideHover(
document: vscode.TextDocument,
position: vscode.Position,
): vscode.ProviderResult<vscode.Hover> {
const line = document.lineAt(position.line)
const m = line.text.match(/^\s*(\S+)/)?.[1]
if (m == null) {
return { contents: [] }
const parsed = parsePattern(document.lineAt(position.line).text)
if (parsed == null) {
return null
}
const idx = line.text.indexOf(m)

const workspaceDir = dirname(dirname(document.uri.fsPath))
const myPath = workspaceDir + "/" + m

let isDirectory: boolean | null = null
try {
isDirectory = fs.statSync(myPath).isDirectory()
} catch (e) {
// @ts-expect-error we should see this error.
if (e.code !== "ENOENT") {
console.error("github-code-owners", e)
}
}
const x = new vscode.MarkdownString()
x.appendCodeblock(m)

const isPattern = !m.startsWith("/")

const { pattern, start } = parsed
const range = new vscode.Range(
new vscode.Position(position.line, idx),
new vscode.Position(position.line, idx + m.length),
new vscode.Position(position.line, start),
new vscode.Position(position.line, start + pattern.length),
)
if (!range.contains(position)) {
return { contents: [] }
}
return {
range,
contents: [
x,
isPattern
? "Matches all files with same name"
: isDirectory
? `Matches all files in directory and subdirectories`
: `Matches path exactly`,
],
return null
}
const code = new vscode.MarkdownString()
code.appendCodeblock(pattern)
return { range, contents: [code, describePattern(pattern)] }
}
}
162 changes: 162 additions & 0 deletions test/suite/codeowners-hover-provider.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import assert from "assert"
import vscode from "vscode"
import {
CodeownersHoverProvider,
describePattern,
parsePattern,
} from "../../src/codeowners-hover-provider"

const EVERY_FILE = "Matches every file."
const NAME_ANY_DEPTH =
"Matches files and directories with this name at any depth, including everything in those directories."
const PATH_ANY_DEPTH =
"Matches files and directories with this path at any depth, including everything in those directories."
const PATH_FROM_ROOT =
"Matches files and directories with this path starting at the repository root, including everything in those directories."
const DIRECTORY_NAME_ANY_DEPTH =
"Matches everything in directories with this name at any depth."
const DIRECTORY_FROM_ROOT =
"Matches everything in directories with this path starting at the repository root."
const NO_SUBDIRECTORIES_FROM_ROOT =
"Matches files directly in directories with this path starting at the repository root, but not in their subdirectories."
const NEGATED_NAME =
"Matches files with this name at any depth, but not directories. `!` doesn't negate on GitHub."

suite("describePattern", () => {
const cases: [string, string][] = [
["*", EVERY_FILE],
["**", EVERY_FILE],
["**/", EVERY_FILE],
["/**", EVERY_FILE],
["/**/", EVERY_FILE],
["**/*", EVERY_FILE],
[
"/*",
"Matches files at the root of the repository, but not in subdirectories.",
],
["foo", NAME_ANY_DEPTH],
["*.js", NAME_ANY_DEPTH],
["**/logs", NAME_ANY_DEPTH],
["My\\ Docs", NAME_ANY_DEPTH],
["**/a/b", PATH_ANY_DEPTH],
["/foo", PATH_FROM_ROOT],
["a/b", PATH_FROM_ROOT],
["/src/*.js", PATH_FROM_ROOT],
["a/**/b", PATH_FROM_ROOT],
["foo/", DIRECTORY_NAME_ANY_DEPTH],
["*/", DIRECTORY_NAME_ANY_DEPTH],
["**/logs/", DIRECTORY_NAME_ANY_DEPTH],
["**/foo/**", DIRECTORY_NAME_ANY_DEPTH],
["/foo/", DIRECTORY_FROM_ROOT],
["a/b/", DIRECTORY_FROM_ROOT],
["docs/**", DIRECTORY_FROM_ROOT],
["docs/**/", DIRECTORY_FROM_ROOT],
["docs/*/", DIRECTORY_FROM_ROOT],
["docs/*", NO_SUBDIRECTORIES_FROM_ROOT],
["/docs/*", NO_SUBDIRECTORIES_FROM_ROOT],
[
"**/foo/*",
"Matches files directly in directories with this name at any depth, but not in their subdirectories.",
],
// `!` without a slash matches file names, and with one it's ordinary.
["!foo", NEGATED_NAME],
["!*.js", NEGATED_NAME],
["!*", `${EVERY_FILE} \`!\` doesn't negate on GitHub.`],
["!a/", DIRECTORY_NAME_ANY_DEPTH],
["!a/b", PATH_FROM_ROOT],
// A trailing `\` is dropped.
["a\\", NAME_ANY_DEPTH],
["/a\\", PATH_FROM_ROOT],
[
"?.txt",
`${NAME_ANY_DEPTH} \`?\` matches one byte of the UTF-8 path, not one character.`,
],
]
for (const [pattern, description] of cases) {
test(pattern, () => {
assert.strictEqual(describePattern(pattern), description)
})
}

const invalid = ["/tmp/***", "/app/[id]/", "\\*.bak", "a]"]
for (const pattern of invalid) {
test(`${pattern} is invalid`, () => {
assert.match(describePattern(pattern), /^Invalid: GitHub skips this line/)
})
}

const neverMatch = [
"/",
"//",
"!",
"./src/",
"a/../b",
"notes\\[1",
"\\[draft\\]*",
"!\\[draft\\]",
]
for (const pattern of neverMatch) {
test(`${pattern} never matches`, () => {
assert.match(describePattern(pattern), /^Never matches:/)
})
}

test("escaped brackets that pair up are valid", () => {
assert.strictEqual(describePattern("/app/\\[id\\]/"), DIRECTORY_FROM_ROOT)
assert.strictEqual(describePattern("**/\\[draft\\]*"), NAME_ANY_DEPTH)
})
})

suite("parsePattern", () => {
test("finds the pattern and where it starts", () => {
assert.deepStrictEqual(parsePattern(" /docs/ @acme/docs"), {
pattern: "/docs/",
start: 2,
})
})

test("keeps escaped spaces and `#`s", () => {
assert.strictEqual(parsePattern("My\\ Docs/ @a")?.pattern, "My\\ Docs/")
assert.strictEqual(parsePattern("/src/C\\#/ @a")?.pattern, "/src/C\\#/")
})

test("ends the pattern at an unescaped `#`", () => {
assert.strictEqual(parsePattern("/src/C#/ @a")?.pattern, "/src/C")
})

test("keeps a trailing `\\`", () => {
assert.strictEqual(parsePattern("a\\")?.pattern, "a\\")
})

test("finds nothing on blank lines and comments", () => {
assert.strictEqual(parsePattern(""), null)
assert.strictEqual(parsePattern(" "), null)
assert.strictEqual(parsePattern("# /docs/ @acme/docs"), null)
assert.strictEqual(parsePattern(" #/docs/"), null)
})
})

suite("CodeownersHoverProvider", () => {
async function hover(content: string, line: number, character: number) {
const document = await vscode.workspace.openTextDocument({ content })
return new CodeownersHoverProvider().provideHover(
document,
new vscode.Position(line, character),
)
}

test("describes the pattern under the cursor", async () => {
const result = await hover(" docs/* @acme/docs", 0, 3)
assert.strictEqual(result?.contents[1], NO_SUBDIRECTORIES_FROM_ROOT)
assert.deepStrictEqual(result?.range, new vscode.Range(0, 2, 0, 8))
})

test("shows nothing past the pattern", async () => {
assert.strictEqual(await hover("/docs/ @acme/docs", 0, 10), null)
assert.strictEqual(await hover("/src/C#/ @acme/docs", 0, 7), null)
})

test("shows nothing on comments", async () => {
assert.strictEqual(await hover("# /docs/ @acme/docs", 0, 3), null)
})
})
Loading