diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 41affaa..65f3406 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,6 +44,15 @@ jobs: - name: Run the unit tests run: npm run test:unit + - name: Install StGit + # The integration tests run stg. Distributions ship old releases, so take one from upstream. + run: | + cd "$RUNNER_TEMP" + curl -fsSLO https://github.com/stacked-git/stgit/releases/download/v2.5.0/stgit_2.5.0-1_amd64.deb + echo "cf9db4b68c4b45dbfe01f537f119a9c6fa234719ac337b36cfeed5d5933d33e8 stgit_2.5.0-1_amd64.deb" | sha256sum -c - + sudo apt-get install -y ./stgit_2.5.0-1_amd64.deb + stg --version + - name: Run the integration tests # VS Code needs a display, even when only running tests. run: xvfb-run -a node ./out/test/runTest.js diff --git a/.vscode/launch.json b/.vscode/launch.json index 1f5b77a..70be883 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -11,7 +11,7 @@ "request": "launch", "args": ["--extensionDevelopmentPath=${workspaceFolder}"], "outFiles": ["${workspaceFolder}/out/**/*.js"], - "preLaunchTask": "${defaultBuildTask}" + "preLaunchTask": "stgit: debug" }, { "name": "Run Extension (Clean)", @@ -19,7 +19,7 @@ "request": "launch", "args": ["--extensionDevelopmentPath=${workspaceFolder}", "--disable-extensions"], "outFiles": ["${workspaceFolder}/out/**/*.js"], - "preLaunchTask": "${defaultBuildTask}" + "preLaunchTask": "stgit: debug" }, { "name": "Extension Tests", @@ -27,7 +27,7 @@ "request": "launch", "args": ["--extensionDevelopmentPath=${workspaceFolder}", "--extensionTestsPath=${workspaceFolder}/out/test/suite/index"], "outFiles": ["${workspaceFolder}/out/test/**/*.js"], - "preLaunchTask": "${defaultBuildTask}" + "preLaunchTask": "stgit: debug" } ] } diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..f0ef899 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "chat.tools.terminal.autoApprove": { + "./node_modules/.bin/eslint": true, + "git check-ignore": true + } +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 5deb2bc..1f49469 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -4,9 +4,23 @@ "version": "2.0.0", "tasks": [ { + "label": "stgit: compile", + "type": "npm", + "script": "compile", + "problemMatcher": "$tsc" + }, + { + "label": "stgit: watch", "type": "npm", "script": "watch", - "problemMatcher": "$tsc-watch", + "problemMatcher": { + "base": "$tsc-watch", + "background": { + "activeOnStart": true, + "beginsPattern": "^\\[0\\].*(Starting compilation in watch mode|File change detected\\. Starting incremental compilation)", + "endsPattern": "^\\[0\\].*Found [0-9]+ errors?\\. Watching for file changes\\." + } + }, "isBackground": true, "presentation": { "reveal": "never" @@ -15,6 +29,12 @@ "kind": "build", "isDefault": true } + }, + { + "label": "stgit: debug", + "dependsOrder": "sequence", + "dependsOn": ["stgit: compile", "stgit: watch"], + "problemMatcher": [] } ] } diff --git a/CHANGELOG.md b/CHANGELOG.md index 61dce6c..aa19a70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,16 @@ repository. Changes up to that version are documented in its ## [Unreleased] +### Changed + +- The stgit buffer is now a web view with stricter controls of navigation. This obviates a bunch of issues with overloaded keyboard shortcuts and vim mode quirks. +- Commit messages are written in a text editor under the StGit window instead of a text box in it, so editor shortcuts and vim mode work. It shows the same template as `stg new` and `stg edit`, where the patch name and author can be changed too, and highlights the message as Markdown. The editor is kept under the StGit window when it is moved or covered. `Ctrl-Enter` or `Ctrl-C Ctrl-C` commits and always closes the editor; should StGit fail, the error offers to edit the message again. +- Patches and commits with an empty commit message are marked with a "no message" tag instead of showing an empty row, and patches without changes with an "empty" tag. + +### Fixed + +- Expanding or collapsing patches, marking patches, viewing diffs and opening or cancelling the commit message editor no longer reload the patch series, index and work tree. Since 1.0.1, every command did. + ## [1.1.2] - 2026-11-10 ### Fixed diff --git a/README.md b/README.md index c6b64ac..62cca62 100644 --- a/README.md +++ b/README.md @@ -12,14 +12,16 @@ Install [StGit Revived](https://marketplace.visualstudio.com/items?itemName=cede ## Features -The StGit patch series is displayed in a window. StGit and Git operations, bound to various keyboard shortcuts, allow the series to be reworked as desired. +The StGit patch series is displayed as a table in a webview. Status symbols distinguish applied and popped patches as well as modified, added, deleted, and conflicted files. A loading indicator appears while StGit commands or status reads are running. StGit and Git operations are available through the existing keyboard shortcuts when the webview is focused. + +Use the arrow keys to select patches and files, Enter to expand a patch or open a file, and `m`/`u` to mark or unmark patches. + +Commit messages (`c` for a new patch, `e` to edit the selected one) are written in a text editor that opens under the StGit window, so your own editor setup, such as vim mode, works in it. It shows the same template as `stg new` and `stg edit`: the patch name, author and date above the message can be changed too, and lines starting with `#` are left out. Commit with `Ctrl-Enter`, `Ctrl-C Ctrl-C` or the Commit button, or save and close the editor. Close the editor without saving, or use the Cancel button, to cancel. Committing always closes the editor: as with `stg new`, an empty message creates no patch, while an existing patch may be given an empty message. Should StGit fail, the error offers to edit the message again. The editor stays under the StGit window: when it is moved elsewhere or covered by another tab, it is put back. The extension also provides an Emacs-like diff mode, which among other things allows individual hunks to be applied, staged or split into smaller hunks. While the StGit window is open, it follows the repository of the active file, including files in submodules. -![Example](images/example.png) - > [!TIP] > > To enter StGit, press `Ctrl-C Ctrl-I` or run the "`StGit: Open...`" @@ -40,9 +42,13 @@ This extension requires StGit to be installed (the executable is called `stg`). Git history entries use the effective `format.pretty` Git configuration. Custom `format:` and `tformat:` values and named `pretty.` aliases are supported. Multiline output is flattened to one line, and terminal colors are omitted. If no reusable one-line format is configured, the extension uses `%h %s`. +## Development + +Starting any Extension Development Host debug configuration builds both the extension and the React webview before starting the background watch task. Subsequent webview JS/CSS rebuilds automatically reload the open StGit panel in the development host, preserving its selection and scroll position. For extension-host code changes, reload the Extension Development Host window to load the newly compiled code. Run `npm run compile` for a one-off build or `npm run watch` outside debugging; restart an older watch process after changing the build scripts. `npm run test:unit` includes a DOM test of the compiled webview; `npm test` runs the VS Code extension-host suite when its test executable is available. + ## Known Issues -The StGit extension can be used together with the popular Vim mode for VsCode, but there are currently a few key mapping conflicts for the StGit editor. +Vim extensions may intercept some StGit keyboard shortcuts in the webview. Closing the StGit tab while editing a commit message closes the message editor and discards the message; cancel the message before closing to get a confirmation. ## Release Notes diff --git a/package-lock.json b/package-lock.json index ba45f62..242aa42 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,19 +10,28 @@ "license": "BSD-2-Clause", "devDependencies": { "@types/glob": "^8.0.3", + "@types/jsdom": "^30.0.0", "@types/mocha": "^9.1.1", "@types/node": "16.x", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", "@types/vscode": "^1.91.0", "@typescript-eslint/eslint-plugin": "^5.59.0", "@typescript-eslint/parser": "^5.59.0", "@vscode/test-electron": "^2.1.5", "@vscode/vsce": "^3.6.0", + "concurrently": "^10.0.6", + "esbuild": "^0.28.2", "eslint": "^8.41.0", "eslint-config-prettier": "^9.1.2", "glob": "^8.0.3", "js-yaml": "^4.1.0", + "jsdom": "^30.1.3", + "lucide-react": "^1.61.0", "mocha": "^10.0.0", "prettier": "^3.9.9", + "react": "^19.3.1", + "react-dom": "^19.3.1", "typescript": "^5.0.4", "vscode-tmgrammar-test": "^0.1.3" }, @@ -30,6 +39,59 @@ "vscode": "^1.91.0" } }, + "node_modules/@asamuzakjp/css-color": { + "version": "7.1.7", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-7.1.7.tgz", + "integrity": "sha512-Q7ioeear07HwixdIitIn9KS1LZi97CEDFCSjPNm9v+y8KNbsu9q4Lrd4zUQW4faED+E7qxvfeVnbNRW46wFKuw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^3.4.3", + "@csstools/css-color-parser": "^4.2.6", + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2", + "lru-cache": "^11.5.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@asamuzakjp/dom-selector": { + "version": "10.0.4", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-10.0.4.tgz", + "integrity": "sha512-A6f1nKy99I6tyoK82U6kBHvQQZmdHmTmPzJYPY/0eaOW0r8/qPmEOwjGHs+hL/vCgOwQTupu4LT1XtXNUuDruA==", + "dev": true, + "license": "MIT", + "dependencies": { + "bidi-js": "^1.1.0", + "css-tree": "^3.2.1", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/@asamuzakjp/dom-selector/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/@azu/format-text": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/@azu/format-text/-/format-text-1.0.2.tgz", @@ -161,83 +223,678 @@ "tslib": "^2.2.0" }, "engines": { - "node": ">=20.0.0" + "node": ">=20.0.0" + } + }, + "node_modules/@azure/logger": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.3.0.tgz", + "integrity": "sha512-fCqPIfOcLE+CGqGPd66c8bZpwAji98tZ4JI9i/mlTNTlsIWslCfpg48s/ypyLxZTump5sypjrKn2/kY7q8oAbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typespec/ts-http-runtime": "^0.3.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@azure/msal-browser": { + "version": "5.10.1", + "resolved": "https://registry.npmjs.org/@azure/msal-browser/-/msal-browser-5.10.1.tgz", + "integrity": "sha512-hTbvOi9Ko2Jvn+G/fSmjzHf9WbNcf/o3epMtbeGx/pMwMrVAbi6OgCJVeCfsAb8IybSRpaCSc4EDRlYAhgngUQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@azure/msal-common": "16.6.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@azure/msal-common": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-16.6.1.tgz", + "integrity": "sha512-VxKdEtUwDuLD0F1hOQP7kye0YadZxFJfv37Em440geEf/w9uggKnHpRrqwZJOdxmPUOdhZ9kyRtKuAJW8wUcRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@azure/msal-node": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/@azure/msal-node/-/msal-node-5.2.1.tgz", + "integrity": "sha512-tmQiQ2HvtzaeLqYGy3BemiPOSGPY4wCy1IW5zDWITKSs/s35WEd7Zij/hCxvUdAOzj6U3qnyaGbYXY91ortFEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@azure/msal-common": "16.6.1", + "jsonwebtoken": "^9.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", + "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.28.5", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bramus/specificity": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.3.tgz", + "integrity": "sha512-0GEz8qJWokkUVYQYRukmkSHIFNoBH8QTreeHrAFbvz1XFYc3Y+puhMs8PQ5x8GNugiC2l5jvDBXKLbBIByeSBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-tree": "^3.2.1" + }, + "bin": { + "specificity": "bin/cli.js" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.2.tgz", + "integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@csstools/css-calc": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.3.tgz", + "integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "4.2.6", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.6.tgz", + "integrity": "sha512-iiPQ3iRWwnJkeEn6RIu6SJPr7hYrLz6XZ9s/QZl+2/LI5KQVjpl2fdmDSZKuD4xP6GMmMPgHFFXg6k1Wkz0Trg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^6.1.2", + "@csstools/css-calc": "^3.4.3" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz", + "integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.15.tgz", + "integrity": "sha512-J0u7HkVl2nzSlhsiTOp4AmwcUQ3D+mGEEKfBy/7To5/y7F2OHwyLrXfrhR0SMgr4p5Lo+eaMVSeai24zUcBIxA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "peerDependencies": { + "css-tree": "^3.2.1" + }, + "peerDependenciesMeta": { + "css-tree": { + "optional": true + } + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz", + "integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" } }, - "node_modules/@azure/logger": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.3.0.tgz", - "integrity": "sha512-fCqPIfOcLE+CGqGPd66c8bZpwAji98tZ4JI9i/mlTNTlsIWslCfpg48s/ypyLxZTump5sypjrKn2/kY7q8oAbA==", + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], "dev": true, "license": "MIT", - "dependencies": { - "@typespec/ts-http-runtime": "^0.3.0", - "tslib": "^2.6.2" - }, + "optional": true, + "os": [ + "openbsd" + ], "engines": { - "node": ">=20.0.0" + "node": ">=18" } }, - "node_modules/@azure/msal-browser": { - "version": "5.10.1", - "resolved": "https://registry.npmjs.org/@azure/msal-browser/-/msal-browser-5.10.1.tgz", - "integrity": "sha512-hTbvOi9Ko2Jvn+G/fSmjzHf9WbNcf/o3epMtbeGx/pMwMrVAbi6OgCJVeCfsAb8IybSRpaCSc4EDRlYAhgngUQ==", + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", - "dependencies": { - "@azure/msal-common": "16.6.1" - }, + "optional": true, + "os": [ + "openharmony" + ], "engines": { - "node": ">=0.8.0" + "node": ">=18" } }, - "node_modules/@azure/msal-common": { - "version": "16.6.1", - "resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-16.6.1.tgz", - "integrity": "sha512-VxKdEtUwDuLD0F1hOQP7kye0YadZxFJfv37Em440geEf/w9uggKnHpRrqwZJOdxmPUOdhZ9kyRtKuAJW8wUcRg==", + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], "dev": true, "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], "engines": { - "node": ">=0.8.0" + "node": ">=18" } }, - "node_modules/@azure/msal-node": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/@azure/msal-node/-/msal-node-5.2.1.tgz", - "integrity": "sha512-tmQiQ2HvtzaeLqYGy3BemiPOSGPY4wCy1IW5zDWITKSs/s35WEd7Zij/hCxvUdAOzj6U3qnyaGbYXY91ortFEQ==", + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", - "dependencies": { - "@azure/msal-common": "16.6.1", - "jsonwebtoken": "^9.0.0" - }, + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": ">=20" + "node": ">=18" } }, - "node_modules/@babel/code-frame": { - "version": "7.29.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", - "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], "dev": true, "license": "MIT", - "dependencies": { - "@babel/helper-validator-identifier": "^7.28.5", - "js-tokens": "^4.0.0", - "picocolors": "^1.1.1" - }, + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": ">=6.9.0" + "node": ">=18" } }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", - "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], "dev": true, "license": "MIT", + "optional": true, + "os": [ + "win32" + ], "engines": { - "node": ">=6.9.0" + "node": ">=18" } }, "node_modules/@eslint-community/eslint-utils": { @@ -327,6 +984,24 @@ "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, "node_modules/@humanwhocodes/config-array": { "version": "0.13.0", "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", @@ -695,6 +1370,45 @@ "@types/node": "*" } }, + "node_modules/@types/jsdom": { + "version": "30.0.0", + "resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-30.0.0.tgz", + "integrity": "sha512-uAHGxujGE0cDaKGdK28zgDotFtNA7MKq5DXl8LrfdxdCI8VHcg15oJz+amHTChPNI5JpgEPQWc2xFdrw3em/nQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/tough-cookie": "*", + "parse5": "^8.0.0", + "undici-types": "^8.9.0" + } + }, + "node_modules/@types/jsdom/node_modules/entities": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", + "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/@types/jsdom/node_modules/parse5": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz", + "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^8.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", @@ -730,6 +1444,26 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, "node_modules/@types/sarif": { "version": "2.1.7", "resolved": "https://registry.npmjs.org/@types/sarif/-/sarif-2.1.7.tgz", @@ -744,6 +1478,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/tough-cookie": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.5.tgz", + "integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/vscode": { "version": "1.120.0", "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.120.0.tgz", @@ -1435,6 +2176,16 @@ "license": "MIT", "optional": true }, + "node_modules/bidi-js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz", + "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" + } + }, "node_modules/binary-extensions": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", @@ -1859,35 +2610,185 @@ "dev": true, "license": "MIT" }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/concurrently": { + "version": "10.0.6", + "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-10.0.6.tgz", + "integrity": "sha512-qgICXXFp2/3nAebRLmxcINKEXM1mLK3ij/y31P02VTs/KIkddIeC05n73DxOXsXMB9LFSqNU1/na3lDlOhcbIw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "5.6.2", + "rxjs": "7.8.2", + "shell-quote": "1.12.0", + "supports-color": "10.2.2", + "tree-kill": "1.2.2", + "yargs": "18.0.0" + }, + "bin": { + "conc": "dist/bin/index.js", + "concurrently": "dist/bin/index.js" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/open-cli-tools/concurrently?sponsor=1" + } + }, + "node_modules/concurrently/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/concurrently/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/concurrently/node_modules/cliui": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz", + "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^7.2.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/concurrently/node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "dev": true, + "license": "MIT" + }, + "node_modules/concurrently/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/concurrently/node_modules/supports-color": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", + "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/concurrently/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", "dev": true, "license": "MIT", "dependencies": { - "delayed-stream": "~1.0.0" + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" }, "engines": { - "node": ">= 0.8" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, - "node_modules/commander": { - "version": "12.1.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", - "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "node_modules/concurrently/node_modules/yargs": { + "version": "18.0.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.0.0.tgz", + "integrity": "sha512-4UEqdc2RYGHZc7Doyqkrqiln3p9X2DZVxaGbwhn2pi7MrRagKaOcIKe8L3OxYcbhXLgLFUS3zAYuQjKBQgmuNg==", "dev": true, "license": "MIT", + "dependencies": { + "cliui": "^9.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "string-width": "^7.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^22.0.0" + }, "engines": { - "node": ">=18" + "node": "^20.19.0 || ^22.12.0 || >=23" } }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "node_modules/concurrently/node_modules/yargs-parser": { + "version": "22.0.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz", + "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==", "dev": true, - "license": "MIT" + "license": "ISC", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=23" + } }, "node_modules/core-util-is": { "version": "1.0.3", @@ -1928,6 +2829,20 @@ "url": "https://github.com/sponsors/fb55" } }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, "node_modules/css-what": { "version": "6.2.2", "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.2.2.tgz", @@ -1941,6 +2856,37 @@ "url": "https://github.com/sponsors/fb55" } }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/data-urls": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz", + "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.1.2" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/data-urls/node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -1972,6 +2918,13 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, "node_modules/decompress-response": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", @@ -2315,6 +3268,48 @@ "node": ">= 0.4" } }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -3112,6 +4107,19 @@ "node": ">=10" } }, + "node_modules/html-encoding-sniffer": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", + "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.15.1" + }, + "engines": { + "node": "^22.13.0 || >=24.0.0" + } + }, "node_modules/htmlparser2": { "version": "10.1.0", "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz", @@ -3416,6 +4424,13 @@ "node": ">=8" } }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, "node_modules/is-unicode-supported": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", @@ -3513,6 +4528,102 @@ "js-yaml": "bin/js-yaml.js" } }, + "node_modules/jsdom": { + "version": "30.1.3", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.1.3.tgz", + "integrity": "sha512-hQMUPvRgN7KxsfIytDQji7bimuJeRQa6Qo5+iuiZQk5CafeRxLIA10/cG5YCBFNpD9RO3oqIiN4CO1Y44kxqXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^7.1.3", + "@asamuzakjp/dom-selector": "^10.0.3", + "@bramus/specificity": "^2.4.2", + "@csstools/css-syntax-patches-for-csstree": "^1.1.15", + "@exodus/bytes": "^1.16.0", + "css-tree": "^3.2.1", + "data-urls": "^8.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^7.0.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3", + "parse5": "^8.0.1", + "saxes": "^6.0.0", + "tough-cookie": "^6.0.2", + "undici": "^8.12.1", + "w3c-xmlserializer": "^6.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.2.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "canvas": "^3.2.3" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jsdom/node_modules/entities": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", + "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/jsdom/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/jsdom/node_modules/parse5": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz", + "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^8.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/jsdom/node_modules/undici": { + "version": "8.12.3", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.3.tgz", + "integrity": "sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/jsdom/node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, "node_modules/json-buffer": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", @@ -3809,6 +4920,22 @@ "node": ">=10" } }, + "node_modules/lucide-react": { + "version": "1.61.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.61.0.tgz", + "integrity": "sha512-v2SQPPPNjnr+BlhL9Spuzmo5yR+hLkftfuE4E3jaxdNPgSH0hJKPcLJBP7yAta87jQNPsSERS59PJjCJ/CorBA==", + "dev": true, + "license": "ISC", + "peerDependencies": { + "@types/react": "*", + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/markdown-it": { "version": "14.1.1", "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.1.tgz", @@ -3837,6 +4964,13 @@ "node": ">= 0.4" } }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, "node_modules/mdurl": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.0.0.tgz", @@ -4821,6 +5955,29 @@ "node": ">=0.10.0" } }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, "node_modules/read": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/read/-/read-1.0.7.tgz", @@ -5037,6 +6194,16 @@ "queue-microtask": "^1.2.2" } }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, "node_modules/safe-buffer": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", @@ -5075,6 +6242,26 @@ "node": ">=11.0.0" } }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "dev": true, + "license": "MIT" + }, "node_modules/secretlint": { "version": "10.2.2", "resolved": "https://registry.npmjs.org/secretlint/-/secretlint-10.2.2.tgz", @@ -5220,6 +6407,19 @@ "node": ">=8" } }, + "node_modules/shell-quote": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.12.0.tgz", + "integrity": "sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/side-channel": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", @@ -5386,6 +6586,16 @@ "url": "https://github.com/chalk/slice-ansi?sponsor=1" } }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/spdx-correct": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.2.0.tgz", @@ -5687,6 +6897,26 @@ "url": "https://bevry.me/fund" } }, + "node_modules/tldts": { + "version": "7.4.19", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.19.tgz", + "integrity": "sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.4.19" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.4.19", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.19.tgz", + "integrity": "sha512-goNXV6Ho9TIOfpJZanTd6CKG5DyYgYAL+k+22T0SLh8l6+KHIfBUPFuePuSZv05UttIaaLmI9tb7TmGIdK5AkQ==", + "dev": true, + "license": "MIT" + }, "node_modules/tmp": { "version": "0.2.5", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz", @@ -5710,6 +6940,42 @@ "node": ">=8.0" } }, + "node_modules/tough-cookie": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz", + "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz", + "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true, + "license": "MIT", + "bin": { + "tree-kill": "cli.js" + } + }, "node_modules/tslib": { "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", @@ -5840,6 +7106,13 @@ "node": ">=20.18.1" } }, + "node_modules/undici-types": { + "version": "8.12.3", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.12.3.tgz", + "integrity": "sha512-EXE4ydL3S76dFb27UFjNVZHTyv/TLdATj/KUe29ptdcg6qXL48J2tZ3126E5kICj5jn781OR+XlVH1N6Mz8jbA==", + "dev": true, + "license": "MIT" + }, "node_modules/unicorn-magic": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.1.0.tgz", @@ -6065,6 +7338,29 @@ "dev": true, "license": "MIT" }, + "node_modules/w3c-xmlserializer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", + "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, "node_modules/whatwg-encoding": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", @@ -6089,6 +7385,21 @@ "node": ">=18" } }, + "node_modules/whatwg-url": { + "version": "17.3.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz", + "integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "tr46": "^7.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -6186,6 +7497,16 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, "node_modules/xml2js": { "version": "0.5.0", "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.5.0.tgz", @@ -6210,6 +7531,13 @@ "node": ">=4.0" } }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", diff --git a/package.json b/package.json index 304fdb3..73f02d6 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,9 @@ "patch series", "git" ], - "activationEvents": [], + "activationEvents": [ + "onFileSystem:stgit-message" + ], "main": "./out/extension.js", "license": "BSD-2-Clause", "repository": { @@ -27,12 +29,6 @@ "publisher": "cedernaes", "icon": "images/icon.png", "contributes": { - "configurationDefaults": { - "[stgit-buffer]": { - "editor.folding": false, - "editor.guides.indentation": false - } - }, "configuration": { "title": "StGit", "properties": { @@ -66,7 +62,23 @@ "when": "comment == stgit-edit" } ], + "editor/title": [ + { + "command": "stgit.submitComment", + "when": "resourceScheme == stgit-message", + "group": "navigation@1" + }, + { + "command": "stgit.discardCommitMessage", + "when": "resourceScheme == stgit-message", + "group": "navigation@2" + } + ], "commandPalette": [ + { + "command": "stgit.discardCommitMessage", + "when": "stgitEditing" + }, { "command": "stgit.commentCreatePatch", "when": "false" @@ -83,6 +95,16 @@ "filenames": [ "StGit" ] + }, + { + "id": "stgit-message", + "aliases": [ + "StGit Message" + ], + "filenames": [ + "STGIT_EDITMSG" + ], + "configuration": "./syntaxes/stgit-message.language-configuration.json" } ], "grammars": [ @@ -90,6 +112,11 @@ "language": "stgit-buffer", "scopeName": "source.stgit", "path": "./syntaxes/stgit.tmLanguage.json" + }, + { + "language": "stgit-message", + "scopeName": "text.stgit-message", + "path": "./syntaxes/stgit-message.tmLanguage.json" } ], "commands": [ @@ -103,6 +130,23 @@ "category": "StGit", "title": "Update" }, + { + "command": "stgit.submitComment", + "category": "StGit", + "title": "Submit Commit Message", + "icon": "$(check)" + }, + { + "command": "stgit.discardCommitMessage", + "category": "StGit", + "title": "Discard Commit Message", + "icon": "$(discard)" + }, + { + "command": "stgit.initializeBranch", + "category": "StGit", + "title": "Initialize Branch" + }, { "command": "stgit.open", "category": "StGit", @@ -379,207 +423,202 @@ { "key": "r", "command": "stgit.refresh", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "ctrl-u r", "command": "stgit.refreshSpecific", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "g", "command": "stgit.reload", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "ctrl-u g", "command": "stgit.repair", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "shift+g", "command": "stgit.gotoPatch", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "shift+p", "command": "stgit.pushOrPopPatches", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "shift+.", "command": "stgit.pushNextPatch", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "shift+,", "command": "stgit.popCurrentPatch", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "shift+h", "command": "stgit.setHistorySize", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "shift+m", "command": "stgit.movePatchesTo", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "ctrl+c shift+b", "command": "stgit.createBranch", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "shift+b", "command": "stgit.switchBranch", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "f", "command": "stgit.highlightFile", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "shift+f", "command": "stgit.cancelHighlighting", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "u", "command": "stgit.unmarkPatch", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "m", "command": "stgit.markPatch", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "i", "command": "stgit.toggleChanges", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "shift+u", "command": "stgit.revertChanges", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "ctrl+c ctrl+b", "command": "stgit.rebase", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "ctrl+c f", "command": "stgit.gitFetch", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "ctrl+c p", "command": "stgit.gitPush", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "ctrl+c r", "command": "stgit.selectRemote", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "ctrl+c u", "command": "stgit.selectUpstreamBranch", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "ctrl+u p", "command": "stgit.gitForcePush", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "ctrl+shift+-", "command": "stgit.undo", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "ctrl+u ctrl+shift+-", "command": "stgit.hardUndo", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "ctrl+c ctrl+shift+-", "command": "stgit.redo", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "shift+n", "command": "stgit.newPatch", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "c", "command": "stgit.createPatch", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "ctrl-c ctrl-c", "command": "stgit.commitOrUncommitPatches", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "h", "command": "stgit.help", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" - }, - { - "key": "enter", - "command": "stgit.toggleExpand", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "-", "command": "stgit.navigateToParent", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "t", "command": "stgit.toggleShowingUnknown", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "shift+R", "command": "stgit.resolveConflict", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "e", "command": "stgit.editCommitMessage", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "shift+s", "command": "stgit.squashPatches", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "shift+d", "command": "stgit.deletePatches", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "shift+=", "command": "stgit.openDiffEditor", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "=", "command": "stgit.showDiff", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "alt-=", "command": "stgit.openDiff", - "when": "resourceScheme == stgit && editorTextFocus && !commentEditorFocused" + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "ctrl+c ctrl+i", @@ -588,18 +627,23 @@ }, { "key": "ctrl+c ctrl+c", - "command": "editor.action.submitComment", - "when": "resourceScheme == stgit && commentEditorFocused" + "command": "stgit.submitComment", + "when": "activeWebviewPanelId == stgit && stgitEditing && !inQuickOpen && !terminalFocus" }, { - "key": "escape", - "command": "stgit.cancel", - "when": "resourceScheme == stgit" + "key": "ctrl+enter", + "command": "stgit.submitComment", + "when": "editorTextFocus && resourceScheme == stgit-message" + }, + { + "key": "ctrl+c ctrl+c", + "command": "stgit.submitComment", + "when": "editorTextFocus && resourceScheme == stgit-message && !editorHasSelection" }, { "key": "escape", - "command": "stgit.cancelEmptyComment", - "when": "resourceScheme == stgit && commentEditorFocused && commentIsEmpty" + "command": "stgit.cancel", + "when": "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus" }, { "key": "h", @@ -655,12 +699,14 @@ }, "scripts": { "vscode:prepublish": "npm run compile", - "compile": "tsc -p ./", + "compile": "tsc -p ./ && npm run compile:webview", + "compile:webview": "tsc --noEmit -p tsconfig.webview.json && esbuild src/webview/index.tsx --bundle --platform=browser --format=iife --jsx=automatic --minify --target=es2020 --outdir=out/webview", "format": "prettier --write .", "format:check": "prettier --check .", - "watch": "tsc -watch -p ./", + "watch": "concurrently -k \"tsc --watch -p ./\" \"tsc --noEmit --watch -p tsconfig.webview.json\" \"npm run watch:webview\"", + "watch:webview": "esbuild src/webview/index.tsx --bundle --platform=browser --format=iife --jsx=automatic --target=es2020 --outdir=out/webview --watch", "pretest": "npm run compile && npm run lint && npm run test:grammar", - "lint": "eslint src --ext ts", + "lint": "eslint src --ext ts,tsx", "test": "node ./out/test/runTest.js", "test:unit": "npm run compile && mocha --ui tdd \"out/test/unit/**/*.test.js\" && npm run test:grammar", "test:grammar": "vscode-tmgrammar-test 'src/test/syntax/*.test.stgit'", @@ -670,19 +716,28 @@ }, "devDependencies": { "@types/glob": "^8.0.3", + "@types/jsdom": "^30.0.0", "@types/mocha": "^9.1.1", "@types/node": "16.x", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", "@types/vscode": "^1.91.0", "@typescript-eslint/eslint-plugin": "^5.59.0", "@typescript-eslint/parser": "^5.59.0", "@vscode/test-electron": "^2.1.5", "@vscode/vsce": "^3.6.0", + "concurrently": "^10.0.6", + "esbuild": "^0.28.2", "eslint": "^8.41.0", "eslint-config-prettier": "^9.1.2", "glob": "^8.0.3", "js-yaml": "^4.1.0", + "jsdom": "^30.1.3", + "lucide-react": "^1.61.0", "mocha": "^10.0.0", "prettier": "^3.9.9", + "react": "^19.3.1", + "react-dom": "^19.3.1", "typescript": "^5.0.4", "vscode-tmgrammar-test": "^0.1.3" } diff --git a/src/branch-label.ts b/src/branch-label.ts new file mode 100644 index 0000000..de5e720 --- /dev/null +++ b/src/branch-label.ts @@ -0,0 +1,14 @@ +/** + * Formats the upstream part of the branch line, e.g. ` <-> origin/main`. + * An upstream with the same name as the local branch is abbreviated to + * `/*`. + */ +export function formatUpstream(branchName: string | null, remoteName: string | null, remoteBranch: string | null): string { + if (remoteBranch && remoteName) { + return ` <-> ${remoteName}/${remoteBranch === branchName ? "*" : remoteBranch}`; + } + if (remoteName) { + return ` (${remoteName})`; + } + return ""; +} diff --git a/src/editor-layout.ts b/src/editor-layout.ts new file mode 100644 index 0000000..e1a1e4f --- /dev/null +++ b/src/editor-layout.ts @@ -0,0 +1,39 @@ +// Editor layouts as the "vscode.getEditorLayout" and "vscode.setEditorLayout" commands describe them. +// Orientation 0 puts groups side by side and 1 stacks them; nested groups take the other orientation. +// The groups without nested groups are the editor groups, in the same order as their view columns. +export interface EditorLayout { + orientation: 0 | 1; + groups: EditorLayoutGroup[]; +} + +export interface EditorLayoutGroup { + groups?: EditorLayoutGroup[]; + size?: number; +} + +// Whether the editor group after `upper` (counted from 0) sits directly under it, just as wide. +// Undefined when the layout has no group `upper`, as for a group in another window. +export function isStackedBelow(layout: EditorLayout, upper: number): boolean | undefined { + let index = 0; + const visit = (groups: EditorLayoutGroup[], stacked: boolean): boolean | undefined => { + for (const [position, group] of groups.entries()) { + if (group.groups?.length) { + const found = visit(group.groups, !stacked); + if (found !== undefined) { + return found; + } + } else if (index++ === upper) { + const next = groups[position + 1]; + return stacked && !!next && !next.groups?.length; + } + } + return undefined; + }; + return visit(layout.groups, layout.orientation === 1); +} + +// The same groups with a new, empty column right of all of them +export function addColumnOnRight(layout: EditorLayout): EditorLayout { + const columns = layout.orientation === 0 ? layout.groups : [{ groups: layout.groups }]; + return { orientation: 0, groups: [...columns, {}] }; +} diff --git a/src/message-editor.ts b/src/message-editor.ts new file mode 100644 index 0000000..3cc6c34 --- /dev/null +++ b/src/message-editor.ts @@ -0,0 +1,329 @@ +import * as vscode from "vscode"; +import { commands, window, workspace } from "vscode"; +import { EditorLayout, isStackedBelow } from "./editor-layout"; +import { log } from "./extension"; + +export const messageScheme = "stgit-message"; + +// Holds the commit messages being written. Saving a message editor stores its text here. +class MessageFileSystem implements vscode.FileSystemProvider { + private readonly files = new Map(); + private readonly changes = new vscode.EventEmitter(); + readonly onDidChangeFile = this.changes.event; + + setText(uri: vscode.Uri, text: string) { + const now = Date.now(); + this.files.set(uri.path, { data: new TextEncoder().encode(text), ctime: now, mtime: now }); + } + + text(uri: vscode.Uri): string { + const file = this.files.get(uri.path); + return file ? new TextDecoder().decode(file.data) : ""; + } + + forget(uri: vscode.Uri) { + this.files.delete(uri.path); + } + + watch(): vscode.Disposable { + return new vscode.Disposable(() => undefined); + } + + stat(uri: vscode.Uri): vscode.FileStat { + const file = this.lookup(uri); + return { type: vscode.FileType.File, ctime: file.ctime, mtime: file.mtime, size: file.data.byteLength }; + } + + readFile(uri: vscode.Uri): Uint8Array { + return this.lookup(uri).data; + } + + writeFile(uri: vscode.Uri, content: Uint8Array) { + const file = this.lookup(uri); + file.data = content; + // Always newer than before, so that VS Code never takes the save for a change made elsewhere + file.mtime = Math.max(Date.now(), file.mtime + 1); + } + + readDirectory(): [string, vscode.FileType][] { + return []; + } + + createDirectory(uri: vscode.Uri) { + throw vscode.FileSystemError.NoPermissions(uri); + } + + delete(uri: vscode.Uri) { + throw vscode.FileSystemError.NoPermissions(uri); + } + + rename(uri: vscode.Uri) { + throw vscode.FileSystemError.NoPermissions(uri); + } + + private lookup(uri: vscode.Uri) { + const file = this.files.get(uri.path); + if (!file) { + throw vscode.FileSystemError.FileNotFound(uri); + } + return file; + } +} + +const fileSystem = new MessageFileSystem(); +let messagesOpened = 0; + +export function registerMessageFileSystem(): vscode.Disposable { + const registration = workspace.registerFileSystemProvider(messageScheme, fileSystem, { isCaseSensitive: true }); + // Message editors that VS Code restored from an earlier session no longer belong to any commit + const stale = window.tabGroups.all.flatMap((group) => group.tabs).filter((tab) => tab.input instanceof vscode.TabInputText && tab.input.uri.scheme === messageScheme); + if (stale.length) { + void window.tabGroups.close(stale, true); + } + return registration; +} + +function isStGitPane(tab: vscode.Tab): boolean { + // Tabs report the webview type of an extension's panel with a prefix, as in "mainThreadWebview-stgit" + return tab.input instanceof vscode.TabInputWebview && /(^|-)stgit$/.test(tab.input.viewType); +} + +// The StGit pane's view column. The panel's own viewColumn is not updated when groups before it come or go, so it is +// read from the pane's tab instead. That also makes it comparable with the view columns of other tabs. +export function paneViewColumn(panel: vscode.WebviewPanel): vscode.ViewColumn | undefined { + return window.tabGroups.all.flatMap((group) => group.tabs).find(isStGitPane)?.group.viewColumn ?? panel.viewColumn; +} + +// Resolves to whether the condition came true within the time, checking it whenever one of the events fires +function waitFor(condition: () => boolean, events: vscode.Event[], timeout = 1000): Promise { + if (condition()) { + return Promise.resolve(true); + } + return new Promise((resolve) => { + const finish = (result: boolean) => { + clearTimeout(timer); + listeners.forEach((listener) => listener.dispose()); + resolve(result); + }; + const listeners = events.map((event) => event(() => condition() && finish(true))); + const timer = setTimeout(() => finish(condition()), timeout); + }); +} + +// A commit message written in a real text editor, kept in an editor group of its own right under the StGit pane. +// VS Code lets the person move any editor, so whenever the editor or the pane moves, or another tab covers the +// editor, it is put back in its place. +export class MessageEditor { + readonly uri: vscode.Uri; + private closed = false; + private readonly listeners: vscode.Disposable[]; + // Docking takes several steps, so it runs one at a time + private queue: Promise = Promise.resolve(); + private checkTimer: ReturnType | undefined; + private moves: number[] = []; + private movedAt = 0; + // Where the person last had the cursor, for the editor that replaces theirs when it is put back + private cursor: vscode.Selection | undefined; + + // `onClose` gets the text last saved when the person closes the editor themselves. The cursor starts at the + // beginning of `cursorLine`. + constructor( + text: string, + private readonly panel: vscode.WebviewPanel, + private readonly onClose: (saved: string) => void, + private readonly cursorLine = 0, + ) { + this.uri = vscode.Uri.from({ scheme: messageScheme, path: `/${++messagesOpened}/STGIT_EDITMSG` }); + fileSystem.setText(this.uri, text); + this.listeners = [ + window.tabGroups.onDidChangeTabs(({ closed }) => { + // A tab moved to another group opens there before it closes here, so the message is still open then + if (!this.closed && closed.some((tab) => this.isMine(tab)) && !this.tabs().length) { + this.onClose(fileSystem.text(this.uri)); + } + this.scheduleCheck(); + }), + window.tabGroups.onDidChangeTabGroups(() => this.scheduleCheck()), + window.onDidChangeTextEditorSelection(({ textEditor, selections, kind }) => { + // Without a kind, the cursor was set by VS Code, as for an editor that was just moved and starts at the top + if (kind !== undefined && textEditor.document.uri.toString() === this.uri.toString()) { + this.cursor = selections[0]; + } + }), + panel.onDidChangeViewState(() => this.scheduleCheck()), + ]; + } + + // What the editor holds, saved or not + get text(): string { + return this.document()?.getText() ?? fileSystem.text(this.uri); + } + + get viewColumn(): vscode.ViewColumn | undefined { + return this.tabs()[0]?.group.viewColumn; + } + + // Shows the editor in its place under the StGit pane, and focuses it + open(): Promise { + return this.enqueue(() => this.dock(true)); + } + + async close() { + if (this.closed) { + return; + } + this.closed = true; + clearTimeout(this.checkTimer); + this.listeners.forEach((listener) => listener.dispose()); + await this.queue; + // Saved first, so that closing does not ask about unsaved changes + const document = this.document(); + if (document?.isDirty) { + await document.save(); + } + await this.closeTabs(); + fileSystem.forget(this.uri); + } + + private enqueue(action: () => Promise): Promise { + this.queue = this.queue.then(() => (this.closed ? undefined : action())).catch((error) => log("Commit message editor:", String(error))); + return this.queue; + } + + // Moving a tab or a group fires several events, so the editor is put back only once things have settled + private scheduleCheck() { + if (this.closed) { + return; + } + clearTimeout(this.checkTimer); + this.checkTimer = setTimeout(() => { + void this.enqueue(async () => { + // Right after a move, the tab groups and the focus that VS Code reports are still catching up + const settling = this.movedAt + 300 - Date.now(); + if (settling > 0) { + await new Promise((resolve) => setTimeout(resolve, settling)); + } + await this.dock(false); + }); + }, 100); + } + + private document(): vscode.TextDocument | undefined { + return workspace.textDocuments.find((document) => document.uri.toString() === this.uri.toString()); + } + + private isMine(tab: vscode.Tab): boolean { + return tab.input instanceof vscode.TabInputText && tab.input.uri.toString() === this.uri.toString(); + } + + private tabs(): vscode.Tab[] { + return window.tabGroups.all.flatMap((group) => group.tabs.filter((tab) => this.isMine(tab))); + } + + // Opening shows and focuses the editor. Otherwise it is only put back, and keeps the focus if it had it. + private async dock(opening: boolean) { + if (!opening && !this.tabs().length) { + // Closed by the person, which ends the message rather than moving it + return; + } + const document = await workspace.openTextDocument(this.uri); + const layout = await commands.executeCommand("vscode.getEditorLayout"); + // Tab groups are only read after every wait, as VS Code replaces them when groups come and go + const tabs = this.tabs(); + const pane = paneViewColumn(this.panel); + if (this.closed || !pane || (!opening && !tabs.length)) { + return; + } + // VS Code goes on reporting the editor as the active one for a moment after the pane took the focus + const focus = opening || (!this.panel.active && window.activeTextEditor?.document === document); + const below = (pane + 1) as vscode.ViewColumn; + const groupBelow = (isStackedBelow(layout, pane - 1) ?? true) ? window.tabGroups.all.find((group) => group.viewColumn === below) : undefined; + if (groupBelow && tabs.length === 1 && tabs[0].group.viewColumn === below) { + // In its place: only bring it to the front if another tab covers it + if (opening || !tabs[0].isActive) { + await window.showTextDocument(document, { viewColumn: below, preserveFocus: !opening, preview: false }); + } + return; + } + if (!opening && this.movedTooOften()) { + return; + } + if (!groupBelow || !(groupBelow.tabs.length === 0 || groupBelow.tabs.some((tab) => this.isMine(tab)))) { + if (!(await this.splitBelowPane(pane))) { + log("Could not open a group under the StGit pane for the commit message editor"); + if (!tabs.length) { + await window.showTextDocument(document, { viewColumn: vscode.ViewColumn.Beside, preview: false }); + } + return; + } + } + // An editor opened in another group starts at the top, so it gets the cursor of the one it replaces. That is + // remembered rather than read from the moved editor, which reports the top for a moment after a move. + const cursor = this.cursor ?? new vscode.Range(this.cursorLine, 0, this.cursorLine, 0); + await window.showTextDocument(document, { viewColumn: below, preview: false, selection: cursor }); + // Keeps other editors from opening in the message editor's group. Locking acts on the active group, so it is + // skipped should another group have become active meanwhile. + if (window.tabGroups.activeTabGroup.viewColumn === below) { + await commands.executeCommand("workbench.action.lockEditorGroup"); + } + // Showing the message in its place first leaves the document open, so closing the other tabs asks nothing + await this.closeTabs(() => (paneViewColumn(this.panel) ?? 0) + 1); + if (!focus) { + this.panel.reveal(undefined, false); + await waitFor(() => this.panel.active, [this.panel.onDidChangeViewState], 500); + } else if (await waitFor(() => this.panel.active, [this.panel.onDidChangeViewState], 500)) { + // The webview takes the focus a moment after the pane was revealed, by StGit or just before by the + // splitting, so the message editor takes it back. Focus moved anywhere else is left alone. + const column = (paneViewColumn(this.panel) ?? 0) + 1; + await window.showTextDocument(document, { viewColumn: column, preview: false, selection: this.cursor ?? cursor }); + } + this.movedAt = Date.now(); + } + + // A layout that keeps undoing the move would otherwise make the editor jump back and forth forever + private movedTooOften(): boolean { + const now = Date.now(); + this.moves = this.moves.filter((time) => now - time < 5000); + if (this.moves.length >= 3) { + log("Stopped moving the commit message editor back under the StGit pane"); + return true; + } + this.moves.push(now); + return false; + } + + // Opens an empty group right under the pane. Coming right after the pane's group in view column order, it is + // opened by that column and not as the active group, because the pane's webview can take the activation back. + private async splitBelowPane(pane: vscode.ViewColumn): Promise { + // A new group can only be split off the active one, and only focusing the pane makes its group active. It is + // revealed in its current column, as the panel's own viewColumn may be out of date and would move the pane. + const paneActive = () => window.tabGroups.activeTabGroup.tabs.some(isStGitPane); + if (!paneActive()) { + this.panel.reveal(undefined, false); + } + if (!(await waitFor(paneActive, [window.tabGroups.onDidChangeTabGroups, window.tabGroups.onDidChangeTabs, this.panel.onDidChangeViewState]))) { + return false; + } + await commands.executeCommand("workbench.action.newGroupBelow"); + const layout = await commands.executeCommand("vscode.getEditorLayout"); + const group = window.tabGroups.all.find((candidate) => candidate.viewColumn === pane + 1); + return paneViewColumn(this.panel) === pane && group?.tabs.length === 0 && (isStackedBelow(layout, pane - 1) ?? true); + } + + // Closes the message's tabs, along with any group they would leave empty, except the one in the column given. + // That column is asked for again after every close, as closing a group renumbers the groups after it. + private async closeTabs(keptColumn?: () => number) { + for (let attempt = 0; attempt < 5; attempt++) { + const kept = keptColumn?.(); + const tab = this.tabs().find((candidate) => candidate.group.viewColumn !== kept); + if (!tab) { + return; + } + if (tab.group.tabs.length === 1) { + await window.tabGroups.close(tab.group, true); + } else { + await window.tabGroups.close(tab, true); + } + } + } +} diff --git a/src/mutation-gate.ts b/src/mutation-gate.ts index c287bee..7926c1e 100644 --- a/src/mutation-gate.ts +++ b/src/mutation-gate.ts @@ -1,3 +1,23 @@ +// StGit commands that leave the repository alone. Any command not listed here is a mutation. +export const viewCommands = { + // Only change what the pane shows, so they can run at any time + immediate: [ + "toggleExpand", + "markPatch", + "unmarkPatch", + "cancelHighlighting", + "toggleShowingUnknown", + "setHistorySize", + "openDiffEditor", + "showDiff", + "openDiff", + "copyCommitSha", + "help", + ], + // Open or close the commit message editor, which must not overtake a mutation that is still running + queued: ["createPatch", "editCommitMessage", "cancel", "discardCommitMessage"], +}; + export class MutationGate { private pending = 0; private tail: Promise = Promise.resolve(); @@ -12,16 +32,28 @@ export class MutationGate { if (this.pending === 1) { this.pause(); } - const current = this.tail.then(action); - this.tail = current.then( - () => undefined, - () => undefined, - ); - return current.finally(() => { + return this.after(action).finally(() => { this.pending--; if (this.pending === 0) { this.resume(); } }); } + + // Runs once the mutations queued so far have finished, without pausing or resuming anything + after(action: () => T | Promise): Promise { + const current = this.tail.then(action); + this.tail = current.then( + () => undefined, + () => undefined, + ); + return current; + } + + command(name: string, action: () => T | Promise): T | Promise { + if (viewCommands.immediate.includes(name)) { + return action(); + } + return viewCommands.queued.includes(name) ? this.after(action) : this.run(action); + } } diff --git a/src/patch-template.ts b/src/patch-template.ts new file mode 100644 index 0000000..6ee48ba --- /dev/null +++ b/src/patch-template.ts @@ -0,0 +1,28 @@ +// Commit messages are written in the template that `stg new` and `stg edit` open in an editor, and StGit reads them +// back from it with --file: Patch, Author and Date lines, then the message, then comment lines starting with '#'. + +// The lines of the template and the number of header lines at the top +function header(template: string): [string[], number] { + const lines = template.replace(/\r\n/g, "\n").split("\n"); + let count = 0; + while (count < lines.length && /^(Patch|Author|Date):/.test(lines[count])) { + count++; + } + return [lines, count]; +} + +// The message itself, as StGit takes it from the template +export function templateMessage(template: string): string { + const [lines, start] = header(template); + return lines + .slice(start) + .filter((line) => !line.startsWith("#")) + .join("\n") + .trim(); +} + +// The line the message starts on: after the header and the empty line below it +export function templateMessageLine(template: string): number { + const [lines, count] = header(template); + return count > 0 && lines[count] === "" ? count + 1 : count; +} diff --git a/src/repo-reader.ts b/src/repo-reader.ts index 5da2cd4..b8239c4 100644 --- a/src/repo-reader.ts +++ b/src/repo-reader.ts @@ -1,7 +1,11 @@ import type { run, runCommand } from "./util"; +const COMMIT_FILE_CACHE_LIMIT = 500; + export class RepoReader { readonly cwd: string; + private readonly commitFiles = new Map(); + private readonly commitFileReads = new Map>(); constructor( repo: { topLevelDir: string }, @@ -20,37 +24,93 @@ export class RepoReader { runCommand(command: Parameters[0], args: string[], opts?: Parameters[2]) { return this.commands.runCommand(command, args, { ...opts, env: { GIT_OPTIONAL_LOCKS: "0", ...opts?.env }, cwd: this.cwd }); } + + cachedCommitFiles(sha: string): string | undefined { + return this.commitFiles.get(sha); + } + + readCommitFiles(sha: string): Promise { + const cached = this.commitFiles.get(sha); + if (cached !== undefined) { + this.commitFiles.delete(sha); + this.commitFiles.set(sha, cached); + return Promise.resolve(cached); + } + const pending = this.commitFileReads.get(sha); + if (pending) { + return pending; + } + const read = this.runCommand("git", ["diff-tree", "--find-renames", "-z", "--no-commit-id", "-r", sha]) + .then((result) => { + if (result.ecode !== 0) { + throw new Error(result.stderr || `git diff-tree failed with exit code ${result.ecode}`); + } + const files = result.stdout; + this.commitFiles.set(sha, files); + if (this.commitFiles.size > COMMIT_FILE_CACHE_LIMIT) { + const oldest = this.commitFiles.keys().next().value; + if (oldest !== undefined) { + this.commitFiles.delete(oldest); + } + } + return files; + }) + .finally(() => this.commitFileReads.delete(sha)); + this.commitFileReads.set(sha, read); + return read; + } } export class LatestLoad { private version = 0; + private loading = false; + + constructor(private readonly onLoadingChange: (loading: boolean) => void = () => undefined) {} + + private setLoading(loading: boolean) { + if (this.loading !== loading) { + this.loading = loading; + this.onLoadingChange(loading); + } + } invalidate() { this.version++; + this.setLoading(false); } async run(read: () => Promise, publish: (value: T) => void, onError: (error: unknown) => void) { const version = ++this.version; - let value: T; + this.setLoading(true); try { - value = await read(); + const value = await read(); + if (version === this.version) { + publish(value); + } } catch (error) { if (version === this.version) { onError(error); } - return; - } - if (version === this.version) { - publish(value); + } finally { + if (version === this.version) { + this.setLoading(false); + } } } } export class RepoDisplayLoads { private reader: RepoReader; - private readonly series = new LatestLoad(); - private readonly changes = new LatestLoad(); + private readonly series = new LatestLoad((loading) => this.updateLoading("series", loading)); + private readonly changes = new LatestLoad((loading) => this.updateLoading("changes", loading)); private paused = false; + private disposed = false; + private seriesLoading = false; + private changesLoading = false; + private prefetchQueue: string[] = []; + private prefetchTimer: NodeJS.Immediate | undefined; + private prefetchRunning = 0; + private prefetched: (() => void) | undefined; constructor( repo: { topLevelDir: string }, @@ -59,44 +119,107 @@ export class RepoDisplayLoads { runCommand: typeof runCommand; }, private readonly onError: (kind: "series" | "changes", error: unknown) => void, + private readonly onLoadingChange: (loading: boolean) => void = () => undefined, ) { this.reader = new RepoReader(repo, commands); } + private updateLoading(kind: "series" | "changes", loading: boolean) { + const wasLoading = this.seriesLoading || this.changesLoading; + if (kind === "series") { + this.seriesLoading = loading; + } else { + this.changesLoading = loading; + } + const isLoading = this.seriesLoading || this.changesLoading; + if (wasLoading !== isLoading && !this.disposed) { + this.onLoadingChange(isLoading); + } + } + get currentReader() { return this.reader; } pause() { this.paused = true; + this.cancelPrefetch(); this.series.invalidate(); this.changes.invalidate(); } resume() { + if (this.disposed) { + return; + } this.paused = false; } switchRepository(repo: { topLevelDir: string }) { + this.cancelPrefetch(); this.series.invalidate(); this.changes.invalidate(); this.reader = new RepoReader(repo, this.commands); } - loadSeries(read: (reader: RepoReader) => Promise, publish: (value: T) => void) { - if (this.paused) { + // `prefetched` is called once when every commit selected by `prefetch` has been read, unless the batch is cancelled first + loadSeries(read: (reader: RepoReader) => Promise, publish: (value: T) => void, prefetch?: (value: T) => string[], prefetched?: () => void) { + if (this.paused || this.disposed) { return Promise.resolve(); } + this.cancelPrefetch(); const reader = this.reader; return this.series.run( () => read(reader), - publish, + (value) => { + publish(value); + if (prefetch && reader === this.reader && !this.paused && !this.disposed) { + this.prefetchQueue = [...new Set(prefetch(value))].slice(0, COMMIT_FILE_CACHE_LIMIT); + this.prefetched = prefetched; + this.prefetchTimer = setImmediate(() => { + this.prefetchTimer = undefined; + this.drainPrefetch(); + }); + } + }, (error) => this.onError("series", error), ); } + private cancelPrefetch() { + this.prefetchQueue = []; + this.prefetched = undefined; + if (this.prefetchTimer) { + clearImmediate(this.prefetchTimer); + this.prefetchTimer = undefined; + } + } + + private drainPrefetch() { + if (this.paused || this.disposed || this.prefetchTimer) { + return; + } + while (this.prefetchRunning < 2 && this.prefetchQueue.length) { + const sha = this.prefetchQueue.shift()!; + const reader = this.reader; + this.prefetchRunning++; + void reader + .readCommitFiles(sha) + .catch(() => undefined) + .finally(() => { + this.prefetchRunning--; + this.drainPrefetch(); + }); + } + if (!this.prefetchRunning) { + const prefetched = this.prefetched; + this.prefetched = undefined; + prefetched?.(); + } + } + loadChanges(read: (reader: RepoReader) => Promise, publish: (value: T) => void) { - if (this.paused) { + if (this.paused || this.disposed) { return Promise.resolve(); } const reader = this.reader; @@ -108,6 +231,8 @@ export class RepoDisplayLoads { } dispose() { + this.disposed = true; + this.cancelPrefetch(); this.series.invalidate(); this.changes.invalidate(); } diff --git a/src/stgit-webview.ts b/src/stgit-webview.ts new file mode 100644 index 0000000..61b29fd --- /dev/null +++ b/src/stgit-webview.ts @@ -0,0 +1,133 @@ +import type * as vscode from "vscode"; + +export interface StGitViewRow { + id: string; + kind: string; + symbol: string; + description: string; + expanded: boolean; + marked: boolean; + empty: boolean; + highlighted: boolean; + files: { path: string; name: string; status: string; kind: string; highlighted: boolean; submodule?: boolean }[]; + // The commit message, and so the description, is empty + noMessage?: boolean; +} + +export interface StGitViewState { + branch: string; + submodule: string; + notice: string; + noticeCommand: string; + rows: StGitViewRow[]; + selected: { patchId: string; path?: string }; + selectionVersion: number; + loading: boolean; + // The message itself is written in a text editor of its own + editing: { kind: "create" | "edit" } | null; + // Number of files per row id; kept apart from the rows so that a new count does not redraw a row + fileCounts: Record; +} + +export interface StGitNavigation { + type: "navigate"; + target: StGitViewState["selected"] | { path: string }; + selectionVersion: number; +} + +// View state that lives in the webview; saved with setState() because VS Code recreates the webview when it is hidden or moved +export interface StGitWebviewState { + cursor?: Pick; + scrollY?: number; +} + +// Saved state may come from another version of the webview, so each field is kept only if it has the expected shape +export function parseStGitWebviewState(raw: unknown): StGitWebviewState { + const { cursor, scrollY } = (raw && typeof raw === "object" ? raw : {}) as Record; + const state: StGitWebviewState = {}; + if (typeof cursor?.selected?.patchId === "string" && ["string", "undefined"].includes(typeof cursor.selected.path) && Number.isSafeInteger(cursor.selectionVersion)) { + state.cursor = cursor; + } + if (typeof scrollY === "number") { + state.scrollY = scrollY; + } + return state; +} + +export function reconcileStGitSelection(selected: StGitViewState["selected"], previous: StGitViewRow[], rows: StGitViewRow[]): StGitViewState["selected"] { + const patch = rows.find((row) => row.id === selected.patchId); + const oldPatch = previous.find((row) => row.id === selected.patchId); + if (patch) { + if (selected.path === undefined || (patch.expanded && patch.files.some((file) => file.path === selected.path))) { + return selected; + } + if (patch.expanded && patch.files.length) { + const oldFiles = oldPatch?.files ?? []; + const index = oldFiles.findIndex((file) => file.path === selected.path); + const candidates = [...oldFiles.slice(index + 1), ...oldFiles.slice(0, Math.max(0, index)).reverse()]; + const nearest = candidates.find((candidate) => patch.files.some((file) => file.path === candidate.path)) ?? patch.files[0]; + return { patchId: patch.id, path: nearest.path }; + } + return { patchId: patch.id }; + } + const index = previous.findIndex((row) => row.id === selected.patchId); + const candidates = [...previous.slice(index + 1), ...previous.slice(0, Math.max(0, index)).reverse()]; + const nearest = candidates.find((candidate) => rows.some((row) => row.id === candidate.id)) ?? rows.find((row) => row.kind === "I") ?? rows[0]; + return nearest ? { patchId: nearest.id } : selected; +} + +function reuseUnchanged(previous: T | undefined, incoming: T): T { + const fields = Object.keys(incoming) as (keyof T)[]; + return previous && + fields.length === Object.keys(previous).length && + fields.every((field) => Object.prototype.hasOwnProperty.call(previous, field) && previous[field] === incoming[field]) + ? previous + : incoming; +} + +function reconcileItems(previous: T[], incoming: T[], key: (item: T) => string, reconcile: (previous: T | undefined, incoming: T) => T = reuseUnchanged): T[] { + const byKey = new Map(previous.map((item) => [key(item), item])); + const items = incoming.map((item) => reconcile(byKey.get(key(item)), item)); + return items.length === previous.length && items.every((item, index) => item === previous[index]) ? previous : items; +} + +export function reconcileStGitViewState(previous: StGitViewState | null, incoming: StGitViewState): StGitViewState { + if (!previous) { + return incoming; + } + const rows = reconcileItems( + previous.rows, + incoming.rows, + (row) => row.id, + (oldRow, row) => { + if (!oldRow) { + return row; + } + const files = reconcileItems(oldRow.files, row.files, (file) => file.path); + return reuseUnchanged(oldRow, { ...row, files }); + }, + ); + const selected = reuseUnchanged(previous.selected, incoming.selected); + const editing = previous.editing && incoming.editing ? reuseUnchanged(previous.editing, incoming.editing) : incoming.editing; + const fileCounts = reuseUnchanged(previous.fileCounts, incoming.fileCounts); + return reuseUnchanged(previous, { ...incoming, rows, selected, editing, fileCounts }); +} + +export function stgitWebviewHtml(webview: vscode.Webview, assets: { script: vscode.Uri; style: vscode.Uri }): string { + const style = webview.asWebviewUri(assets.style); + const script = webview.asWebviewUri(assets.script); + return ` + + + + + + StGit + + + + +
+ +`; +} diff --git a/src/stgit.ts b/src/stgit.ts index a1187d6..5e4179b 100644 --- a/src/stgit.ts +++ b/src/stgit.ts @@ -3,18 +3,22 @@ import * as vscode from "vscode"; import { commands, window, workspace } from "vscode"; -import { CommentDraft, confirmCommentDiscard } from "./comment-discard"; +import { formatUpstream } from "./branch-label"; +import { confirmCommentDiscard } from "./comment-discard"; import { getStGitConfig } from "./config"; import { openAndShowDiffDocument, refreshDiff } from "./diff-provider"; +import { EditorLayout, addColumnOnRight } from "./editor-layout"; import { getUserConfirmation, info, log, showStatusMessage } from "./extension"; import { uncommitFiles } from "./git"; +import { MessageEditor, paneViewColumn, registerMessageFileSystem } from "./message-editor"; import { MutationGate } from "./mutation-gate"; +import { templateMessage, templateMessageLine } from "./patch-template"; import { RepositoryInfo } from "./repo"; import { RepoDisplayLoads, RepoReader } from "./repo-reader"; import { RepositoryFollower } from "./repository-follower"; -import { correspondingLine, nextStagedFileLine, remainingIndexFileLine } from "./stage-selection"; import { StGitStateMonitor, readRepositoryState } from "./state-monitor"; -import { run, runAndReportErrors, runCommand, sleep } from "./util"; +import { StGitNavigation, StGitViewState, stgitWebviewHtml } from "./stgit-webview"; +import { run, runAndReportErrors, runCommand } from "./util"; const RENAMEOPTS: readonly string[] = ["--find-renames"]; @@ -105,6 +109,13 @@ export class Delta { } return `${s2.padEnd(50)} ${sinfo}`; } + get statusLabel() { + const similarity = this.status === "R" ? ` ${Number(this.score)}%` : ""; + return `${Delta.STATUS_MESSAGE[this.status]}${similarity}${this.permissionDelta}${this.stageInfoString ? ` ${this.stageInfoString}` : ""}`; + } + get kind() { + return this.status; + } static fromDiff(diffOutput: string): Delta[] { const entries: Delta[] = []; for (let s = diffOutput; ;) { @@ -156,11 +167,43 @@ abstract class Patch { private readonly symbol: "+" | "-" | ">" | " " = " ", ) {} - async updateFromOld(old: Patch) { + get rowId(): string { + const namespace = this.kind === "+" || this.kind === "-" ? "P" : this.kind; + return `${namespace}:${this.kind === "H" ? this.sha : this.label}`; + } + + get commitSha(): string | null { + return this.sha; + } + + get isExpanded(): boolean { + return this.expanded; + } + + get statusSymbol(): string { + return this.symbol; + } + + // Takes over the view state of the row this patch replaces, which the user may have changed while this patch was loading + inherit(old: Patch, redraw: () => void) { this.marked = old.marked; - if (this.expanded !== old.expanded) { - await this.toggleExpanded(); + this.expanded = old.expanded; + if (this.expanded && !this.detailsFetcher) { + // Keep showing the previous files until this patch's own have been read + this.deltas = old.deltas; + void this.fetchDetails().then(redraw, () => undefined); + } + } + + // Takes the commit's files from the cache if they were read before, e.g. by the prefetch; tells whether it did + useCachedFiles(): boolean { + const files = this.detailsFetcher || !this.sha ? undefined : this.reader.cachedCommitFiles(this.sha); + if (files === undefined) { + return false; } + this.deltas = Delta.fromDiff(files); + this.detailsFetcher = Promise.resolve(); + return true; } getLines(): string[] { const m = this.marked ? "*" : " "; @@ -195,7 +238,10 @@ abstract class Patch { fetchDetails(): Promise { if (!this.detailsFetcher) { - this.detailsFetcher = this.doFetchDetails(); + this.detailsFetcher = this.doFetchDetails().catch((error) => { + this.detailsFetcher = null; + throw error; + }); } return this.detailsFetcher; } @@ -215,9 +261,13 @@ abstract class Patch { return this.commitMessage; } + // The state changes at once, so that a reload in between cannot lose it; the promise settles when the files are known async toggleExpanded() { - await this.fetchDetails(); this.expanded = !this.expanded; + await this.fetchDetails().catch((error) => { + this.expanded = false; + throw error; + }); } } @@ -243,8 +293,8 @@ export class StGitPatch extends Patch { return patch; } protected async doFetchDetails(): Promise { - this.sha = await this.reader.run("stg", ["id", "--", this.label]); - const tree = await this.reader.run("git", ["diff-tree", ...RENAMEOPTS, "-z", "--no-commit-id", "-r", this.sha]); + this.sha ??= await this.reader.run("stg", ["id", "--", this.label]); + const tree = await this.reader.readCommitFiles(this.sha); this.deltas = Delta.fromDiff(tree); } } @@ -270,7 +320,13 @@ export class WorkTree extends Patch { } protected async doFetchDetails(): Promise { const result = await Promise.all([this.reader.run("git", ["diff", "--raw", "--no-renames", "-z"]), this.fetchUnknownFiles()]); - this.deltas = Delta.fromDiff(result.join("")); + const byPath = new Map(); + for (const delta of Delta.fromDiff(result.join(""))) { + if (!byPath.has(delta.path) || delta.conflict) { + byPath.set(delta.path, delta); + } + } + this.deltas = [...byPath.values()]; } } @@ -344,7 +400,7 @@ export class History extends Patch { return lines; } protected async doFetchDetails(): Promise { - const tree = await this.reader.run("git", ["diff-tree", ...RENAMEOPTS, "-z", "--no-commit-id", "-r", this.sha]); + const tree = await this.reader.readCommitFiles(this.sha); this.deltas = Delta.fromDiff(tree); } static async fromRev(reader: RepoReader, rev: string, limit: number) { @@ -373,13 +429,23 @@ class StGitDoc { () => { this.monitor.pause(); this.displayLoads.pause(); + this.running = true; + this.notifyDirty(); }, () => { + if (this.disposed) { + return; + } this.monitor.resume(); this.displayLoads.resume(); this.reload(); + this.running = false; + this.notifyDirty(); }, ); + private running = false; + private loading = false; + private disposed = false; private unknownFilesVisible = false; private monitor: StGitStateMonitor; private displayLoads: RepoDisplayLoads; @@ -389,6 +455,8 @@ class StGitDoc { private popped: Patch[] = []; private index: Patch; private workTree: Patch; + private selectedRow: { patchId: string; path?: string } = { patchId: "I:" }; + private selectionVersion = 0; private needRepair = false; private stgMissing = false; private branchInitialized = true; @@ -412,62 +480,33 @@ class StGitDoc { // start of history private baseSha: string | null = null; - private commentThread: vscode.CommentThread | null = null; - private commentDraft: CommentDraft | null = null; - - // Patch being edited in editor - private editPatch: Patch | null = null; - - private mainViewColumn = window.tabGroups.all.length; - - private subscriptions: vscode.Disposable[] = []; + private editing: { kind: "create" | "edit"; initialBody: string; patch: Patch | null; editor: MessageEditor } | null = null; - private highlightRanges: vscode.Range[] = []; - private historyRanges: vscode.Range[] = []; + private get mainViewColumn(): vscode.ViewColumn { + return paneViewColumn(this.panel) ?? vscode.ViewColumn.One; + } constructor( - public doc: vscode.TextDocument, + public panel: vscode.WebviewPanel, public repo: RepositoryInfo, public notifyDirty: () => void, - private commentController: vscode.CommentController, + private readonly navigate: (target: StGitNavigation["target"], selectionVersion: number) => void, ) { - this.displayLoads = new RepoDisplayLoads(repo, { run, runCommand }, (kind, error) => log(`StGit ${kind} reload failed:`, String(error))); + this.displayLoads = new RepoDisplayLoads( + repo, + { run, runCommand }, + (kind, error) => log(`StGit ${kind} reload failed:`, String(error)), + (loading) => { + this.loading = loading; + this.notifyDirty(); + }, + ); this.index = new Index(this.reader); this.workTree = new WorkTree(this.reader, this.unknownFilesVisible); - this.subscriptions.push( - window.onDidChangeVisibleTextEditors((editors) => { - this.updateEditorDecorations(); - for (const e of editors) { - if (e.document === this.doc && e.viewColumn) { - this.mainViewColumn = e.viewColumn; - break; - } - } - }), - workspace.onDidChangeTextDocument((ev) => { - if (ev.document === this.doc) { - this.updateEditorDecorations(); - } - }), - workspace.onDidOpenTextDocument((document) => { - if (window.activeTextEditor?.document === this.doc) { - this.commentDraft?.trackDocument(document); - } - }), - // this event fires when an entire tab group is added or removed - window.onDidChangeTextEditorViewColumn((ev) => { - if (ev.textEditor.document === this.doc) { - this.mainViewColumn = ev.viewColumn; - } - }), - getStGitConfig().onDidChangeConfiguration(() => { - this.updateConfiguration({ reload: true }); - }), - ); + this.configListener = getStGitConfig().onDidChangeConfiguration(() => this.updateConfiguration({ reload: true })); this.updateConfiguration({ reload: false }); this.setupSubmoduleContext(repo); this.reload(); - this.openInitialEditor(); this.monitor = new StGitStateMonitor(repo, { readState: (currentRepo) => readRepositoryState(currentRepo, runCommand), watchFiles: (currentRepo, changed) => { @@ -483,10 +522,15 @@ class StGitDoc { }); this.monitor.start(); } + private configListener: vscode.Disposable; dispose() { + this.disposed = true; this.displayLoads.dispose(); this.monitor.dispose(); - this.subscriptions.forEach((s) => s.dispose()); + this.configListener.dispose(); + void this.editing?.editor.close(); + this.editing = null; + void commands.executeCommand("setContext", "stgitEditing", false); } private get reader() { @@ -497,9 +541,65 @@ class StGitDoc { return this.mutations.run(action); } + runCommand(name: string, action: () => T | Promise): T | Promise { + return this.mutations.command(name, action); + } + private get patches() { return [...this.history, ...this.applied, this.index, this.workTree, ...this.popped]; } + + selectRow(patchId: string, path: string | undefined, selectionVersion: number) { + if (selectionVersion < this.selectionVersion) { + return; + } + this.selectionVersion = selectionVersion; + if (!this.patches.some((patch) => patch.rowId === patchId && (path === undefined || patch.deltas.some((delta) => delta.path === path)))) { + this.notifyDirty(); + return; + } + this.selectedRow = { patchId, path }; + } + + get viewState(): StGitViewState { + return { + branch: `${this.branchName ?? this.baseSha?.slice(0, 16) ?? ""}${this.upstreamString}`, + submodule: this.relativePathFromRoot, + notice: this.stgMissing + ? "StGit is not installed (stg binary missing)" + : !this.branchInitialized + ? "Initialize this branch for StGit" + : this.needRepair + ? "StGit repair needed (Ctrl+U G)" + : "", + noticeCommand: this.stgMissing ? "" : !this.branchInitialized ? "stgit.initializeBranch" : this.needRepair ? "stgit.repair" : "", + selected: this.selectedRow, + selectionVersion: this.selectionVersion, + loading: this.running || this.loading, + editing: this.editing && { kind: this.editing.kind }, + rows: this.patches.map((patch) => ({ + id: patch.rowId, + kind: patch.kind, + symbol: patch.statusSymbol || (patch.kind === "I" ? "◫" : patch.kind === "W" ? "◇" : "○"), + description: patch.description, + noMessage: patch.kind !== "I" && patch.kind !== "W" && !patch.description, + expanded: patch.isExpanded, + marked: patch.marked, + empty: patch.empty, + highlighted: this.applied.includes(patch) && patch.deltas.some((delta) => this.highlightPaths?.has(delta.path)), + // A collapsed row only shows how many files it has + files: (patch.isExpanded ? patch.deltas : []).map((delta) => ({ + path: delta.path, + name: `${delta.path}${delta.destPath ? ` → ${delta.destPath}` : ""}`, + status: delta.statusLabel, + kind: delta.kind, + highlighted: this.highlightPaths?.has(delta.path) ?? false, + submodule: delta.isSubmodule, + })), + })), + fileCounts: Object.fromEntries(this.patches.map((patch) => [patch.rowId, patch.deltas.length])), + }; + } private updateConfiguration(opt: { reload: boolean }) { const config = getStGitConfig(); this.unknownFilesVisible = config.showUnknownFiles; @@ -515,12 +615,17 @@ class StGitDoc { } this.parentRepoStack = stack; this.relativePathFromRoot = relativePath; + this.notifyDirty(); } switchRepository(repo: RepositoryInfo, context: Awaited>) { if (this.repo.gitDir === repo.gitDir) { return; } + if (this.editing) { + info("Finish or cancel the commit message before switching repositories."); + return; + } this.displayLoads.switchRepository(repo); this.repo = repo; RepositoryInfo.setSelectedRepo(repo); @@ -532,6 +637,7 @@ class StGitDoc { this.popped = []; this.index = new Index(this.reader); this.workTree = new WorkTree(this.reader, this.unknownFilesVisible); + this.selectedRow = { patchId: this.index.rowId }; this.baseSha = null; this.branchName = null; this.remoteName = null; @@ -542,10 +648,14 @@ class StGitDoc { this.branchInitialized = true; this.highlightPaths = null; this.notifyDirty(); + this.navigate({ patchId: this.index.rowId }, this.selectionVersion); this.reload(); } reload() { + if (this.disposed) { + return; + } void this.displayLoads.loadSeries( (reader) => this.readSeries(reader), (state) => { @@ -560,6 +670,14 @@ class StGitDoc { if (this.stgMissing) { this.warnAboutMissingStGit(); } + const shown = new Map(this.patches.map((patch) => [patch.rowId, patch])); + for (const patch of [...state.patches, ...state.history]) { + patch.useCachedFiles(); + const old = shown.get(patch.rowId); + if (old && old !== patch) { + patch.inherit(old, this.notifyDirty); + } + } this.popped = state.patches.filter((p) => p.kind === "-"); this.applied = state.patches.filter((p) => p.kind !== "-"); this.baseSha = state.baseSha; @@ -568,12 +686,18 @@ class StGitDoc { this.needRepair = state.needRepair; this.notifyDirty(); }, + (state) => [...state.patches, ...state.history.slice().reverse()].flatMap((patch) => (patch.commitSha ? [patch.commitSha] : [])), + () => { + // The file counts of the commits that had to be read appear together, in a single redraw + if (this.patches.filter((patch) => patch.useCachedFiles()).length) { + this.notifyDirty(); + } + }, ); this.reloadIndexAndWorkTree(); } private async readSeries(reader: RepoReader) { - const old = new Map(this.patches.map((p) => [p.label, p])); const [branch, upstream, series, base, top, gitHead] = await Promise.all([ reader.run("git", ["symbolic-ref", "--short", "HEAD"]), reader.run("git", ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], { inhibitLogging: true }), @@ -595,17 +719,9 @@ class StGitDoc { const sha = line.slice(3, 43); return StGitPatch.fromSeries(line, messagesBySha.get(sha) ?? "", reader); }); - await Promise.all( - patches.map(async (patch) => { - const previous = old.get(patch.label); - if (previous) { - await patch.updateFromOld(previous); - } - if (this.highlightPaths) { - await patch.fetchDetails(); - } - }), - ); + // Rows that are expanded are published with their files; the files of other rows are read when they are needed + const shown = new Map(this.patches.map((patch) => [patch.rowId, patch])); + await Promise.all(patches.filter((patch) => this.highlightPaths || shown.get(patch.rowId)?.isExpanded).map((patch) => patch.fetchDetails())); const baseSha = base || gitHead; const historySize = this.historySize; const [history, stgHead] = await Promise.all([ @@ -625,14 +741,19 @@ class StGitDoc { } reloadIndexAndWorkTree() { + if (this.disposed) { + return; + } void this.displayLoads.loadChanges( async (reader) => { const index = new Index(reader); const workTree = new WorkTree(reader, this.unknownFilesVisible); - await Promise.all([index.updateFromOld(this.index).then(() => index.fetchDetails()), workTree.updateFromOld(this.workTree).then(() => workTree.fetchDetails())]); + await Promise.all([index.fetchDetails(), workTree.fetchDetails()]); return { index, workTree }; }, (state) => { + state.index.inherit(this.index, this.notifyDirty); + state.workTree.inherit(this.workTree, this.notifyDirty); this.index = state.index; this.workTree = state.workTree; this.notifyDirty(); @@ -744,59 +865,52 @@ class StGitDoc { } this.reload(); } - private async openCommentEditor(line: number, body: string, context: string, editPatch: Patch | null = null) { - if (this.commentThread && !(await this.confirmDiscardComment())) { + private async openCommentEditor(body: string, kind: "create" | "edit", editPatch: Patch | null = null) { + if (this.editing && !(await this.confirmDiscardComment())) { return; } - const comment: vscode.Comment = { - contextValue: context, - body: body, - mode: vscode.CommentMode.Editing, - label: "(use 50/72 format)", - author: { - name: "Commit Message", - }, - }; - this.commentThread?.dispose(); - this.commentDraft = new CommentDraft(body); - const comments: vscode.Comment[] = [comment]; - const pos = new vscode.Position(line, 0); - const range = new vscode.Range(pos, pos); - const thread = this.commentController.createCommentThread(this.doc.uri, range, comments); - thread.label = "Enter commit message:"; - thread.contextValue = context; - thread.canReply = false; - thread.collapsibleState = vscode.CommentThreadCollapsibleState.Collapsed; - thread.state = vscode.CommentThreadState.Unresolved; - this.commentThread = thread; - this.editPatch = editPatch; - - const delay = vscode.env.remoteName ? 400 : 200; - await sleep(delay); - await commands.executeCommand("workbench.action.expandAllComments"); - - // It is difficult to determine when comment editor is really visible. - // This is a workaround which works well in practice. - const next = pos.translate(1); - for (let i = 0; i < 8; i++) { - await sleep(100); - this.editor?.revealRange(new vscode.Range(pos, next)); + await this.editing?.editor.close(); + const onClose = (saved: string) => void this.runMutation(() => this.messageEditorClosed(editor, saved)); + const editor = new MessageEditor(body, this.panel, onClose, templateMessageLine(body)); + this.editing = { kind, initialBody: body, patch: editPatch, editor }; + void commands.executeCommand("setContext", "stgitEditing", true); + this.notifyDirty(); + await editor.open(); + } + async showCommitMessage() { + await this.editing?.editor.open(); + } + // Closing the message editor works like closing the editor of `stg new`: a message that was saved commits, anything else cancels + private async messageEditorClosed(editor: MessageEditor, saved: string) { + const editing = this.editing; + if (editing?.editor !== editor) { + return; + } + const normalize = (text: string) => text.replace(/\r\n/g, "\n"); + if (normalize(saved) !== normalize(editing.initialBody)) { + await this.submitComment(saved); + } else { + await this.closeCommentEditor(); } } + // The message is written in the template that `stg new` and `stg edit` open in an editor, with the patch name, + // author and date above it, which can be changed too, and help below it async createPatch() { - const patch = this.index.deltas.length ? this.index : this.workTree; - const line = patch.lineNum + patch.deltas.length; - await this.openCommentEditor(line, "", "stgit"); + const template = await runAndReportErrors("stg", ["new", "--save-template", "-"], { trim: false }); + if (template.ecode === 0) { + await this.openCommentEditor(template.stdout, "create"); + } } async editCommitMessage() { const p = this.curPatch; if (!p || !["+", "-"].includes(p.kind)) { return; } - const sha = (await p.getSha()) ?? "error retrieving commit message>"; - const msg = await run("git", ["show", "-s", sha, "--format=%B"]); - await this.openCommentEditor(p.lineNum, msg, "stgit-edit", p); + const template = await runAndReportErrors("stg", ["edit", "--save-template", "-", "--", p.label], { trim: false }); + if (template.ecode === 0) { + await this.openCommentEditor(template.stdout, "edit", p); + } } async copyCommitSha() { const sha = await this.curPatch?.getSha(); @@ -806,32 +920,54 @@ class StGitDoc { await vscode.env.clipboard.writeText(sha); showStatusMessage(`Copied commit SHA ${sha}`); } + // Takes the message from the message editor unless given one. The editor always closes: should StGit fail, the + // error offers to bring the message back. + async submitComment(body?: string) { + const editing = this.editing; + if (!editing) { + return; + } + const msg = body ?? editing.editor.text; + await this.closeCommentEditor(); + if (editing.kind === "create" && !templateMessage(msg)) { + // As in the editor of `stg new`. Given the message with --file, StGit would make a patch without one. + showStatusMessage("Empty commit message: no patch created"); + return; + } + const args = editing.kind === "create" ? ["new", "--file", "-"] : ["edit", "--file", "-", "--", editing.patch?.label ?? ""]; + const result = await runCommand("stg", args, { stdin: msg }); + if (result.ecode !== 0) { + log(result.stderr); + const action = editing.kind === "create" ? "create the patch" : `update ${editing.patch?.label}`; + const error = result.stderr.split("\n")[0] || `exit code ${result.ecode}`; + // Not awaited: the notification may stay open long after this mutation should have finished + void window.showErrorMessage(`StGit could not ${action}: ${error}`, "Edit Message Again").then((choice) => { + if (choice) { + void this.runCommand("createPatch", () => this.openCommentEditor(msg, editing.kind, editing.patch)); + } + }); + this.reload(); + } else if (editing.kind === "create") { + // Takes the staged changes, or else all changes in the work tree, into the new patch + await this.refresh(); + } else { + this.reload(); + } + } async commentCreatePatch() { - if (this.commentThread) { - const msg = this.commentThread.comments[0].body; - await this.closeCommentEditor(); - if (msg) { - await run("stg", ["new", "-m", msg as string]); - await this.refresh(); - } + if (this.editing?.kind === "create") { + await this.submitComment(); } } async completePatchEdit() { - if (this.commentThread) { - const msg = this.commentThread.comments[0].body; - const editPatch = this.editPatch; - await this.closeCommentEditor(); - if (msg && editPatch) { - await run("stg", ["edit", "-m", msg as string, "--", editPatch.label]); - this.reload(); - } + if (this.editing?.kind === "edit") { + await this.submitComment(); } } focusWindow() { - return window.showTextDocument(this.doc, { - preview: false, - viewColumn: this.mainViewColumn, - }); + if (!this.disposed) { + this.panel.reveal(); + } } async closeAllDiffEditors() { const editors = window.visibleTextEditors.filter((e) => e.document.uri.scheme === "stgit-diff"); @@ -847,27 +983,34 @@ class StGitDoc { } } private async closeCommentEditor() { - this.commentThread?.dispose(); - this.commentThread = null; - this.commentDraft = null; - this.editPatch = null; + const editor = this.editing?.editor; + this.editing = null; + void commands.executeCommand("setContext", "stgitEditing", false); + this.notifyDirty(); + await editor?.close(); await this.closeAllDiffEditors(); - await this.focusWindow(); + this.focusWindow(); } private confirmDiscardComment(): Promise { - return confirmCommentDiscard(this.commentDraft?.hasChanges ?? false, async () => { + const normalize = (text: string) => text.replace(/\r\n/g, "\n"); + const hasChanges = !!this.editing && normalize(this.editing.editor.text) !== normalize(this.editing.initialBody); + return confirmCommentDiscard(hasChanges, async () => { const choice = await window.showWarningMessage("Close the commit message editor? Unsaved changes may be lost.", { modal: true }, "Discard and Close"); return choice === "Discard and Close"; }); } async cancel() { + if (this.editing?.kind === "create" && !this.editing.editor.text) { + await this.closeCommentEditor(); + return; + } if (!(await this.confirmDiscardComment())) { return; } await this.closeCommentEditor(); } async cancelEmptyComment() { - if (this.commentThread?.contextValue === "stgit") { + if (this.editing?.kind === "create" && !this.editing.editor.text) { await this.closeCommentEditor(); } else { await this.cancel(); @@ -932,7 +1075,7 @@ class StGitDoc { const srcUri = vscode.Uri.parse(`${s}#${delta.srcSha}`); let dstUri = vscode.Uri.parse(`${s}#${delta.destSha}`); const opts: vscode.TextDocumentShowOptions = { - viewColumn: this.alternateViewColumn, + viewColumn: await this.diffViewColumn(), //preserveFocus: true, preview: true, }; @@ -1000,7 +1143,7 @@ class StGitDoc { refreshDiff(uri); } await openAndShowDiffDocument(uri, { - viewColumn: this.alternateViewColumn, + viewColumn: await this.diffViewColumn(), preserveFocus: opts.preserveFocus, }); } @@ -1188,7 +1331,7 @@ class StGitDoc { if (delta) { // Check if the delta is a submodule - if so, navigate into it if (delta.isSubmodule) { - await this.navigateToSubmodule(delta.path); + await this.runMutation(() => this.navigateToSubmodule(delta.path)); return; } const uri = this.repo.getPathUri(delta.path); @@ -1198,21 +1341,12 @@ class StGitDoc { const doc = await workspace.openTextDocument(uri); if (doc) { await window.showTextDocument(doc, { - viewColumn: this.alternateViewColumn, + viewColumn: await this.diffViewColumn(), }); } - } else if (patch && patch.lineNum === this.curLine) { + } else if (patch) { await patch.toggleExpanded(); this.notifyDirty(); - } else { - const line = this.editor?.document.lineAt(this.curLine); - if (line?.text.startsWith("!")) { - if (this.needRepair) { - await this.repair(); - } else if (!this.branchInitialized) { - await this.initializeBranch(); - } - } } } async navigateToSubmodule(submodulePath: string) { @@ -1228,7 +1362,6 @@ class StGitDoc { const context = await RepositoryInfo.buildParentStack(submoduleRepo); this.switchRepository(submoduleRepo, context); - this.moveCursorToIndex(); } async navigateToParent() { if (this.parentRepoStack.length === 0) { @@ -1239,7 +1372,7 @@ class StGitDoc { const parent = this.parentRepoStack.at(-1)!; const context = await RepositoryInfo.buildParentStack(parent.repo); this.switchRepository(parent.repo, context); - void this.moveCursorToDelta(parent.submodulePath); + this.navigate({ path: parent.submodulePath }, this.selectionVersion); } async resolveConflict() { const change = this.curChange; @@ -1256,6 +1389,7 @@ class StGitDoc { // Move changes between index and work tree const patch = this.curPatch; const change = this.curChange; + const selectionVersion = this.selectionVersion; if (change?.conflict) { info("Conflicts must be marked as resolved (shift-R)."); return; @@ -1267,12 +1401,7 @@ class StGitDoc { } else { await run("git", ["add", "--", change.path, ...(change.destPath ? [change.destPath] : [])]); } - const editor = this.editor; - const nextLine = nextStagedFileLine(patch.lineNum, patch.deltas.indexOf(change), patch.deltas.length); - if (editor && nextLine !== undefined) { - const pos = new vscode.Position(nextLine, editor.selection.active.character); - editor.selection = new vscode.Selection(pos, pos); - } + this.navigate({ patchId: patch.rowId, path: patch.deltas[patch.deltas.indexOf(change) + 1]?.path }, selectionVersion); } else { await run("git", ["add", "-u"]); } @@ -1280,12 +1409,8 @@ class StGitDoc { } else if (patch?.kind == "I") { if (change) { await run("git", ["restore", "-S", "--", change.path, ...(change.destPath ? [change.destPath] : [])]); - const editor = this.editor; - if (editor) { - const line = remainingIndexFileLine(patch.lineNum, patch.deltas.indexOf(change), patch.deltas.length); - const pos = new vscode.Position(line, editor.selection.active.character); - editor.selection = new vscode.Selection(pos, pos); - } + const index = patch.deltas.indexOf(change); + this.navigate({ patchId: patch.rowId, path: patch.deltas[index > 0 ? index - 1 : 1]?.path }, selectionVersion); } else { await run("git", ["reset", "HEAD"]); } @@ -1382,207 +1507,40 @@ class StGitDoc { const curPatch = this.curPatch; const ind = list.findIndex((p) => p === curPatch); const nextPatch = list[ind + 1]; - if (this.editor) { - const line = nextPatch ? nextPatch.lineNum : this.curLine + 1; - const pos = new vscode.Position(line, 2); - this.editor.selection = new vscode.Selection(pos, pos); - } - } - - private async openInitialEditor() { - const editor = await window.showTextDocument(this.doc, { - viewColumn: this.mainViewColumn, - preview: false, - }); - const opts = editor.options; - opts.lineNumbers = vscode.TextEditorLineNumbersStyle.Off; - opts.cursorStyle = vscode.TextEditorCursorStyle.Block; - - // move cursor to Index - this.moveCursorToIndexAtOpen(editor); - } - - private async moveCursorToIndex() { - const editor = this.editor; - if (!editor) { - return; - } - this.moveCursorToIndexAtOpen(editor); - } - - private async moveCursorToDelta(path: string) { - const editor = this.editor; - if (!editor) { - return; - } - // The work tree deltas may load after several document - // updates, so keep trying on each update until found. - let resolve: () => void; - const found = new Promise((r) => { - resolve = r; - }); - const watcher = workspace.onDidChangeTextDocument((e) => { - if (e.document !== this.doc) { - return; - } - for (const p of this.patches) { - const idx = p.deltas.findIndex((d) => d.path === path); - if (idx < 0) { - continue; - } - const line = p.lineNum + idx + 1; - const pos = new vscode.Position(line, 0); - editor.selection = new vscode.Selection(pos, pos); - editor.revealRange(new vscode.Range(pos, pos)); - resolve(); - return; - } - }); - const winner = await Promise.race([found.then(() => "found" as const), sleep(4000).then(() => "timeout" as const)]); - watcher.dispose(); - if (winner === "timeout") { - this.moveCursorToIndex(); - } - } - - private async moveCursorToIndexAtOpen(editor: vscode.TextEditor) { - let resolve: () => void; - const found = new Promise((r) => { - resolve = r; - }); - const watcher = workspace.onDidChangeTextDocument((e) => { - if (e.document !== this.doc) { - return; - } - const line = this.index.lineNum; - if (line === 0) { - return; - } - const p = new vscode.Position(line, 0); - editor.selection = new vscode.Selection(p, p); - editor.revealRange(new vscode.Range(p, p)); - resolve(); - }); - const winner = await Promise.race([found.then(() => "found" as const), sleep(4000).then(() => "timeout" as const)]); - watcher.dispose(); - if (winner === "timeout") { - this.moveCursorToIndex(); - } - } - - private updateDecorations() { - this.highlightRanges = this.applied.filter((p) => p.deltas.some((d) => this.highlightPaths?.has(d.path))).map((p) => new vscode.Range(p.lineNum, 2, p.lineNum, 2)); - this.historyRanges = this.history.map((p) => new vscode.Range(p.lineNum, 0, p.lineNum, 999)); - this.updateEditorDecorations(); - } - - private updateEditorDecorations() { - for (const editor of window.visibleTextEditors) { - if (editor.document !== this.doc) { - continue; - } - - const cls = StGitMode.instance!; - editor.setDecorations(cls.fileHighlightDecoration, this.highlightRanges); - editor.setDecorations(cls.historyDecoration, this.historyRanges); - } - } - - get editor(): vscode.TextEditor | null { - const active = window.activeTextEditor; - if (active?.document === this.doc) { - return active; - } else { - return window.visibleTextEditors.find((e) => e.document === this.doc) ?? null; - } - } - private get curLine(): number { - return this.editor?.selection.active.line ?? -1; + this.navigate({ patchId: nextPatch?.rowId ?? curPatch?.rowId ?? this.index.rowId }, this.selectionVersion); } private get curPatch(): Patch | null { - const line = this.curLine; - for (const p of this.patches) { - if (p.lineNum <= line && line < p.lineNum + p.lineCount) { - return p; - } - } - return null; + return this.patches.find((patch) => patch.rowId === this.selectedRow.patchId) ?? null; } private get curChange(): Delta | null { - const line = this.curLine; - for (const p of this.patches) { - if (p.lineNum < line && line < p.lineNum + p.lineCount) { - return p.deltas[line - p.lineNum - 1] ?? null; - } - } - return null; - } - get alternateViewColumn() { - const col = this.mainViewColumn; - return col > 1 ? col - 1 : col + 1; + return this.curPatch?.deltas.find((delta) => delta.path === this.selectedRow.path) ?? null; } - - private get upstreamString(): string { - if (this.remoteBranch && this.remoteName) { - return ` <-> ${this.remoteName}/${this.remoteBranch}`; - } - if (this.remoteName) { - return ` (${this.remoteName})`; + // Next to the StGit pane, but never the commit message editor's group under it + private async diffViewColumn(): Promise { + const pane = this.mainViewColumn; + const message = this.editing?.editor.viewColumn; + const column = (pane > 1 ? [pane - 1, pane + 1, pane + 2] : [pane + 1, pane + 2]).find((candidate) => candidate !== message) as vscode.ViewColumn; + if (message === pane + 1 && column === pane + 2 && window.tabGroups.all.length === 2) { + // VS Code would put the new group beside the message editor, under the pane: give it a column of its own instead + const layout = await commands.executeCommand("vscode.getEditorLayout"); + await commands.executeCommand("vscode.setEditorLayout", addColumnOnRight(layout)); } - return ""; + return column; } - get documentContents(): string { - const b = this.branchName ?? this.baseSha?.slice(0, 16) ?? ""; - const branchLine = `Branch: ${b}${this.upstreamString}`; - const lines: string[] = []; - if (this.relativePathFromRoot) { - lines.push(`Submodule: ${this.relativePathFromRoot}`); - } - lines.push(branchLine, ""); - function pushVec(patches: Patch[]) { - for (const p of patches) { - const patchLines = p.getLines(); - p.updateLineSpan(lines.length, patchLines.length); - lines.push(...patchLines); - } - } - pushVec(this.history); - pushVec(this.applied); - if (!this.applied.length) { - lines.push("> "); - } - if (this.stgMissing) { - lines.push("! *** StGit not installed ('stg' binary missing) ***"); - } else if (!this.branchInitialized) { - lines.push("! *** Setup branch for StGit ('stg init') ***"); - } else if (this.needRepair) { - lines.push("! *** Repair needed [C-u g] ***"); - } - pushVec([this.index]); - pushVec([this.workTree]); - pushVec(this.popped); - - this.updateDecorations(); - return lines.join("\n") + "\n--\n"; + private get upstreamString(): string { + return formatUpstream(this.branchName, this.remoteName, this.remoteBranch); } } class StGitMode { static instance: StGitMode | null; - private changeEmitter = new vscode.EventEmitter(); - private pendingSelections = new Map< - vscode.TextEditor, - { - previous: string; - next: string; - selections: readonly vscode.Selection[]; - } - >(); - private commentController = vscode.comments.createCommentController("stgit.comments", "StGit"); - stgit: StGitDoc | null = null; + private assetRevision = 0; + private assetReloadTimer: ReturnType | undefined; + // Whether the next "ready" from the webview should pull keyboard focus into it + private focusWhenReady = true; private repositoryFollower = new RepositoryFollower({ lookup: (directory: string) => RepositoryInfo.createForPath(directory), current: () => this.stgit?.repo ?? null, @@ -1592,80 +1550,39 @@ class StGitMode { }, }); - readonly fileHighlightDecoration = window.createTextEditorDecorationType({ - before: { contentText: "⏹ " }, - }); - readonly historyDecoration = window.createTextEditorDecorationType({ - dark: { color: "#777" }, - light: { color: "#999" }, - }); - constructor(context: vscode.ExtensionContext) { - const provider: vscode.TextDocumentContentProvider = { - onDidChange: this.changeEmitter.event, - provideTextDocumentContent: (uri: vscode.Uri, token) => { - const next = this.stgit?.documentContents ?? "\nIndex\n"; - const doc = this.stgit?.doc; - if (doc && next !== doc.getText()) { - this.pendingSelections.clear(); - for (const editor of window.visibleTextEditors) { - if (editor.document === doc) { - this.pendingSelections.set(editor, { - previous: doc.getText(), - next, - selections: editor.selections, - }); - } - } - } - return next; - }, - }; + constructor(private readonly context: vscode.ExtensionContext) { const cmd = (cmd: string, func: () => void | Promise) => { - return commands.registerTextEditorCommand(`stgit.${cmd}`, () => { + return commands.registerCommand(`stgit.${cmd}`, () => { const doc = this.stgit; - return doc ? doc.runMutation(func) : func(); + return doc ? doc.runCommand(cmd, func) : func(); }); }; - const globalCmd = (cmd: string, func: () => void | Promise) => - commands.registerCommand(`stgit.${cmd}`, () => { - const doc = this.stgit; - return doc ? doc.runMutation(func) : func(); - }); - context.subscriptions.push( - this /* self dispose */, - - window.onDidChangeTextEditorSelection((event) => { - if (event.kind !== undefined) { - const pending = this.pendingSelections.get(event.textEditor); - if (pending) { - pending.selections = event.selections; - } - } - }), - workspace.onDidChangeTextDocument((event) => { - if (event.document !== this.stgit?.doc) { - return; + if (context.extensionMode === vscode.ExtensionMode.Development) { + const assetRoot = vscode.Uri.joinPath(context.extensionUri, "out", "webview"); + const assetWatcher = workspace.createFileSystemWatcher(new vscode.RelativePattern(assetRoot, "index.{js,css}")); + const scheduleReload = () => { + if (this.assetReloadTimer) { + clearTimeout(this.assetReloadTimer); } - for (const [editor, pending] of this.pendingSelections) { - if (event.document.getText() !== pending.next) { - continue; + this.assetReloadTimer = setTimeout(() => { + this.assetReloadTimer = undefined; + if (this.stgit) { + this.assetRevision++; + // The webview element survives an HTML update and keeps its own focus + this.focusWhenReady = false; + this.setWebviewHtml(this.stgit.panel); } - editor.selections = pending.selections.map((selection) => { - const position = (point: vscode.Position) => { - const line = correspondingLine(pending.previous, pending.next, point.line); - const column = Math.min(point.character, event.document.lineAt(line).text.length); - return new vscode.Position(line, column); - }; - return new vscode.Selection(position(selection.anchor), position(selection.active)); - }); - editor.revealRange(editor.selection, vscode.TextEditorRevealType.InCenterIfOutsideViewport); - this.pendingSelections.delete(editor); - } - }), - - globalCmd("open", () => this.openStgit()), + }, 150); + }; + context.subscriptions.push(assetWatcher, assetWatcher.onDidChange(scheduleReload), assetWatcher.onDidCreate(scheduleReload)); + } + context.subscriptions.push( + this /* self dispose */, + registerMessageFileSystem(), + commands.registerCommand("stgit.open", () => this.openStgit()), cmd("refresh", () => this.stgit?.refresh()), cmd("repair", () => this.stgit?.repair()), + cmd("initializeBranch", () => this.stgit?.initializeBranch()), cmd("refreshSpecific", () => this.stgit?.refreshSpecific()), cmd("createBranch", () => this.stgit?.createBranch()), cmd("switchBranch", () => this.stgit?.switchBranch()), @@ -1691,7 +1608,9 @@ class StGitMode { cmd("movePatchesTo", () => this.stgit?.movePatchesTo()), cmd("commentCreatePatch", () => this.stgit?.commentCreatePatch()), cmd("completePatchEdit", () => this.stgit?.completePatchEdit()), + cmd("submitComment", () => this.stgit?.submitComment()), cmd("cancel", () => this.stgit?.cancel()), + cmd("discardCommitMessage", () => this.stgit?.cancel()), cmd("cancelEmptyComment", () => this.stgit?.cancelEmptyComment()), cmd("editCommitMessage", () => this.stgit?.editCommitMessage()), cmd("copyCommitSha", () => this.stgit?.copyCommitSha()), @@ -1710,24 +1629,7 @@ class StGitMode { cmd("redo", () => this.stgit?.redo()), cmd("help", () => this.stgit?.help()), cmd("navigateToParent", () => this.stgit?.navigateToParent()), - - workspace.registerTextDocumentContentProvider("stgit", provider), - vscode.languages.registerFoldingRangeProvider( - { scheme: "stgit", language: "stgit-buffer" }, - { - provideFoldingRanges: () => [], - }, - ), - - workspace.onDidCloseTextDocument((doc) => { - if (doc === this.stgit?.doc) { - this.pendingSelections.clear(); - this.repositoryFollower.cancel(); - this.stgit.dispose(); - this.stgit = null; - } - }), - workspace.onDidSaveTextDocument((doc) => { + workspace.onDidSaveTextDocument(() => { this.stgit?.reloadWorkTree(); }), window.onDidChangeActiveTextEditor((editor) => { @@ -1738,21 +1640,18 @@ class StGitMode { ); } dispose() { - this.pendingSelections.clear(); + if (this.assetReloadTimer) { + clearTimeout(this.assetReloadTimer); + } this.repositoryFollower.cancel(); this.stgit?.dispose(); this.stgit = null; - this.commentController.dispose(); - this.changeEmitter.dispose(); StGitMode.instance = null; - - this.fileHighlightDecoration.dispose(); - this.historyDecoration.dispose(); } private async openStgit() { if (this.stgit) { const scheme = window.activeTextEditor?.document.uri.scheme || ""; - const isInStgitBuffer = ["stgit", "stgit-diff"].includes(scheme); + const isInStgitBuffer = this.stgit.panel.active || scheme === "stgit-diff"; if (!isInStgitBuffer) { const repo = await RepositoryInfo.lookup(); if (!repo) { @@ -1762,7 +1661,7 @@ class StGitMode { const context = await RepositoryInfo.buildParentStack(repo); this.stgit.switchRepository(repo, context); } - await this.stgit.focusWindow(); + this.stgit.focusWindow(); this.stgit.reload(); } else { const repo = await RepositoryInfo.lookup(); @@ -1771,21 +1670,102 @@ class StGitMode { return; } RepositoryInfo.setSelectedRepo(repo); - const doc = await vscode.languages.setTextDocumentLanguage(await workspace.openTextDocument(this.uri), "stgit-buffer"); + const assetRoot = vscode.Uri.joinPath(this.context.extensionUri, "out", "webview"); + this.focusWhenReady = true; + const panel = window.createWebviewPanel("stgit", "StGit", vscode.ViewColumn.Active, { + enableScripts: true, + localResourceRoots: [assetRoot], + }); this.stgit = new StGitDoc( - doc, + panel, repo, () => { - if (this.stgit?.documentContents !== doc.getText()) { - this.changeEmitter.fire(doc.uri); + if (this.stgit?.panel === panel && panel.visible) { + void panel.webview.postMessage({ type: "render", state: this.stgit.viewState }); + } + }, + (target, selectionVersion) => { + if (this.stgit?.panel === panel) { + void panel.webview.postMessage({ type: "navigate", target, selectionVersion }); } }, - this.commentController, ); + panel.webview.onDidReceiveMessage((message: unknown) => void this.handleMessage(panel, message)); + panel.onDidChangeViewState(() => { + if (panel.visible && this.stgit?.panel === panel) { + void panel.webview.postMessage({ type: "render", state: this.stgit.viewState }); + } + }); + panel.onDidDispose(() => { + const doc = this.stgit; + if (doc?.panel === panel) { + // Forgotten first, so that nothing during the teardown can leave a closed panel behind as the current one + this.stgit = null; + this.repositoryFollower.cancel(); + doc.dispose(); + } + }); + this.setWebviewHtml(panel); } } - private get uri() { - return vscode.Uri.from({ scheme: "stgit", path: "/StGit" }); + private setWebviewHtml(panel: vscode.WebviewPanel) { + const assetRoot = vscode.Uri.joinPath(this.context.extensionUri, "out", "webview"); + const query = `v=${this.assetRevision}`; + panel.webview.html = stgitWebviewHtml(panel.webview, { + script: vscode.Uri.joinPath(assetRoot, "index.js").with({ query }), + style: vscode.Uri.joinPath(assetRoot, "index.css").with({ query }), + }); + } + private async handleMessage(panel: vscode.WebviewPanel, raw: unknown) { + const doc = this.stgit; + if (!doc || doc.panel !== panel || !raw || typeof raw !== "object") { + return; + } + const message = raw as Record; + if (message.type === "ready") { + void panel.webview.postMessage({ type: "render", state: doc.viewState }); + // VS Code recreates the webview when the panel is opened, moved to another + // group or shown again after being hidden, and focuses the panel before the + // new content has loaded, so keyboard focus never reaches it. Focus it again + // now that the content is ready. + const focus = this.focusWhenReady; + this.focusWhenReady = true; + if (focus && panel.active) { + // In the current column: the panel's viewColumn is out of date once groups before it come or go + panel.reveal(undefined, false); + } + } else if ( + message.type === "select" && + typeof message.patchId === "string" && + (message.path === undefined || typeof message.path === "string") && + typeof message.selectionVersion === "number" && + Number.isSafeInteger(message.selectionVersion) && + message.selectionVersion >= 0 + ) { + doc.selectRow(message.patchId, message.path as string | undefined, message.selectionVersion); + } else if (message.type === "submit") { + await doc.runMutation(() => doc.submitComment()); + } else if (message.type === "showMessage") { + await doc.showCommitMessage(); + } else if (message.type === "cancel") { + await doc.runCommand("cancel", () => doc.cancel()); + } else if ( + message.type === "command" && + typeof message.command === "string" && + [ + "stgit.reload", + "stgit.refresh", + "stgit.newPatch", + "stgit.help", + "stgit.toggleExpand", + "stgit.markPatch", + "stgit.unmarkPatch", + "stgit.initializeBranch", + "stgit.repair", + ].includes(message.command) + ) { + await commands.executeCommand(message.command); + } } } diff --git a/src/test/runTest.ts b/src/test/runTest.ts index 2d610d1..196e4a6 100644 --- a/src/test/runTest.ts +++ b/src/test/runTest.ts @@ -1,9 +1,25 @@ +import * as fs from "fs"; +import * as os from "os"; import * as path from "path"; import { runTests } from "@vscode/test-electron"; +// While running extension tests, VS Code prints its whole log to stdout, so turn off what would fill it. +const settings = { + // The chat and agent features keep failing to sign in to GitHub + "chat.disableAIFeatures": true, + "chat.remoteAgentHostsEnabled": false, + // The Git extension opens the repositories the tests create and fails once they are deleted + "git.enabled": false, +}; + async function main() { + // A fresh profile for each run, as in CI, rather than one that keeps the state of earlier runs + const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "stgit-test-profile-")); try { + fs.mkdirSync(path.join(userDataDir, "User")); + fs.writeFileSync(path.join(userDataDir, "User", "settings.json"), JSON.stringify(settings, null, 4)); + // The folder containing the Extension Manifest package.json // Passed to `--extensionDevelopmentPath` const extensionDevelopmentPath = path.resolve(__dirname, "../../"); @@ -17,11 +33,13 @@ async function main() { extensionDevelopmentPath, extensionTestsPath, // Keep the other extensions (e.g. chat) out of the tests. - launchArgs: ["--disable-extensions"], + launchArgs: ["--disable-extensions", `--user-data-dir=${userDataDir}`], }); } catch (err) { console.error("Failed to run tests", err); - process.exit(1); + process.exitCode = 1; + } finally { + fs.rmSync(userDataDir, { recursive: true, force: true }); } } diff --git a/src/test/suite/commit-message.test.ts b/src/test/suite/commit-message.test.ts new file mode 100644 index 0000000..8844cb3 --- /dev/null +++ b/src/test/suite/commit-message.test.ts @@ -0,0 +1,134 @@ +import * as assert from "assert"; +import { execFileSync } from "child_process"; +import * as fs from "fs/promises"; +import * as os from "os"; +import * as path from "path"; +import * as vscode from "vscode"; +import { messageScheme } from "../../message-editor"; + +async function until(what: string, condition: () => boolean) { + for (let attempt = 0; attempt < 100; attempt++) { + if (condition()) { + return; + } + await new Promise((resolve) => setTimeout(resolve, 50)); + } + assert.fail(`timed out waiting until ${what}`); +} + +const allTabs = () => vscode.window.tabGroups.all.flatMap((group) => group.tabs); +const describeGroups = () => vscode.window.tabGroups.all.map((group) => `${group.viewColumn}: ${group.tabs.map((tab) => tab.label).join(", ")}`).join(" | "); +const messageTabs = () => allTabs().filter((tab) => tab.input instanceof vscode.TabInputText && tab.input.uri.scheme === messageScheme); + +suite("Writing commit messages", function () { + this.timeout(30000); + let dir: string; + let groups: number; + // Errors include what was printed to stderr, so keep it out of the test output + const run = (command: string, ...args: string[]) => execFileSync(command, args, { cwd: dir, encoding: "utf8", stdio: "pipe" }); + const topSubject = () => run("git", "log", "-1", "--format=%s").trim(); + + suiteSetup(async () => { + await vscode.commands.executeCommand("workbench.action.closeAllEditors"); + // Empty groups survive closing all editors, and VS Code keeps the layout from the last run + await vscode.commands.executeCommand("vscode.setEditorLayout", { orientation: 0, groups: [{}] }); + dir = await fs.mkdtemp(path.join(os.tmpdir(), "stgit-message-")); + run("git", "init", "-q"); + run("git", "config", "user.name", "Test"); + run("git", "config", "user.email", "test@example.org"); + await fs.writeFile(path.join(dir, "file.txt"), "content\n"); + run("git", "add", "."); + run("git", "commit", "-qm", "initial"); + run("stg", "init"); + // The pane opens on the repository of the active file + await vscode.window.showTextDocument(vscode.Uri.file(path.join(dir, "file.txt"))); + await vscode.commands.executeCommand("stgit.open"); + await until("the StGit pane opens", () => allTabs().some((tab) => tab.input instanceof vscode.TabInputWebview)); + groups = vscode.window.tabGroups.all.length; + }); + + suiteTeardown(async () => { + await vscode.commands.executeCommand("workbench.action.closeAllEditors"); + await fs.rm(dir, { recursive: true, force: true }); + }); + + async function writeMessage(text: string): Promise { + await vscode.commands.executeCommand("stgit.createPatch"); + await until("the message editor opens", () => vscode.window.activeTextEditor?.document.uri.scheme === messageScheme); + const editor = vscode.window.activeTextEditor!; + assert.strictEqual(editor.document.languageId, "stgit-message"); + assert.strictEqual(vscode.window.tabGroups.all.length, groups + 1, `it opens in a group of its own: ${describeGroups()}`); + // The template of `stg new`: the patch name, author and date, then room for the message, then help + const lines = editor.document.getText().split("\n"); + assert.deepStrictEqual(lines.slice(0, 2), ["Patch: ", "Author: Test "]); + assert.match(lines[2], /^Date: {3}\d{4}-\d\d-\d\d \d\d:\d\d:\d\d [+-]\d{4}$/); + assert.match(lines[6], /^# Please enter the message for your patch/); + assert.deepStrictEqual(editor.selection.active, new vscode.Position(4, 0), "the cursor starts where the message goes"); + await editor.edit((edit) => edit.insert(editor.selection.active, text)); + return editor; + } + + test("takes the patch name and author from the template", async () => { + const editor = await writeMessage("Named by hand"); + await editor.edit((edit) => { + edit.insert(new vscode.Position(0, "Patch: ".length), "my-name"); + edit.replace(editor.document.lineAt(1).range, "Author: Someone Else "); + }); + await vscode.commands.executeCommand("stgit.submitComment"); + await until("the patch is created", () => topSubject() === "Named by hand"); + assert.strictEqual(run("stg", "top").trim(), "my-name"); + assert.strictEqual(run("git", "log", "-1", "--format=%an <%ae>").trim(), "Someone Else "); + assert.strictEqual(run("git", "log", "-1", "--format=%B").trim(), "Named by hand", "the help is left out"); + await until("the message editor is gone", () => !messageTabs().length); + }); + + test("closes without creating a patch when there is no message, like stg new", async () => { + const top = run("stg", "top").trim(); + await writeMessage(""); + await vscode.commands.executeCommand("stgit.submitComment"); + await until("the message editor is gone", () => !messageTabs().length); + await new Promise((resolve) => setTimeout(resolve, 1000)); + assert.strictEqual(run("stg", "top").trim(), top); + }); + + test("closes when StGit fails, leaving the work tree alone", async () => { + const series = run("stg", "series"); + await fs.writeFile(path.join(dir, "file.txt"), "changed\n"); + const editor = await writeMessage("Invalid name"); + await editor.edit((edit) => edit.insert(new vscode.Position(0, "Patch: ".length), "bad..name")); + await vscode.commands.executeCommand("stgit.submitComment"); + await until("the message editor is gone", () => !messageTabs().length); + await new Promise((resolve) => setTimeout(resolve, 1000)); + assert.strictEqual(run("stg", "series"), series); + // Refreshing after a failed `stg new` would have put the change in the previous patch + assert.strictEqual(run("git", "diff", "--name-only").trim(), "file.txt"); + run("git", "checkout", "file.txt"); + }); + + test("commits the message written in the editor, saved or not", async () => { + await writeMessage("Written in a text editor\n\nWith a body"); + await vscode.commands.executeCommand("stgit.submitComment"); + await until("the patch is created", () => topSubject() === "Written in a text editor"); + assert.strictEqual(run("git", "log", "-1", "--format=%b").trim(), "With a body"); + await until("the message editor and its group are gone", () => !messageTabs().length && vscode.window.tabGroups.all.length === groups); + }); + + test("commits a saved message when its editor is closed, like git commit", async () => { + const editor = await writeMessage("Saved and closed"); + await editor.document.save(); + await vscode.commands.executeCommand("workbench.action.closeActiveEditor"); + await until("the patch is created", () => topSubject() === "Saved and closed"); + await until("the group is gone", () => vscode.window.tabGroups.all.length === groups); + }); + + test("cancels when the editor is closed without saving", async () => { + await writeMessage("Never saved"); + await vscode.commands.executeCommand("workbench.action.revertAndCloseActiveEditor"); + await until("the message editor and its group are gone", () => !messageTabs().length && vscode.window.tabGroups.all.length === groups); + // Long enough for a patch that was going to be created + await new Promise((resolve) => setTimeout(resolve, 1000)); + // The series is not compared as a whole: the refresh after the previous patch may still show its temporary patch + assert.doesNotMatch(run("stg", "series"), /never-saved/); + assert.strictEqual(topSubject(), "Saved and closed"); + }); +}); diff --git a/src/test/suite/extension.test.ts b/src/test/suite/extension.test.ts index ced20ad..2c73ce1 100644 --- a/src/test/suite/extension.test.ts +++ b/src/test/suite/extension.test.ts @@ -84,6 +84,180 @@ suite("Extension Test Suite", () => { const subject = "Fix #123 and #456"; const patch = StGitPatch.fromSeries(` > ${"a".repeat(40)} fix-bug # ${subject}`, `${subject}\n`, reader); assert.strictEqual(patch.description, subject); + // As `stg series --description` lists a patch with an empty commit message, which the pane marks + const unnamed = StGitPatch.fromSeries(`*+ ${"a".repeat(40)} renamed #`, "", reader); + assert.strictEqual(unnamed.description, ""); + assert.strictEqual(unnamed.label, "renamed"); + }); + + test("Keeps patch row identity stable across applied, popped and refreshed series entries", () => { + const reader = new RepoReader( + { topLevelDir: "/repo" }, + { + run: async () => "", + runCommand: async () => ({ stdout: "", stderr: "", ecode: 0 }), + }, + ); + const applied = StGitPatch.fromSeries(` > ${"a".repeat(40)} fix-identity # Fix identity`, "Fix identity\n", reader); + const popped = StGitPatch.fromSeries(` - ${"a".repeat(40)} fix-identity # Fix identity`, "Fix identity\n", reader); + const refreshed = StGitPatch.fromSeries(` + ${"b".repeat(40)} fix-identity # Updated subject`, "Updated subject\n", reader); + const other = StGitPatch.fromSeries(` > ${"a".repeat(40)} other-patch # Fix identity`, "Fix identity\n", reader); + assert.strictEqual(applied.kind, "+"); + assert.strictEqual(popped.kind, "-"); + assert.strictEqual(applied.rowId, "P:fix-identity"); + assert.strictEqual(popped.rowId, applied.rowId); + assert.strictEqual(refreshed.rowId, applied.rowId); + assert.notStrictEqual(other.rowId, applied.rowId); + assert.strictEqual(new WorkTree(reader, false).rowId, "W:"); + }); + + test("Shares cached files across reloaded patch and history rows using the listed commit SHA", async () => { + const calls: string[][] = []; + const reader = new RepoReader( + { topLevelDir: "/repo" }, + { + run: async () => assert.fail("Commit file reads must check the exit status"), + runCommand: async (command, args) => { + assert.strictEqual(command, "git"); + assert.strictEqual(args[0], "diff-tree"); + calls.push(args); + return { stdout: `:100644 100644 ${"c".repeat(40)} ${"d".repeat(40)} M\0file.txt\0`, stderr: "", ecode: 0 }; + }, + }, + ); + const sha = "a".repeat(40); + const first = StGitPatch.fromSeries(` > ${sha} cached-patch # Cached patch`, "Cached patch\n", reader); + const reloaded = StGitPatch.fromSeries(` - ${sha} cached-patch # Cached patch`, "Cached patch\n", reader); + const history = new History(reader, sha, "Committed patch"); + await Promise.all([first.fetchDetails(), reloaded.fetchDetails(), history.fetchDetails()]); + assert.strictEqual(calls.length, 1); + assert.strictEqual(first.deltas[0].path, "file.txt"); + assert.notStrictEqual(first.deltas[0], reloaded.deltas[0]); + assert.notStrictEqual(first.deltas[0], history.deltas[0]); + + const refreshedSha = "b".repeat(40); + const refreshed = StGitPatch.fromSeries(` > ${refreshedSha} cached-patch # Cached patch`, "Cached patch\n", reader); + await refreshed.fetchDetails(); + assert.strictEqual(calls.length, 2); + assert.strictEqual(calls[1][calls[1].length - 1], refreshedSha); + }); + + test("Retries failed commit details on the same row", async () => { + let attempts = 0; + const reader = new RepoReader( + { topLevelDir: "/repo" }, + { + run: async () => "", + runCommand: async () => + ++attempts === 1 + ? { stdout: "", stderr: "read failed", ecode: 1 } + : { stdout: `:100644 100644 ${"c".repeat(40)} ${"d".repeat(40)} M\0file.txt\0`, stderr: "", ecode: 0 }, + }, + ); + const patch = StGitPatch.fromSeries(` > ${"a".repeat(40)} retry-patch # Retry patch`, "Retry patch\n", reader); + await assert.rejects(patch.fetchDetails(), /read failed/); + await patch.fetchDetails(); + assert.strictEqual(attempts, 2); + assert.strictEqual(patch.deltas[0].path, "file.txt"); + }); + + test("Expands a row at once, and collapses it again if its files cannot be read", async () => { + let attempts = 0; + const reader = new RepoReader( + { topLevelDir: "/repo" }, + { + run: async () => "", + runCommand: async () => + ++attempts === 1 + ? { stdout: "", stderr: "read failed", ecode: 1 } + : { stdout: `:100644 100644 ${"c".repeat(40)} ${"d".repeat(40)} M\0file.txt\0`, stderr: "", ecode: 0 }, + }, + ); + const patch = StGitPatch.fromSeries(` > ${"a".repeat(40)} expand-patch # Expand patch`, "Expand patch\n", reader); + const failed = patch.toggleExpanded(); + assert.strictEqual(patch.isExpanded, true); + await assert.rejects(failed, /read failed/); + assert.strictEqual(patch.isExpanded, false); + await patch.toggleExpanded(); + assert.strictEqual(patch.isExpanded, true); + assert.strictEqual(patch.deltas[0].path, "file.txt"); + }); + + test("A reloaded row takes over the view state its predecessor has when it is shown", async () => { + const oldSha = "a".repeat(40); + const reader = new RepoReader( + { topLevelDir: "/repo" }, + { + run: async () => "", + runCommand: async (_command, args) => { + const file = args[args.length - 1] === oldSha ? "old-file.txt" : "new-file.txt"; + return { stdout: `:100644 100644 ${"c".repeat(40)} ${"d".repeat(40)} M\0${file}\0`, stderr: "", ecode: 0 }; + }, + }, + ); + const series = (sha: string) => StGitPatch.fromSeries(` > ${sha} reloaded-patch # Reloaded patch`, "Reloaded patch\n", reader); + let redrawn = 0; + const shown = series(oldSha); + + // The row is expanded and marked after its replacement was read, but before the replacement is shown. + const refreshed = series("b".repeat(40)); + shown.setMarked(true); + await shown.toggleExpanded(); + refreshed.inherit(shown, () => redrawn++); + assert.strictEqual(refreshed.marked, true); + assert.strictEqual(refreshed.isExpanded, true); + assert.strictEqual(refreshed.deltas[0].path, "old-file.txt"); + assert.strictEqual(redrawn, 0); + await refreshed.fetchDetails(); + assert.strictEqual(refreshed.deltas[0].path, "new-file.txt"); + assert.strictEqual(redrawn, 1); + + // The other way around: collapsed and unmarked after its replacement was read with files. + const reloaded = series("b".repeat(40)); + await reloaded.toggleExpanded(); + refreshed.setMarked(false); + await refreshed.toggleExpanded(); + reloaded.inherit(refreshed, () => redrawn++); + assert.strictEqual(reloaded.marked, false); + assert.strictEqual(reloaded.isExpanded, false); + assert.strictEqual(reloaded.deltas[0].path, "new-file.txt"); + assert.strictEqual(redrawn, 1); + + const workTree = new WorkTree(reader, false); + await workTree.toggleExpanded(); + const reloadedWorkTree = new WorkTree(reader, false); + await reloadedWorkTree.fetchDetails(); + reloadedWorkTree.inherit(workTree, () => redrawn++); + assert.strictEqual(reloadedWorkTree.isExpanded, false); + assert.strictEqual(redrawn, 1); + }); + + test("A row takes the files of a commit that was read before from the cache, without waiting", async () => { + const reads: string[] = []; + const reader = new RepoReader( + { topLevelDir: "/repo" }, + { + run: async () => "", + runCommand: async (_command, args) => { + reads.push(args[args.length - 1]); + return { stdout: `:100644 100644 ${"c".repeat(40)} ${"d".repeat(40)} M\0file.txt\0`, stderr: "", ecode: 0 }; + }, + }, + ); + const sha = "a".repeat(40); + const unread = StGitPatch.fromSeries(` > ${sha} cached-patch # Cached patch`, "Cached patch\n", reader); + assert.strictEqual(unread.useCachedFiles(), false); + assert.strictEqual(unread.deltas.length, 0); + + await reader.readCommitFiles(sha); + const reloaded = StGitPatch.fromSeries(` - ${sha} cached-patch # Cached patch`, "Cached patch\n", reader); + assert.strictEqual(reloaded.useCachedFiles(), true); + assert.strictEqual(reloaded.deltas[0].path, "file.txt"); + assert.strictEqual(reloaded.useCachedFiles(), false); + await reloaded.fetchDetails(); + assert.strictEqual(new History(reader, sha, "Committed patch").useCachedFiles(), true); + assert.strictEqual(new WorkTree(reader, false).useCachedFiles(), false); + assert.deepStrictEqual(reads, [sha]); }); test("Shows the work-tree expansion state in its header", async () => { @@ -132,15 +306,14 @@ suite("Extension Test Suite", () => { assert.deepStrictEqual(commit.getLines(), ["▸ abc12 Committed change"]); }); - test("Disables native folding in the StGit document", async () => { + test("Registers StGit webview actions without a virtual document", async () => { const extension = vscode.extensions.getExtension("cedernaes.stgit-revived"); assert.ok(extension); await extension.activate(); - const uri = vscode.Uri.from({ scheme: "stgit", path: "/StGit" }); - const doc = await vscode.workspace.openTextDocument(uri); - assert.strictEqual(doc.languageId, "stgit-buffer"); - const ranges = await vscode.commands.executeCommand("vscode.executeFoldingRangeProvider", uri); - assert.deepStrictEqual(ranges, []); + const registered = await vscode.commands.getCommands(true); + assert.ok(registered.includes("stgit.open")); + assert.ok(registered.includes("stgit.refresh")); + assert.ok(registered.includes("stgit.submitComment")); }); test("Keeps the cursor on its file when a redraw changes line counts", () => { diff --git a/src/test/suite/message-editor.test.ts b/src/test/suite/message-editor.test.ts new file mode 100644 index 0000000..2708f60 --- /dev/null +++ b/src/test/suite/message-editor.test.ts @@ -0,0 +1,147 @@ +import * as assert from "assert"; +import * as vscode from "vscode"; +import { EditorLayout, addColumnOnRight, isStackedBelow } from "../../editor-layout"; +import { MessageEditor, paneViewColumn } from "../../message-editor"; + +const layout = () => vscode.commands.executeCommand("vscode.getEditorLayout"); +const allTabs = () => vscode.window.tabGroups.all.flatMap((group) => group.tabs); + +// The editor groups and their tabs, to tell what went wrong +async function describe(): Promise { + const groups = vscode.window.tabGroups.all.map((group) => { + const tabs = group.tabs.map((tab) => { + const input = tab.input instanceof vscode.TabInputWebview ? `webview:${tab.input.viewType}` : tab.label; + return `${input}${tab.isActive ? "*" : ""}`; + }); + return `${group.viewColumn}${group.isActive ? " (active)" : ""}: ${tabs.join(", ")}`; + }); + return `${groups.join(" | ")}; layout ${JSON.stringify(await layout())}`; +} + +async function until(what: string, condition: () => boolean | Promise) { + for (let attempt = 0; attempt < 100; attempt++) { + if (await condition()) { + return; + } + await new Promise((resolve) => setTimeout(resolve, 50)); + } + assert.fail(`timed out waiting until ${what}: ${await describe()}`); +} + +// Documents that close without asking to be saved +const blank = () => vscode.workspace.openTextDocument({ language: "plaintext" }); + +suite("Commit message editor", function () { + this.timeout(20000); + let panel: vscode.WebviewPanel; + let editor: MessageEditor; + let closes: string[]; + + const messageTabs = () => allTabs().filter((tab) => tab.input instanceof vscode.TabInputText && tab.input.uri.toString() === editor.uri.toString()); + // Exactly one message tab, in front, in the group right under the pane + const docked = async () => { + const tabs = messageTabs(); + const pane = paneViewColumn(panel)!; + return tabs.length === 1 && tabs[0].isActive && tabs[0].group.viewColumn === pane + 1 && !!isStackedBelow(await layout(), pane - 1); + }; + + suiteSetup(async () => { + await vscode.extensions.getExtension("cedernaes.stgit-revived")!.activate(); + }); + + setup(async () => { + await vscode.commands.executeCommand("workbench.action.closeAllEditors"); + // Empty groups survive closing all editors, and VS Code keeps the layout from the last run + await vscode.commands.executeCommand("vscode.setEditorLayout", { orientation: 0, groups: [{}] }); + closes = []; + panel = vscode.window.createWebviewPanel("stgit", "StGit", vscode.ViewColumn.One, {}); + // Diffs and files the person opens, to the right of the pane + await vscode.window.showTextDocument(await blank(), { viewColumn: vscode.ViewColumn.Beside, preview: false }); + panel.reveal(vscode.ViewColumn.One, false); + await until("the pane is active", () => panel.active); + // The webview takes the focus a moment after it is revealed + await new Promise((resolve) => setTimeout(resolve, 300)); + editor = new MessageEditor("Subject\n\nBody\n", panel, (saved) => closes.push(saved), 2); + await editor.open(); + }); + + teardown(async () => { + await editor.close(); + panel.dispose(); + await vscode.commands.executeCommand("workbench.action.closeAllEditors"); + }); + + test("opens as a focused StGit message editor right under the StGit pane", async () => { + assert.ok(await docked(), await describe()); + assert.strictEqual(vscode.window.activeTextEditor?.document.uri.toString(), editor.uri.toString()); + assert.strictEqual(vscode.window.activeTextEditor?.document.languageId, "stgit-message"); + assert.strictEqual(editor.text, "Subject\n\nBody\n"); + assert.deepStrictEqual(vscode.window.activeTextEditor?.selection.active, new vscode.Position(2, 0), "the cursor starts on the line given"); + assert.strictEqual(vscode.window.tabGroups.all.length, 3); + }); + + test("other editors do not open in the message editor's group", async () => { + const shown = await vscode.window.showTextDocument(await blank(), { preview: false }); + assert.notStrictEqual(shown.viewColumn, editor.viewColumn, await describe()); + await until("the message editor is still in its place", docked); + }); + + test("comes back under the pane when moved to another group", async () => { + const cursor = new vscode.Selection(2, 2, 2, 2); + vscode.window.activeTextEditor!.selection = cursor; + await vscode.commands.executeCommand("workbench.action.moveEditorToRightGroup"); + await until("the message editor is back under the pane", docked); + assert.strictEqual(vscode.window.tabGroups.all.length, 3, "no group is left behind"); + assert.deepStrictEqual(closes, [], "moving is not closing"); + // The pane is focused to split it, and its webview takes the focus once more a moment later + await until("the person can keep typing in it", () => vscode.window.activeTextEditor?.document.uri.toString() === editor.uri.toString()); + assert.deepStrictEqual(vscode.window.activeTextEditor?.selection, cursor, "where they left off"); + }); + + test("comes back to the front when another tab covers it", async () => { + await vscode.window.showTextDocument(await blank(), { viewColumn: editor.viewColumn, preview: false }); + await until("the message tab is in front again", docked); + }); + + test("follows the StGit pane to another group", async () => { + const other = vscode.window.tabGroups.all.find((group) => group.viewColumn === vscode.ViewColumn.Three)!.tabs[0].label; + panel.reveal(vscode.ViewColumn.Three, false); + const paneGroup = () => vscode.window.tabGroups.all.find((group) => group.viewColumn === paneViewColumn(panel)); + await until("the message editor is under the moved pane", async () => !!paneGroup()?.tabs.some((tab) => tab.label === other) && (await docked())); + // Handing the focus back to the pane is the last step + await until("the focus is back in the pane that was moved", () => panel.active); + }); + + test("stays under the pane when diffs get a column of their own", async () => { + // The order of tabGroups.all is not the view column order + const column = (viewColumn: number) => vscode.window.tabGroups.all.find((group) => group.viewColumn === viewColumn)!; + await vscode.window.tabGroups.close(column(3)); + await until("only the pane and the message editor are left", async () => vscode.window.tabGroups.all.length === 2 && (await docked())); + await vscode.commands.executeCommand("vscode.setEditorLayout", addColumnOnRight(await layout())); + assert.strictEqual(vscode.window.tabGroups.all.length, 3, await describe()); + assert.ok(await docked(), await describe()); + assert.strictEqual(column(3).tabs.length, 0, "the new column is on the right and empty"); + }); + + test("closing it reports what was last saved", async () => { + const text = vscode.window.activeTextEditor!; + await text.edit((edit) => edit.insert(new vscode.Position(0, 0), "Saved ")); + await text.document.save(); + await text.edit((edit) => edit.insert(new vscode.Position(0, 0), "Unsaved ")); + await vscode.commands.executeCommand("workbench.action.revertAndCloseActiveEditor"); + await until("the close is reported", () => closes.length > 0); + assert.deepStrictEqual(closes, ["Saved Subject\n\nBody\n"]); + assert.strictEqual(vscode.window.tabGroups.all.length, 2, "the message editor's group goes with it"); + }); + + test("closes without asking about unsaved changes", async () => { + const text = vscode.window.activeTextEditor!; + assert.strictEqual(text?.document.uri.toString(), editor.uri.toString(), await describe()); + await text.edit((edit) => edit.insert(new vscode.Position(0, 0), "Unsaved ")); + assert.strictEqual(editor.text, "Unsaved Subject\n\nBody\n"); + await editor.close(); + assert.strictEqual(messageTabs().length, 0); + assert.strictEqual(vscode.window.tabGroups.all.length, 2); + assert.deepStrictEqual(closes, [], "closing it from StGit is not the person closing it"); + }); +}); diff --git a/src/test/suite/mutation-gate.test.ts b/src/test/suite/mutation-gate.test.ts index 3eca8c4..263aa3e 100644 --- a/src/test/suite/mutation-gate.test.ts +++ b/src/test/suite/mutation-gate.test.ts @@ -1,5 +1,7 @@ import * as assert from "assert"; -import { MutationGate } from "../../mutation-gate"; +import { readFileSync } from "fs"; +import * as path from "path"; +import { MutationGate, viewCommands } from "../../mutation-gate"; import { RepoDisplayLoads } from "../../repo-reader"; suite("Mutation gate", () => { @@ -74,4 +76,40 @@ suite("Mutation gate", () => { ); assert.deepStrictEqual(events, ["paused", "resumed"]); }); + + test("runs view commands without pausing or reloading, and only makes the commit message editor wait for a mutation", async () => { + const events: string[] = []; + let finishRefresh!: () => void; + const gate = new MutationGate( + () => events.push("paused"), + () => events.push("resumed and reloaded"), + ); + await gate.command("toggleExpand", () => events.push("expanded")); + await gate.command("createPatch", () => events.push("editor opened")); + assert.deepStrictEqual(events.splice(0), ["expanded", "editor opened"]); + + const refresh = gate.command("refresh", async () => { + events.push("refresh started"); + await new Promise((resolve) => { + finishRefresh = resolve; + }); + }); + const cancel = gate.command("cancel", () => events.push("editor closed")); + await gate.command("markPatch", () => events.push("marked")); + assert.deepStrictEqual(events, ["paused", "marked", "refresh started"]); + finishRefresh(); + await Promise.all([refresh, cancel]); + assert.deepStrictEqual(events, ["paused", "marked", "refresh started", "resumed and reloaded", "editor closed"]); + }); + + test("lists only existing commands as view commands, since a misspelled one would silently run as a mutation", () => { + const manifest = JSON.parse(readFileSync(path.resolve(__dirname, "../../../package.json"), "utf8")); + const contributed: string[] = manifest.contributes.commands.map((entry: { command: string }) => entry.command); + const listed = [...viewCommands.immediate, ...viewCommands.queued]; + assert.deepStrictEqual( + listed.filter((name) => !contributed.includes(`stgit.${name}`)), + [], + ); + assert.strictEqual(new Set(listed).size, listed.length); + }); }); diff --git a/src/test/suite/rename.test.ts b/src/test/suite/rename.test.ts index d95aac0..aca8fcb 100644 --- a/src/test/suite/rename.test.ts +++ b/src/test/suite/rename.test.ts @@ -40,6 +40,99 @@ suite("Rename Test Suite", () => { assert.deepStrictEqual(commands, ["diff"]); }); + test("Lists conflicted worktree paths once, preferring unresolved status in either order", async () => { + for (const kinds of [ + ["U", "M"], + ["M", "U"], + ]) { + const diff = [ + ":100644 100644 abc123 def456 M\0before.txt\0", + ...kinds.map((kind) => `:100644 100644 abc123 def456 ${kind}\0conflicted.txt\0`), + ":100644 100644 abc123 def456 M\0after.txt\0", + ].join(""); + const commands: string[] = []; + const reader = new RepoReader( + { topLevelDir: "/repo" }, + { + run: async (_command, args) => { + commands.push(args[0]); + return diff; + }, + runCommand: async () => ({ stdout: "", stderr: "", ecode: 0 }), + }, + ); + const workTree = new WorkTree(reader, false); + await workTree.fetchDetails(); + assert.deepStrictEqual( + workTree.deltas.map((delta) => [delta.path, delta.kind]), + [ + ["before.txt", "M"], + ["conflicted.txt", "U"], + ["after.txt", "M"], + ], + ); + assert.deepStrictEqual(commands, ["diff"]); + } + }); + + test("Removes resolved conflicts from the worktree without losing neighboring changes", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "stgit-conflict-")); + // The merge is meant to fail, so keep what it prints out of the test output + const git = (...args: string[]) => execFileSync("git", args, { cwd: dir, encoding: "utf8", stdio: "pipe" }); + try { + git("init", "-q"); + git("config", "user.name", "Test"); + git("config", "user.email", "test@example.org"); + for (const name of ["a.txt", "b.txt", "z.txt"]) { + await fs.writeFile(path.join(dir, name), "base\n"); + } + git("add", "."); + git("commit", "-qm", "initial"); + git("checkout", "-qb", "incoming"); + await fs.writeFile(path.join(dir, "b.txt"), "theirs\n"); + git("commit", "-qam", "incoming change"); + git("checkout", "-q", "-"); + await fs.writeFile(path.join(dir, "b.txt"), "ours\n"); + git("commit", "-qam", "local change"); + assert.throws(() => git("merge", "--no-edit", "incoming")); + for (const name of ["a.txt", "z.txt"]) { + await fs.writeFile(path.join(dir, name), "modified\n"); + } + + const raw = Delta.fromDiff(git("diff", "--raw", "--no-renames", "-z")); + assert.deepStrictEqual( + raw.filter((delta) => delta.path === "b.txt").map((delta) => delta.kind), + ["U", "M"], + ); + const reader = new RepoReader({ topLevelDir: dir }, { run, runCommand }); + const conflicted = new WorkTree(reader, false); + await conflicted.fetchDetails(); + assert.deepStrictEqual( + conflicted.deltas.map((delta) => [delta.path, delta.kind]), + [ + ["a.txt", "M"], + ["b.txt", "U"], + ["z.txt", "M"], + ], + ); + + await fs.writeFile(path.join(dir, "b.txt"), "resolved\n"); + git("add", "--", "b.txt"); + assert.strictEqual(git("ls-files", "-u"), ""); + const resolved = new WorkTree(reader, false); + await resolved.fetchDetails(); + assert.deepStrictEqual( + resolved.deltas.map((delta) => [delta.path, delta.kind]), + [ + ["a.txt", "M"], + ["z.txt", "M"], + ], + ); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } + }); + test("Ignores metadata-only worktree changes", async () => { const dir = await fs.mkdtemp(path.join(os.tmpdir(), "stgit-stat-")); const git = (...args: string[]) => diff --git a/src/test/suite/repo-display-loads.test.ts b/src/test/suite/repo-display-loads.test.ts index d08ef0d..bdb59c4 100644 --- a/src/test/suite/repo-display-loads.test.ts +++ b/src/test/suite/repo-display-loads.test.ts @@ -12,6 +12,301 @@ function deferred() { } suite("Repository display loads", () => { + test("publishes rows before prefetching with two workers and shares demand reads", async () => { + const shas = ["a", "b", "a", "c"].map((letter) => letter.repeat(40)); + const pending = new Map(shas.map((sha) => [sha, deferred()])); + const events: string[] = []; + const loading: boolean[] = []; + const failures: unknown[] = []; + const loads = new RepoDisplayLoads( + { topLevelDir: "/repo" }, + { + run: async () => "", + runCommand: async (_command, args) => { + const sha = args[args.length - 1]; + events.push(sha); + return { stdout: await pending.get(sha)!.promise, stderr: "", ecode: 0 }; + }, + }, + (_kind, error) => failures.push(error), + (busy) => loading.push(busy), + ); + await loads.loadSeries( + async () => shas, + () => events.push("published"), + (value) => value, + ); + assert.deepStrictEqual(events, ["published"]); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepStrictEqual(events, ["published", shas[0], shas[1]]); + assert.deepStrictEqual(loading, [true, false]); + + const demand = loads.currentReader.readCommitFiles(shas[0]); + pending.get(shas[0])!.resolve("files-a"); + assert.strictEqual(await demand, "files-a"); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepStrictEqual(events, ["published", shas[0], shas[1], shas[3]]); + pending.get(shas[1])!.resolve("files-b"); + pending.get(shas[3])!.resolve("files-c"); + await new Promise((resolve) => setImmediate(resolve)); + assert.strictEqual(await loads.currentReader.readCommitFiles(shas[3]), "files-c"); + assert.deepStrictEqual(failures, []); + assert.deepStrictEqual(loading, [true, false]); + loads.dispose(); + }); + + test("cancels scheduled and remaining prefetch on pause, disposal, repo switch and replacement loads", async () => { + for (const action of ["pause", "dispose", "switch", "reload"]) { + for (const started of [false, true]) { + const shas = ["a", "b", "c"].map((letter) => letter.repeat(40)); + const pending = new Map(shas.map((sha) => [sha, deferred()])); + const reads: string[] = []; + const loads = new RepoDisplayLoads( + { topLevelDir: "/old" }, + { + run: async () => "", + runCommand: async (_command, args) => { + const sha = args[args.length - 1]; + reads.push(sha); + return { stdout: await pending.get(sha)!.promise, stderr: "", ecode: 0 }; + }, + }, + (_kind, error) => assert.fail(String(error)), + ); + await loads.loadSeries( + async () => shas, + () => undefined, + (value) => value, + ); + if (started) { + await new Promise((resolve) => setImmediate(resolve)); + assert.strictEqual(reads.length, 2); + } + if (action === "pause") { + loads.pause(); + } else if (action === "dispose") { + loads.dispose(); + } else if (action === "switch") { + loads.switchRepository({ topLevelDir: "/new" }); + } else { + await loads.loadSeries( + async () => [], + () => undefined, + ); + } + for (const read of pending.values()) { + read.resolve("files"); + } + await new Promise((resolve) => setImmediate(resolve)); + assert.deepStrictEqual(reads, started ? shas.slice(0, 2) : [], `${action}, started=${started}`); + loads.dispose(); + } + } + }); + + test("keeps the two-worker limit across repository switches with old reads still running", async () => { + const oldShas = ["a", "b", "c"].map((letter) => letter.repeat(40)); + const newShas = ["d", "e"].map((letter) => letter.repeat(40)); + const pending = new Map([...oldShas, ...newShas].map((sha) => [sha, deferred()])); + const reads: string[] = []; + let running = 0; + let maximumRunning = 0; + const loads = new RepoDisplayLoads( + { topLevelDir: "/old" }, + { + run: async () => "", + runCommand: async (_command, args, opts) => { + const sha = args[args.length - 1]; + reads.push(`${opts?.cwd}:${sha}`); + maximumRunning = Math.max(maximumRunning, ++running); + try { + return { stdout: await pending.get(sha)!.promise, stderr: "", ecode: 0 }; + } finally { + running--; + } + }, + }, + (_kind, error) => assert.fail(String(error)), + ); + await loads.loadSeries( + async () => oldShas, + () => undefined, + (value) => value, + ); + await new Promise((resolve) => setImmediate(resolve)); + loads.switchRepository({ topLevelDir: "/new" }); + await loads.loadSeries( + async () => newShas, + () => undefined, + (value) => value, + ); + await new Promise((resolve) => setImmediate(resolve)); + assert.strictEqual(reads.length, 2); + pending.get(oldShas[0])!.resolve("old-a"); + await new Promise((resolve) => setImmediate(resolve)); + assert.strictEqual(reads.length, 3); + pending.get(oldShas[1])!.resolve("old-b"); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepStrictEqual(reads, [`/old:${oldShas[0]}`, `/old:${oldShas[1]}`, `/new:${newShas[0]}`, `/new:${newShas[1]}`]); + pending.get(newShas[0])!.resolve("new-d"); + pending.get(newShas[1])!.resolve("new-e"); + await new Promise((resolve) => setImmediate(resolve)); + assert.strictEqual(maximumRunning, 2); + assert.strictEqual(await loads.currentReader.readCommitFiles(newShas[0]), "new-d"); + assert.strictEqual(reads.length, 4); + loads.dispose(); + }); + + test("limits each prefetch batch to the cache capacity and reuses it on reload", async () => { + const shas = Array.from({ length: 501 }, (_unused, index) => index.toString(16).padStart(40, "0")); + const reads: string[] = []; + const loads = new RepoDisplayLoads( + { topLevelDir: "/repo" }, + { + run: async () => "", + runCommand: async (_command, args) => { + reads.push(args[args.length - 1]); + return { stdout: "files", stderr: "", ecode: 0 }; + }, + }, + (_kind, error) => assert.fail(String(error)), + ); + for (let reload = 0; reload < 2; reload++) { + await loads.loadSeries( + async () => shas, + () => undefined, + (value) => value, + ); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepStrictEqual(reads, shas.slice(0, 500)); + } + loads.dispose(); + }); + + test("ignores speculative failures and lets demand reads retry", async () => { + const sha = "f".repeat(40); + let attempts = 0; + const errors: unknown[] = []; + const loads = new RepoDisplayLoads( + { topLevelDir: "/repo" }, + { + run: async () => "", + runCommand: async () => { + if (++attempts === 1) { + return { stdout: "", stderr: "prefetch failed", ecode: 1 }; + } + return { stdout: "files", stderr: "", ecode: 0 }; + }, + }, + (_kind, error) => errors.push(error), + ); + await loads.loadSeries( + async () => [sha], + () => undefined, + (value) => value, + ); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepStrictEqual(errors, []); + assert.strictEqual(await loads.currentReader.readCommitFiles(sha), "files"); + assert.strictEqual(attempts, 2); + loads.dispose(); + }); + + test("reports once when a prefetch batch has been read, but not when the batch was cancelled", async () => { + const shas = ["a", "b", "c"].map((letter) => letter.repeat(40)); + const pending = new Map(shas.map((sha) => [sha, deferred()])); + const events: string[] = []; + const loads = new RepoDisplayLoads( + { topLevelDir: "/repo" }, + { + run: async () => "", + runCommand: async (_command, args) => ({ stdout: await pending.get(args[args.length - 1])!.promise, stderr: "", ecode: 0 }), + }, + (_kind, error) => assert.fail(String(error)), + ); + const load = (label: string) => + loads.loadSeries( + async () => shas, + () => events.push(`${label} published`), + (value) => value, + () => events.push(`${label} prefetched`), + ); + const tick = () => new Promise((resolve) => setImmediate(resolve)); + + await load("first"); + await tick(); + pending.get(shas[0])!.resolve("files-a"); + await tick(); + await load("second"); + await tick(); + assert.deepStrictEqual(events, ["first published", "second published"]); + pending.get(shas[1])!.resolve("files-b"); + pending.get(shas[2])!.resolve("files-c"); + await tick(); + assert.deepStrictEqual(events, ["first published", "second published", "second prefetched"]); + + await load("cached"); + await tick(); + assert.deepStrictEqual(events.slice(3), ["cached published", "cached prefetched"]); + loads.dispose(); + }); + + test("reports only current series and change reads as loading", async () => { + const oldSeries = deferred(); + const currentSeries = deferred(); + const changes = deferred(); + const loading: boolean[] = []; + const failures: string[] = []; + const loads = new RepoDisplayLoads( + { topLevelDir: "/repo" }, + { run: async () => "", runCommand: async () => ({ stdout: "", stderr: "", ecode: 0 }) }, + (_kind, error) => failures.push(String(error)), + (busy) => loading.push(busy), + ); + const stale = loads.loadSeries( + () => oldSeries.promise, + () => undefined, + ); + const files = loads.loadChanges( + () => changes.promise, + () => undefined, + ); + const current = loads.loadSeries( + () => currentSeries.promise, + () => undefined, + ); + assert.deepStrictEqual(loading, [true]); + oldSeries.resolve("stale"); + await stale; + assert.deepStrictEqual(loading, [true]); + changes.resolve("files"); + await files; + assert.deepStrictEqual(loading, [true]); + currentSeries.resolve("series"); + await current; + assert.deepStrictEqual(loading, [true, false]); + + const abandoned = deferred(); + const pending = loads.loadChanges( + () => abandoned.promise, + () => undefined, + ); + loads.pause(); + abandoned.resolve("ignored"); + await pending; + assert.deepStrictEqual(loading, [true, false, true, false]); + loads.resume(); + await loads.loadSeries( + async () => { + throw new Error("read failed"); + }, + () => undefined, + ); + assert.deepStrictEqual(loading, [true, false, true, false, true, false]); + assert.deepStrictEqual(failures, ["Error: read failed"]); + loads.dispose(); + }); + test("invalidates in-flight results and skips loads during a mutation", async () => { const oldSeries = deferred(); const oldChanges = deferred(); @@ -219,7 +514,45 @@ suite("Repository display loads", () => { series.resolve("late series"); changes.reject(new Error("late failure")); await Promise.all([pendingSeries, pendingChanges]); - assert.deepStrictEqual(shown, []); + assert.strictEqual(shown.length, 0); assert.deepStrictEqual(failures, []); + let readsAfterDispose = 0; + loads.resume(); + await loads.loadSeries( + async () => { + readsAfterDispose++; + return "late series"; + }, + (result) => shown.push(result), + ); + await loads.loadChanges( + async () => { + readsAfterDispose++; + return "late changes"; + }, + (result) => shown.push(result), + ); + assert.strictEqual(readsAfterDispose, 0); + assert.strictEqual(shown.length, 0); + }); + + test("reports no loading change when it is disposed during a read", async () => { + const series = deferred(); + const loading: boolean[] = []; + const loads = new RepoDisplayLoads( + { topLevelDir: "/repo" }, + { run: async () => "", runCommand: async () => ({ stdout: "", stderr: "", ecode: 0 }) }, + (_kind, error) => assert.fail(String(error)), + (busy) => loading.push(busy), + ); + const pending = loads.loadSeries( + () => series.promise, + () => assert.fail("published after disposal"), + ); + assert.deepStrictEqual(loading, [true]); + loads.dispose(); + series.resolve("late series"); + await pending; + assert.deepStrictEqual(loading, [true]); }); }); diff --git a/src/test/suite/repo-reader.test.ts b/src/test/suite/repo-reader.test.ts index da7e9f8..ebc8833 100644 --- a/src/test/suite/repo-reader.test.ts +++ b/src/test/suite/repo-reader.test.ts @@ -46,6 +46,113 @@ suite("Repo-bound display loads", () => { assert.deepStrictEqual(calls, ["/first", "/first"]); }); + test("shares pending commit file reads and caches empty results", async () => { + const calls: string[][] = []; + let finish!: (files: string) => void; + const reader = new RepoReader( + { topLevelDir: "/repo" }, + { + run: async () => "", + runCommand: async (_command, args) => { + calls.push(args); + const stdout = await new Promise((resolve) => { + finish = resolve; + }); + return { stdout, stderr: "", ecode: 0 }; + }, + }, + ); + const sha = "a".repeat(40); + const first = reader.readCommitFiles(sha); + const second = reader.readCommitFiles(sha); + assert.strictEqual(first, second); + assert.deepStrictEqual(calls, [["diff-tree", "--find-renames", "-z", "--no-commit-id", "-r", sha]]); + finish(""); + assert.strictEqual(await first, ""); + assert.strictEqual(await reader.readCommitFiles(sha), ""); + assert.strictEqual(calls.length, 1); + }); + + test("does not cache stdout from failed Git commands", async () => { + const reader = new RepoReader( + { topLevelDir: "/repo" }, + { + run: async () => "", + runCommand: async () => ({ stdout: "partial output", stderr: "commit lookup failed", ecode: 1 }), + }, + ); + await assert.rejects(reader.readCommitFiles("d".repeat(40)), /commit lookup failed/); + }); + + test("retries failed commit file reads instead of caching failures", async () => { + let attempts = 0; + const reader = new RepoReader( + { topLevelDir: "/repo" }, + { + run: async () => "", + runCommand: async () => { + if (++attempts === 1) { + return { stdout: "", stderr: "read failed", ecode: 1 }; + } + return { stdout: "files", stderr: "", ecode: 0 }; + }, + }, + ); + const sha = "b".repeat(40); + await assert.rejects(reader.readCommitFiles(sha), /read failed/); + assert.strictEqual(await reader.readCommitFiles(sha), "files"); + assert.strictEqual(attempts, 2); + }); + + test("isolates cached commit files between repositories and never caches live reads", async () => { + const directories: string[] = []; + const commands = { + run: async (_command: "git" | "stg", _args: string[], opts?: { cwd?: string }) => { + directories.push(opts?.cwd ?? ""); + return opts?.cwd ?? ""; + }, + runCommand: async (_command: "git" | "stg", _args: string[], opts?: { cwd?: string }) => { + directories.push(opts?.cwd ?? ""); + return { stdout: opts?.cwd ?? "", stderr: "", ecode: 0 }; + }, + }; + const oldReader = new RepoReader({ topLevelDir: "/old" }, commands); + const newReader = new RepoReader({ topLevelDir: "/new" }, commands); + const sha = "c".repeat(40); + assert.strictEqual(await oldReader.readCommitFiles(sha), "/old"); + assert.strictEqual(await newReader.readCommitFiles(sha), "/new"); + await oldReader.readCommitFiles(sha); + await newReader.readCommitFiles(sha); + await newReader.run("git", ["diff"]); + await newReader.run("git", ["diff"]); + assert.deepStrictEqual(directories, ["/old", "/new", "/new", "/new"]); + }); + + test("keeps only the 500 most recently used completed commit file lookups", async () => { + const calls: string[] = []; + const reader = new RepoReader( + { topLevelDir: "/repo" }, + { + run: async () => "", + runCommand: async (_command, args) => { + calls.push(args[args.length - 1]); + return { stdout: "files", stderr: "", ecode: 0 }; + }, + }, + ); + const sha = (index: number) => index.toString(16).padStart(40, "0"); + for (let index = 0; index < 500; index++) { + await reader.readCommitFiles(sha(index)); + } + await reader.readCommitFiles(sha(0)); + await reader.readCommitFiles(sha(500)); + await reader.readCommitFiles(sha(0)); + assert.strictEqual(calls.length, 501); + await reader.readCommitFiles(sha(1)); + assert.strictEqual(calls.length, 502); + assert.strictEqual(calls[calls.length - 1], sha(1)); + }); + test("only publishes the most recent load", async () => { const gate = new LatestLoad(); const shown: string[] = []; diff --git a/src/test/unit/branch-label.test.ts b/src/test/unit/branch-label.test.ts new file mode 100644 index 0000000..ac0e649 --- /dev/null +++ b/src/test/unit/branch-label.test.ts @@ -0,0 +1,22 @@ +import * as assert from "assert"; +import { formatUpstream } from "../../branch-label"; + +suite("Branch label", () => { + test("abbreviates an upstream with the same name as the branch", () => { + assert.strictEqual(formatUpstream("webview", "fork", "webview"), " <-> fork/*"); + assert.strictEqual(formatUpstream("feature/x", "origin", "feature/x"), " <-> origin/*"); + }); + + test("shows an upstream with a different name in full", () => { + assert.strictEqual(formatUpstream("webview", "fork", "main"), " <-> fork/main"); + }); + + test("does not abbreviate without a branch name", () => { + assert.strictEqual(formatUpstream(null, "fork", "main"), " <-> fork/main"); + }); + + test("shows only the remote when there is no upstream branch", () => { + assert.strictEqual(formatUpstream("webview", "fork", null), " (fork)"); + assert.strictEqual(formatUpstream("webview", null, null), ""); + }); +}); diff --git a/src/test/unit/comment-discard.test.ts b/src/test/unit/comment-discard.test.ts index 9bdd2b6..25327bf 100644 --- a/src/test/unit/comment-discard.test.ts +++ b/src/test/unit/comment-discard.test.ts @@ -4,17 +4,18 @@ import * as path from "path"; import { CommentDraft, confirmCommentDiscard } from "../../comment-discard"; suite("Comment discard", () => { - test("Escape closes an empty focused comment without prompting", () => { + test("Escape cancels the webview composer without invoking patch actions", () => { const manifest = JSON.parse(readFileSync(path.resolve(__dirname, "../../../package.json"), "utf8")); const bindings = manifest.contributes.keybindings.filter((binding: { key: string; command: string; when?: string }) => { - return binding.key === "escape" && binding.when?.includes("resourceScheme == stgit"); - }); - assert.strictEqual(bindings.at(-2).command, "stgit.cancel"); - assert.deepStrictEqual(bindings.at(-1), { - key: "escape", - command: "stgit.cancelEmptyComment", - when: "resourceScheme == stgit && commentEditorFocused && commentIsEmpty", + return binding.key === "escape" && binding.when?.includes("activeWebviewPanelId == stgit"); }); + assert.deepStrictEqual(bindings, [ + { + key: "escape", + command: "stgit.cancel", + when: "activeWebviewPanelId == stgit && !stgitEditing && !inQuickOpen && !terminalFocus && !inputFocus", + }, + ]); }); test("closes without asking when there are no unsaved changes", async () => { diff --git a/src/test/unit/debug-tasks.test.ts b/src/test/unit/debug-tasks.test.ts new file mode 100644 index 0000000..055f3a7 --- /dev/null +++ b/src/test/unit/debug-tasks.test.ts @@ -0,0 +1,41 @@ +import * as assert from "assert"; +import { readFileSync } from "fs"; +import * as path from "path"; +import * as ts from "typescript"; + +function readConfig(file: string): Record { + const location = path.resolve(__dirname, "../../../.vscode", file); + const parsed = ts.parseConfigFileTextToJson(location, readFileSync(location, "utf8")); + assert.strictEqual(parsed.error, undefined); + return parsed.config as Record; +} + +suite("Extension debug tasks", () => { + test("compiles host and webview assets before starting watch for every launch", () => { + const tasks = readConfig("tasks.json").tasks as { + label: string; + script?: string; + isBackground?: boolean; + dependsOn?: string[]; + dependsOrder?: string; + problemMatcher?: { base: string; background: { activeOnStart: boolean; beginsPattern: string; endsPattern: string } }; + }[]; + const compile = tasks.find((task) => task.label === "stgit: compile"); + const watch = tasks.find((task) => task.label === "stgit: watch"); + const debug = tasks.find((task) => task.label === "stgit: debug"); + assert.strictEqual(compile?.script, "compile"); + assert.strictEqual(watch?.script, "watch"); + assert.strictEqual(watch?.isBackground, true); + assert.strictEqual(watch?.problemMatcher?.base, "$tsc-watch"); + assert.strictEqual(watch?.problemMatcher?.background.activeOnStart, true); + const readiness = watch!.problemMatcher!.background; + assert.match("[0] 2:26:27 PM - Starting compilation in watch mode...", new RegExp(readiness.beginsPattern)); + assert.match("[0] 2:26:28 PM - Found 0 errors. Watching for file changes.", new RegExp(readiness.endsPattern)); + assert.doesNotMatch("[1] 2:26:28 PM - Found 0 errors. Watching for file changes.", new RegExp(readiness.endsPattern)); + assert.strictEqual(debug?.dependsOrder, "sequence"); + assert.deepStrictEqual(debug?.dependsOn, [compile.label, watch.label]); + const launches = readConfig("launch.json").configurations as { preLaunchTask: string }[]; + assert.ok(launches.length > 0); + assert.ok(launches.every((launch) => launch.preLaunchTask === debug.label)); + }); +}); diff --git a/src/test/unit/editor-layout.test.ts b/src/test/unit/editor-layout.test.ts new file mode 100644 index 0000000..e654158 --- /dev/null +++ b/src/test/unit/editor-layout.test.ts @@ -0,0 +1,45 @@ +import * as assert from "assert"; +import { EditorLayout, addColumnOnRight, isStackedBelow } from "../../editor-layout"; + +suite("Editor layout", () => { + test("finds a group directly under another, just as wide", () => { + const stacked: EditorLayout = { orientation: 1, groups: [{ size: 300 }, { size: 200 }] }; + assert.strictEqual(isStackedBelow(stacked, 0), true); + assert.strictEqual(isStackedBelow(stacked, 1), false, "nothing under the last group"); + assert.strictEqual(isStackedBelow({ orientation: 0, groups: [{}] }, 0), false); + assert.strictEqual(isStackedBelow({ orientation: 0, groups: [{}, {}] }, 0), false, "side by side"); + }); + + test("counts groups in view column order through nested columns and rows", () => { + // StGit pane over the message editor, diffs to the right + const paneOnLeft: EditorLayout = { orientation: 0, groups: [{ groups: [{}, {}] }, {}] }; + assert.deepStrictEqual( + [0, 1, 2].map((group) => isStackedBelow(paneOnLeft, group)), + [true, false, false], + ); + // Diffs to the left + const paneOnRight: EditorLayout = { orientation: 0, groups: [{}, { groups: [{}, {}] }] }; + assert.deepStrictEqual( + [0, 1, 2].map((group) => isStackedBelow(paneOnRight, group)), + [false, true, false], + ); + assert.strictEqual(isStackedBelow(paneOnRight, 3), undefined, "a group the layout does not have, as in another window"); + }); + + test("does not count a group under a whole row, or a row under a group", () => { + // [pane | other] over a group as wide as both + assert.strictEqual(isStackedBelow({ orientation: 1, groups: [{ groups: [{}, {}] }, {}] }, 0), false); + // The pane over [a | b] + assert.strictEqual(isStackedBelow({ orientation: 1, groups: [{}, { groups: [{}, {}] }] }, 0), false); + }); + + test("adds a column right of stacked groups, keeping their sizes", () => { + const stacked: EditorLayout = { orientation: 1, groups: [{ size: 300 }, { size: 200 }] }; + const widened = addColumnOnRight(stacked); + assert.deepStrictEqual(widened, { orientation: 0, groups: [{ groups: [{ size: 300 }, { size: 200 }] }, {}] }); + assert.strictEqual(isStackedBelow(widened, 0), true, "the message editor stays under the pane"); + assert.strictEqual(isStackedBelow(widened, 2), false); + const nested: EditorLayout = { orientation: 0, groups: [{ groups: [{}, {}] }] }; + assert.deepStrictEqual(addColumnOnRight(nested), { orientation: 0, groups: [{ groups: [{}, {}] }, {}] }); + }); +}); diff --git a/src/test/unit/patch-template.test.ts b/src/test/unit/patch-template.test.ts new file mode 100644 index 0000000..d2d7d73 --- /dev/null +++ b/src/test/unit/patch-template.test.ts @@ -0,0 +1,38 @@ +import * as assert from "assert"; +import { templateMessage, templateMessageLine } from "../../patch-template"; + +// As `stg new --save-template -` and `stg edit --save-template -` print them +const footer = [ + "# Please enter the message for your patch. Lines starting with", + "# '#' will be ignored. An empty message aborts the new patch.", + "# The patch name and author information may also be modified.", + "", +].join("\n"); +const newPatch = `Patch: \nAuthor: Test Person \nDate: 2026-11-28 09:01:59 +0100\n\n\n\n${footer}`; +const editPatch = `Patch: a-patch\nAuthor: Test Person \nDate: 2026-11-28 09:01:59 +0100\n\nA patch\n\nWith a body\n\n${footer}`; + +suite("Patch templates", () => { + test("a new patch's template has no message yet", () => { + assert.strictEqual(templateMessage(newPatch), ""); + }); + + test("finds the message between the header and the comments", () => { + assert.strictEqual(templateMessage(editPatch), "A patch\n\nWith a body"); + assert.strictEqual(templateMessage(editPatch.replace(/\n/g, "\r\n")), "A patch\n\nWith a body"); + }); + + test("keeps a '#' that does not start a line, and a message without a header", () => { + assert.strictEqual(templateMessage(newPatch.replace("\n\n\n\n", "\n\nFix #12\n\n")), "Fix #12"); + assert.strictEqual(templateMessage("Just a message\n# comment\n"), "Just a message"); + }); + + test("a renamed patch or another author is not a message", () => { + assert.strictEqual(templateMessage(newPatch.replace("Patch: ", "Patch: my-name")), ""); + }); + + test("the message starts after the header and the empty line below it", () => { + assert.strictEqual(templateMessageLine(newPatch), 4); + assert.strictEqual(templateMessageLine(editPatch), 4); + assert.strictEqual(templateMessageLine("Just a message\n"), 0); + }); +}); diff --git a/src/test/unit/stgit-webview.test.ts b/src/test/unit/stgit-webview.test.ts new file mode 100644 index 0000000..9ba7421 --- /dev/null +++ b/src/test/unit/stgit-webview.test.ts @@ -0,0 +1,1115 @@ +import * as assert from "assert"; +import { readFileSync } from "fs"; +import * as path from "path"; +import * as vm from "vm"; +import { buildSync } from "esbuild"; +import { JSDOM } from "jsdom"; +import * as runtime from "react/jsx-runtime"; +import * as ts from "typescript"; +import { parseStGitWebviewState, reconcileStGitSelection, reconcileStGitViewState, stgitWebviewHtml } from "../../stgit-webview"; +import type { StGitNavigation, StGitViewState, StGitWebviewState } from "../../stgit-webview"; + +async function until(condition: () => boolean) { + for (let attempt = 0; attempt < 30; attempt++) { + if (condition()) { + return; + } + await new Promise((resolve) => setTimeout(resolve, 10)); + } + assert.ok(condition(), "webview did not update in time"); +} + +suite("StGit view snapshots", () => { + function snapshot(): StGitViewState { + return { + branch: "feature/snapshots", + submodule: "", + notice: "", + noticeCommand: "", + selected: { patchId: "+:patch-a" }, + selectionVersion: 0, + loading: false, + editing: { kind: "create" }, + fileCounts: {}, + rows: ["patch-a", "patch-b"].map((name) => ({ + id: `+:${name}`, + kind: "+", + symbol: "+", + description: name, + expanded: true, + marked: false, + empty: false, + highlighted: false, + files: ["first", "second"].map((file) => ({ path: `${name}/${file}.ts`, name: file, status: "Modified", kind: "M", highlighted: false })), + })), + }; + } + + test("accepts the initial snapshot and reuses an identical cloned snapshot", () => { + const previous = snapshot(); + assert.strictEqual(reconcileStGitViewState(null, previous), previous); + assert.strictEqual(reconcileStGitViewState(previous, snapshot()), previous); + }); + + test("metadata-only updates preserve the table, selection and editing references", () => { + const previous = snapshot(); + const incoming = { ...snapshot(), loading: true, branch: "feature/updated" }; + const next = reconcileStGitViewState(previous, incoming); + assert.notStrictEqual(next, previous); + assert.strictEqual(next.loading, true); + assert.strictEqual(next.branch, incoming.branch); + assert.strictEqual(next.rows, previous.rows); + assert.strictEqual(next.selected, previous.selected); + assert.strictEqual(next.editing, previous.editing); + }); + + test("a file update replaces only its file and ancestor references without mutating either snapshot", () => { + const previous = snapshot(); + const incoming = snapshot(); + incoming.rows[0].files[0].status = "Added"; + const next = reconcileStGitViewState(previous, incoming); + assert.notStrictEqual(next.rows, previous.rows); + assert.notStrictEqual(next.rows[0], previous.rows[0]); + assert.notStrictEqual(next.rows[0].files, previous.rows[0].files); + assert.strictEqual(next.rows[0].files[0], incoming.rows[0].files[0]); + assert.strictEqual(next.rows[0].files[1], previous.rows[0].files[1]); + assert.strictEqual(next.rows[1], previous.rows[1]); + assert.deepStrictEqual(previous, snapshot()); + assert.notStrictEqual(incoming.rows[1], previous.rows[1]); + assert.deepStrictEqual(next, incoming); + }); + + test("reordering patches preserves their identities and reordering files preserves surviving file identities", () => { + const previous = snapshot(); + const incoming = snapshot(); + incoming.rows.reverse(); + const reordered = reconcileStGitViewState(previous, incoming); + assert.strictEqual(reordered.rows[0], previous.rows[1]); + assert.strictEqual(reordered.rows[1], previous.rows[0]); + + incoming.rows[0].files.reverse(); + const next = reconcileStGitViewState(reordered, incoming); + assert.strictEqual(next.rows[0].files[0], previous.rows[1].files[1]); + assert.strictEqual(next.rows[0].files[1], previous.rows[1].files[0]); + assert.strictEqual(next.rows[1], previous.rows[0]); + }); + + test("insertions and removals retain surviving patches and files", () => { + const previous = snapshot(); + const incoming = snapshot(); + incoming.rows.unshift({ ...snapshot().rows[0], id: "+:patch-new" }); + incoming.rows[1].files.shift(); + const next = reconcileStGitViewState(previous, incoming); + assert.strictEqual(next.rows.length, 3); + assert.strictEqual(next.rows[0], incoming.rows[0]); + assert.strictEqual(next.rows[1].files.length, 1); + assert.strictEqual(next.rows[1].files[0], previous.rows[0].files[1]); + assert.strictEqual(next.rows[2], previous.rows[1]); + + incoming.rows.splice(0, 2); + const removed = reconcileStGitViewState(next, incoming); + assert.strictEqual(removed.rows.length, 1); + assert.strictEqual(removed.rows[0], previous.rows[1]); + }); + + test("selection and editing updates remain visible while rows are reused", () => { + const previous = snapshot(); + const incoming = snapshot(); + incoming.selected = { patchId: "+:patch-b", path: "patch-b/first.ts" }; + incoming.editing = { kind: "edit" }; + const next = reconcileStGitViewState(previous, incoming); + assert.strictEqual(next.rows, previous.rows); + assert.strictEqual(next.selected, incoming.selected); + assert.strictEqual(next.editing, incoming.editing); + assert.strictEqual(reconcileStGitViewState(next, { ...incoming, editing: null }).editing, null); + }); + + test("file counts that arrive later replace only the counts", () => { + const previous = { ...snapshot(), fileCounts: { "+:patch-a": 2 } }; + assert.strictEqual(reconcileStGitViewState(previous, { ...snapshot(), fileCounts: { "+:patch-a": 2 } }), previous); + const incoming = { ...snapshot(), fileCounts: { "+:patch-a": 2, "+:patch-b": 5 } }; + const next = reconcileStGitViewState(previous, incoming); + assert.strictEqual(next.fileCounts, incoming.fileCounts); + assert.strictEqual(next.rows, previous.rows); + assert.strictEqual(next.selected, previous.selected); + assert.strictEqual(next.editing, previous.editing); + }); + + test("selection follows surviving row keys, not position or patch kind", () => { + const previous = snapshot(); + const incoming = snapshot(); + const selected = { patchId: "+:patch-a", path: "patch-a/first.ts" }; + incoming.rows.reverse(); + incoming.rows[1].kind = "-"; + incoming.rows[1].files.reverse(); + assert.strictEqual(reconcileStGitSelection(selected, previous.rows, incoming.rows), selected); + }); + + test("a missing file falls back to a surviving neighbor or its collapsed or empty parent", () => { + const previous = snapshot(); + const incoming = snapshot(); + const selected = { patchId: "+:patch-a", path: "patch-a/first.ts" }; + incoming.rows[0].files.shift(); + assert.deepStrictEqual(reconcileStGitSelection(selected, previous.rows, incoming.rows), { patchId: "+:patch-a", path: "patch-a/second.ts" }); + const lastRemoved = snapshot(); + lastRemoved.rows[0].files.pop(); + assert.deepStrictEqual(reconcileStGitSelection({ patchId: "+:patch-a", path: "patch-a/second.ts" }, previous.rows, lastRemoved.rows), selected); + incoming.rows[0].expanded = false; + assert.deepStrictEqual(reconcileStGitSelection(selected, previous.rows, incoming.rows), { patchId: "+:patch-a" }); + incoming.rows[0].expanded = true; + incoming.rows[0].files = []; + assert.deepStrictEqual(reconcileStGitSelection(selected, previous.rows, incoming.rows), { patchId: "+:patch-a" }); + }); + + test("a missing patch chooses the next surviving header, then the previous one, with a safe empty view", () => { + const { rows } = snapshot(); + assert.deepStrictEqual(reconcileStGitSelection({ patchId: rows[0].id, path: "patch-a/first.ts" }, rows, rows.slice(1)), { patchId: rows[1].id }); + assert.deepStrictEqual(reconcileStGitSelection({ patchId: rows[1].id }, rows, rows.slice(0, 1)), { patchId: rows[0].id }); + const selected = { patchId: "missing" }; + assert.strictEqual(reconcileStGitSelection(selected, rows, []), selected); + assert.deepStrictEqual(reconcileStGitSelection(selected, [], [{ ...rows[0], id: "I:", kind: "I" }]), { patchId: "I:" }); + }); + + test("saved webview state survives serialization and loses only the fields that cannot be trusted", () => { + const saved: Required = { + cursor: { selected: { patchId: "P:patch-a", path: "patch-a/first.ts" }, selectionVersion: 4 }, + scrollY: 140, + }; + const { cursor, scrollY } = saved; + const onHeader = { selected: { patchId: "P:patch-a" }, selectionVersion: 4 }; + assert.deepStrictEqual(parseStGitWebviewState(JSON.parse(JSON.stringify(saved))), saved); + assert.deepStrictEqual(parseStGitWebviewState({ cursor: onHeader }), { cursor: onHeader }); + assert.deepStrictEqual(parseStGitWebviewState(undefined), {}); + assert.deepStrictEqual(parseStGitWebviewState("scrollY"), {}); + assert.deepStrictEqual(parseStGitWebviewState({ scrollY: 60, filter: "from a newer version" }), { scrollY: 60 }); + assert.deepStrictEqual(parseStGitWebviewState({ ...saved, cursor: { selected: { patchId: 7 }, selectionVersion: 4 } }), { scrollY }); + assert.deepStrictEqual(parseStGitWebviewState({ ...saved, cursor: { selected: cursor.selected } }), { scrollY }); + assert.deepStrictEqual(parseStGitWebviewState({ ...saved, scrollY: "140" }), { cursor }); + // The commit message editor of older versions kept its caret and height here + assert.deepStrictEqual(parseStGitWebviewState({ ...saved, composer: { selectionStart: 3, selectionEnd: 7, height: "260px" } }), saved); + }); +}); + +suite("StGit webview", () => { + test("loads the compiled React bundle and stylesheet under a restrictive CSP", () => { + const assetRoot = path.resolve(__dirname, "../../../out/webview"); + const script = readFileSync(path.join(assetRoot, "index.js"), "utf8"); + assert.doesNotThrow(() => new vm.Script(script)); + assert.ok(readFileSync(path.join(assetRoot, "index.css"), "utf8").includes(".loading")); + const webview = { + cspSource: "vscode-resource:", + asWebviewUri: (uri: { toString(): string }) => uri, + } as unknown as Parameters[0]; + const assets = { + script: { toString: () => "vscode-resource:/out/webview/index.js?v=1" }, + style: { toString: () => "vscode-resource:/out/webview/index.css?v=1" }, + } as Parameters[1]; + const html = stgitWebviewHtml(webview, assets); + assert.match(html, /default-src 'none'/); + assert.match(html, /script-src vscode-resource:/); + assert.match(html, /src="vscode-resource:.*index\.js\?v=1"/); + assert.match(html, /href="vscode-resource:.*index\.css\?v=1"/); + assert.doesNotMatch(html, /