diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d4d1d3..8ff3a1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## 5.1.0 - 2026-11-08 + +### Changed + +- Format CODEOWNERS with the gh-codeowners language server. Formatting behavior has changed (#43). + +### Deprecated + +- Unused settings are marked as deprecated: `githubCodeOwners.format.enabled` and `githubCodeOwners.format.alignmentOffset` (#43). + ## 5.0.0 - 2026-11-07 ### Changed diff --git a/README.md b/README.md index 3af09ac..6dbc697 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ 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. +The extension uses [gh-codeowners](https://github.com/chdsbd/gh-codeowners) to count file matches, warn about unused or malformed rules, and format CODEOWNERS. #### Counts for matching rules @@ -36,9 +36,9 @@ The extension uses [gh-codeowners](https://github.com/chdsbd/gh-codeowners) to c #### Link usernames to Slack -click to open username in GitHub +click to open username in Slack -> Define a Slack mapping in your VSCode settings (`github-code-owners.team-mapping.slack`) to enable this feature. +> Define a Slack mapping in your VSCode settings (`githubCodeOwners.teamMapping.slack`) to enable this feature. #### Auto complete @@ -52,9 +52,9 @@ Escapes, wildcards, comments and owners are highlighted the way GitHub reads the #### Formatting -> Enable formatting by setting `github-code-owners.format.enabled` to `true`. +Format Document lines up owners and trailing comments in each section. -auto complete of paths and usernames +owners lined up in each section of a CODEOWNERS file ### Command @@ -78,7 +78,7 @@ Download the extension package from the [latest Github release](https://github.c ### From source -Clone [this repo](https://github.com/chdsbd/vscode-github-code-owners) and run `npm ci` and `npm run package`. Install the resulting package with `code --install-extension github-code-owners-*.vsix` +Clone [this repo](https://github.com/chdsbd/vscode-github-code-owners) and run `npm ci`, `s/download-server darwin-arm64` (or your platform) to bundle the language server, and `npm run package`. Install the resulting package with `code --install-extension github-code-owners-*.vsix` ## Related extensions @@ -90,4 +90,4 @@ Clone [this repo](https://github.com/chdsbd/vscode-github-code-owners) and run ` ## Fork -This repository is forked from [jasonnutter/vscode-codeowners](https://github.com/jasonnutter/vscode-codeowners), with UI changes and more correct CODEOWNERS compliance via [@snyk/github-codeowners](https://www.npmjs.com/package/@snyk/github-codeowners). +This repository is forked from [jasonnutter/vscode-codeowners](https://github.com/jasonnutter/vscode-codeowners), with UI changes and more correct CODEOWNERS compliance via [gh-codeowners](https://github.com/chdsbd/gh-codeowners). diff --git a/images/formatting.gif b/images/formatting.gif deleted file mode 100644 index 7fdbf98..0000000 Binary files a/images/formatting.gif and /dev/null differ diff --git a/images/formatting.png b/images/formatting.png new file mode 100644 index 0000000..d02e4ad Binary files /dev/null and b/images/formatting.png differ diff --git a/package-lock.json b/package-lock.json index 36fa89b..49d0187 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "github-code-owners", - "version": "5.0.0", + "version": "5.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "github-code-owners", - "version": "5.0.0", + "version": "5.1.0", "license": "SEE LICENSE IN LICENSE", "dependencies": { "@snyk/github-codeowners": "github:chdsbd/github-codeowners#bb24c2adb022a88e03f25a3680a23934a281a5c3", diff --git a/package.json b/package.json index a56274b..439f5f2 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": "5.0.0", + "version": "5.1.0", "icon": "images/logo256.png", "homepage": "https://github.com/chdsbd/vscode-github-code-owners/blob/master/README.md", "keywords": [ @@ -67,14 +67,18 @@ "type": "boolean", "default": false, "order": 1, - "description": "Whether or not to enable formatting." + "description": "Whether or not to enable formatting.", + "markdownDeprecationMessage": "**Deprecated**: Formatting is always available from the language server. Use `Format Document` or `#editor.formatOnSave#`.", + "deprecationMessage": "Deprecated: Formatting is always available from the language server. Use Format Document or editor.formatOnSave." }, "githubCodeOwners.format.alignmentOffset": { "type": "number", "default": 4, "minimum": 1, "order": 2, - "description": "Space offset to use from the longest file pattern the first code owner when aligning." + "description": "Space offset to use from the longest file pattern the first code owner when aligning.", + "markdownDeprecationMessage": "**Deprecated**: The language server lines up owners one space after the longest pattern in each section.", + "deprecationMessage": "Deprecated: The language server lines up owners one space after the longest pattern in each section." }, "githubCodeOwners.fileCounts.enabled": { "order": 6, @@ -152,15 +156,15 @@ } }, "github-code-owners.format.enabled": { - "markdownDeprecationMessage": "**Deprecated**: Please use `#githubCodeOwners.format.enabled#` instead.", - "deprecationMessage": "Deprecated: Please use githubCodeOwners.format.enabled instead.", + "markdownDeprecationMessage": "**Deprecated**: Formatting is always available from the language server. Use `Format Document` or `#editor.formatOnSave#`.", + "deprecationMessage": "Deprecated: Formatting is always available from the language server. Use Format Document or editor.formatOnSave.", "type": "boolean", "default": false, "description": "Whether or not to enable formatting." }, "github-code-owners.format.alignment-offset": { - "markdownDeprecationMessage": "**Deprecated**: Please use `#githubCodeOwners.format.alignmentOffset#` instead.", - "deprecationMessage": "Deprecated: Please use githubCodeOwners.format.alignmentOffset instead.", + "markdownDeprecationMessage": "**Deprecated**: The language server lines up owners one space after the longest pattern in each section.", + "deprecationMessage": "Deprecated: The language server lines up owners one space after the longest pattern in each section.", "type": "number", "default": 4, "minimum": 1, diff --git a/s/download-server b/s/download-server index 7b0eab0..5f77adf 100755 --- a/s/download-server +++ b/s/download-server @@ -5,7 +5,7 @@ # darwin-arm64, into bin/, where the extension looks for its language server. set -euo pipefail -GH_CODEOWNERS_VERSION=v0.2.0 +GH_CODEOWNERS_VERSION=v0.3.0 target=$1 case "$target" in diff --git a/src/align-codeowners.ts b/src/align-codeowners.ts deleted file mode 100644 index cfd594c..0000000 --- a/src/align-codeowners.ts +++ /dev/null @@ -1,133 +0,0 @@ -import vscode from "vscode" -import trimStart from "lodash/trimStart" -import trimEnd from "lodash/trimEnd" -import trim from "lodash/trim" -import range from "lodash/range" -import { getAlignmentOffset, isFormatEnabled } from "./configuration" - -interface LineToAlign { - lineNum: number - ownersStartIndex: number - filePatternLength: number -} -/** - * Determines whether the line is a comment or empty - * @param lineText - Text of a given line - * @returns true if comment or empty line - */ -function isCommentOrEmptyLine(lineText: string): boolean { - return trimStart(lineText).indexOf("#") === 0 || trim(lineText).length === 0 -} - -/** - * Finds the sting index of the first owner in a line. - * @param lineText - Text of a given line. - * @returns Sting start index of the first owner. - */ -function findOwnerStartIndex(lineText: string): number { - return lineText.indexOf("@") -} -/** - * Finds the sting index of the file pattern length - * @param lineText - Text of a given line. - * @param Sting start index of the first owner. - * @returns Sting index of the file pattern length - */ -function findFilePatternLength( - lineText: string, - ownersStartIndex: number, -): number { - return trimEnd(lineText.substring(0, ownersStartIndex - 1)).length -} -/** - * Formats `lineText` given the `filePatternLength`, `lineOffSet` - * @typedef {Object} args - Argument collection object to make calls less error prawn. - * @param {string} args.lineText - Text of the line tp format. - * @param {string} args.filePatternLength - Sting index of the file pattern length. - * @param {string} args.perLineOffSet - Offset between the end of the file pattern and code owner. - * @param {string} args.ownersStartIndex - Sting start index of the first owner. - * @returns line: Formatted line - */ -function formatLine({ - lineText, - filePatternLength, - perLineOffSet, - ownersStartIndex, -}: { - lineText: string - filePatternLength: number - perLineOffSet: number - ownersStartIndex: number -}): string { - return ( - lineText.substring(0, filePatternLength) + - " ".repeat(perLineOffSet) + - lineText.substring(ownersStartIndex) - ) -} - -/** - * Provide Formatting using the ``tabSize`` the user provided. - */ -export class AlignOwnersFormattingProvider - implements vscode.DocumentFormattingEditProvider -{ - async provideDocumentFormattingEdits( - document: vscode.TextDocument, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - options: vscode.FormattingOptions, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - token: vscode.CancellationToken, - ): Promise { - // Early exit if formatting is disabled or set to a bad value - if (!isFormatEnabled()) { - return [] - } - const alignmentOffset = getAlignmentOffset() - - // Check that config value for `alinementOffset` is valid before breaking things - if (alignmentOffset < 1) { - throw Error( - `Expected number greater 1 for 'githubCodeOwners.format.alignmentOffset' but got ${alignmentOffset}!`, - ) - } - // Find the `maxFilePatternLength` and which lines to potentially edit - const editLines: LineToAlign[] = [] - let maxFilePatternLength = 0 - for (const lineNum of range(0, document.lineCount)) { - const { text } = document.lineAt(lineNum) - if (isCommentOrEmptyLine(text)) { - continue - } - const ownersStartIndex = findOwnerStartIndex(text) - const filePatternLength = findFilePatternLength(text, ownersStartIndex) - if (filePatternLength > maxFilePatternLength) { - maxFilePatternLength = filePatternLength - } - editLines.push({ lineNum, ownersStartIndex, filePatternLength }) - } - - // Issue the line replacement if needed - return editLines.reduce((acc: vscode.TextEdit[], editLine: LineToAlign) => { - const { lineNum, ownersStartIndex, filePatternLength } = editLine - // We need the + 1 because we want `alinementOffset` spaces to be between the end of the - // File pattern an before the first owner starts - const newOwnersStartIndex = maxFilePatternLength + alignmentOffset + 1 - const line = document.lineAt(lineNum) - if (ownersStartIndex !== newOwnersStartIndex) { - acc.push( - vscode.TextEdit.replace( - line.range, - formatLine({ - lineText: line.text, - filePatternLength, - perLineOffSet: newOwnersStartIndex - filePatternLength, - ownersStartIndex, - }), - ), - ) - } - return acc - }, []) - } -} diff --git a/src/configuration.ts b/src/configuration.ts index 6e9d5d6..f0e9e9f 100644 --- a/src/configuration.ts +++ b/src/configuration.ts @@ -17,38 +17,6 @@ export function getGitHubUrl(): string { return setting } -export function isFormatEnabled(): boolean { - const formatEnabled = vscode.workspace - .getConfiguration() - .get("githubCodeOwners.format.enabled") - if (typeof formatEnabled === "boolean") { - return formatEnabled - } - const formatEnabledDeprecated = vscode.workspace - .getConfiguration() - .get("github-code-owners.format.enabled") - if (typeof formatEnabledDeprecated === "boolean") { - return formatEnabledDeprecated - } - return false -} - -export function getAlignmentOffset(): number { - const alignmentOffset = vscode.workspace - .getConfiguration() - .get("githubCodeOwners.format.alignmentOffset") - if (typeof alignmentOffset === "number") { - return alignmentOffset - } - const alignmentOffsetDeprecated = vscode.workspace - .getConfiguration() - .get("github-code-owners.format.alignment-offset") - if (typeof alignmentOffsetDeprecated === "number") { - return alignmentOffsetDeprecated - } - return 4 -} - export type SlackMappingConfigurationItem = { domain: string channel: string diff --git a/src/extension.ts b/src/extension.ts index c12913e..1ef2101 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -6,7 +6,6 @@ import { OwnerNameCompletionItemProvider } from "./owner-name-completion-item-pr import { showOwnersCommandHandler } from "./show-owners-command" 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" @@ -23,7 +22,7 @@ export async function activate(context: vscode.ExtensionContext) { log: true, }, ) - // Diagnostics, hovers, file counts and owners come from gh-codeowners' + // Diagnostics, hovers, file counts, owners and formatting come from gh-codeowners' // language server, when this platform has it. const server = await CodeownersLanguageServer.start(context, outputChannel) const getServer = () => server @@ -40,11 +39,6 @@ export async function activate(context: vscode.ExtensionContext) { ), } - vscode.languages.registerDocumentFormattingEditProvider( - CODEOWNERS_SELECTOR, - new AlignOwnersFormattingProvider(), - ) - context.subscriptions.push( vscode.commands.registerCommand( COMMAND_ID, diff --git a/test/data/align-codeowners/expected-formatted-with-offset-4 b/test/data/align-codeowners/expected-formatted-with-offset-4 deleted file mode 100644 index 6a703a0..0000000 --- a/test/data/align-codeowners/expected-formatted-with-offset-4 +++ /dev/null @@ -1,9 +0,0 @@ -* @foo - /some-path @bar -another-path/but-loooooooooonger @baz - -# a comment - - # an indented comment -/docs/**/*.md @foo @bar -# /docs/**/*.rst @foo @bar diff --git a/test/data/align-codeowners/expected-formatted-with-offset-8 b/test/data/align-codeowners/expected-formatted-with-offset-8 deleted file mode 100644 index a9f360c..0000000 --- a/test/data/align-codeowners/expected-formatted-with-offset-8 +++ /dev/null @@ -1,9 +0,0 @@ -* @foo - /some-path @bar -another-path/but-loooooooooonger @baz - -# a comment - - # an indented comment -/docs/**/*.md @foo @bar -# /docs/**/*.rst @foo @bar diff --git a/test/data/align-codeowners/input-to-format b/test/data/align-codeowners/input-to-format deleted file mode 100644 index af770df..0000000 --- a/test/data/align-codeowners/input-to-format +++ /dev/null @@ -1,9 +0,0 @@ -* @foo - /some-path @bar -another-path/but-loooooooooonger @baz - -# a comment - - # an indented comment -/docs/**/*.md @foo @bar -# /docs/**/*.rst @foo @bar diff --git a/test/data/align-codeowners/should-never-change b/test/data/align-codeowners/should-never-change deleted file mode 100644 index 10bc699..0000000 --- a/test/data/align-codeowners/should-never-change +++ /dev/null @@ -1,3 +0,0 @@ -# This file should never change due to grammar - - # This is also true for indented comment and blank lines diff --git a/test/suite/align-codeowners.test.ts b/test/suite/align-codeowners.test.ts deleted file mode 100644 index 9666207..0000000 --- a/test/suite/align-codeowners.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -/* eslint-disable init-declarations */ -// That is how the tests are supposed to be written ¯\_(ツ)_/¯ -import vscode from "vscode" -import { AlignOwnersFormattingProvider } from "../../src/align-codeowners" -import assert from "assert" -import fs from "fs" -import { beforeEach, afterEach } from "mocha" - -import path from "path" - -const repoRoot = path.resolve(__dirname, "../../..") - -async function createMockDocument( - testFilePath: string, -): Promise { - const resolvedTestFilePath = path.join(repoRoot, testFilePath) - const mockDocument = await vscode.workspace.openTextDocument( - resolvedTestFilePath, - ) - if (mockDocument === undefined) { - throw Error(`Test file at path ${resolvedTestFilePath} was not found`) - } - return mockDocument -} - -suite("AlignOwnersFormattingProvider", () => { - vscode.window.showInformationMessage("Start formatting tests.") - let provider: AlignOwnersFormattingProvider - // Ignored anyway - let mockOptions: vscode.FormattingOptions - let mockToken: vscode.CancellationToken - const badOffSetValues = [-1, 0] as const - - beforeEach(() => { - provider = new AlignOwnersFormattingProvider() - // Ignored anyway - mockOptions = { insertSpaces: true, tabSize: 2 } - mockToken = { - isCancellationRequested: false, - // eslint-disable-next-line - onCancellationRequested: () => false as any, - } - }) - - afterEach(async () => { - // restore default config - const settings = vscode.workspace.getConfiguration("githubCodeOwners") - await settings.update( - "format.enabled", - true, - vscode.ConfigurationTarget.Global, - ) - await settings.update( - "format.alignmentOffset", - 4, - vscode.ConfigurationTarget.Global, - ) - }) - - test("should never edit this document due to the grammar", async () => { - const testDocument = await createMockDocument( - "test/data/align-codeowners/should-never-change", - ) - - const result = await provider.provideDocumentFormattingEdits( - testDocument, - mockOptions, - mockToken, - ) - - assert(Array.isArray(result)) - assert.strictEqual(result.length, 0) - }) - - test("should not edit when formatting is disabled", async () => { - const settings = vscode.workspace.getConfiguration("githubCodeOwners") - await settings.update( - "format.enabled", - false, - vscode.ConfigurationTarget.Global, - ) - const testDocument = await createMockDocument( - "test/data/align-codeowners/input-to-format", - ) - - const result = await provider.provideDocumentFormattingEdits( - testDocument, - mockOptions, - mockToken, - ) - assert(Array.isArray(result)) - assert.strictEqual(result.length, 0) - }) - - badOffSetValues.forEach((badOffSetValue) => { - test(`should throw an error when alignment offset is not a positive number: ${badOffSetValue}`, async () => { - const settings = vscode.workspace.getConfiguration("githubCodeOwners") - await settings.update( - "format.alignmentOffset", - badOffSetValue, - vscode.ConfigurationTarget.Global, - ) - const testDocument = await createMockDocument( - "test/data/align-codeowners/input-to-format", - ) - await assert.rejects( - () => - provider.provideDocumentFormattingEdits( - testDocument, - mockOptions, - mockToken, - ), - Error, - ) - }) - }) - - test("should create same output as 'expected-formatted-with-offset-4'", async () => { - const testDocument = await createMockDocument( - "test/data/align-codeowners/input-to-format", - ) - const result = await provider.provideDocumentFormattingEdits( - testDocument, - mockOptions, - mockToken, - ) - const workEdits = new vscode.WorkspaceEdit() - await workEdits.set(testDocument.uri, result) - await vscode.workspace.applyEdit(workEdits) - - const expected = fs.readFileSync( - path.join( - repoRoot, - "test/data/align-codeowners/expected-formatted-with-offset-4", - ), - ) - assert.strictEqual(testDocument.getText(), expected.toString()) - }) - - test("should create same output as 'expected-formatted-with-offset-8'", async () => { - const settings = vscode.workspace.getConfiguration("githubCodeOwners") - await settings.update( - "format.alignmentOffset", - 8, - vscode.ConfigurationTarget.Global, - ) - const testDocument = await createMockDocument( - "test/data/align-codeowners/input-to-format", - ) - - const result = await provider.provideDocumentFormattingEdits( - testDocument, - mockOptions, - mockToken, - ) - const workEdits = new vscode.WorkspaceEdit() - await workEdits.set(testDocument.uri, result) - await vscode.workspace.applyEdit(workEdits) - - const expected = fs.readFileSync( - path.join( - repoRoot, - "test/data/align-codeowners/expected-formatted-with-offset-8", - ), - ) - assert.strictEqual(testDocument.getText(), expected.toString()) - }) -}) diff --git a/test/suite/language-server.test.ts b/test/suite/language-server.test.ts index 0ee2af0..cfe6ae2 100644 --- a/test/suite/language-server.test.ts +++ b/test/suite/language-server.test.ts @@ -101,6 +101,29 @@ suite("language server", function () { assert.strictEqual(edit?.newText, "/app/\\[id\\]/") }) + test("formats the document", async () => { + const document = await vscode.workspace.openTextDocument({ + language: "codeowners", + content: " /src/ @acme/web # web\n/docs/ @acme/docs\n", + }) + const edits = await waitFor( + () => + vscode.commands.executeCommand( + "vscode.executeFormatDocumentProvider", + document.uri, + { tabSize: 2, insertSpaces: true }, + ), + (e) => e != null && e.length > 0, + ) + const edit = new vscode.WorkspaceEdit() + edit.set(document.uri, edits ?? []) + await vscode.workspace.applyEdit(edit) + assert.strictEqual( + document.getText(), + "/src/ @acme/web # web\n/docs/ @acme/docs\n", + ) + }) + test("hides file counts when they're disabled", async () => { const config = vscode.workspace.getConfiguration("githubCodeOwners") await config.update(