Repository: emeraldwalk/vscode-runonsave
Branch: main
Commit: 9b269c4375e9
Files: 34
Total size: 55.8 KB
Directory structure:
gitextract_tk17q1u7/
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.md
│ │ └── feature_request.md
│ ├── pull_request_template.md
│ └── workflows/
│ ├── prettier-check.yml
│ └── test.yml
├── .gitignore
├── .nvmrc
├── .prettierignore
├── .prettierrc.yaml
├── .vscode/
│ ├── launch.json
│ ├── settings.json
│ └── tasks.json
├── .vscodeignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── __mocks__/
│ ├── child_process.ts
│ └── vscode.ts
├── eslint.config.mjs
├── package.json
├── scripts/
│ ├── pre-release.sh
│ └── publish.sh
├── src/
│ ├── ExtensionController.ts
│ ├── SaveTracker.ts
│ ├── extension.ts
│ ├── model.ts
│ ├── test/
│ │ ├── ExtensionController.spec.ts
│ │ ├── SaveTracker.spec.ts
│ │ ├── testUtils.ts
│ │ └── utils.spec.ts
│ └── utils.ts
├── tsconfig.json
├── tsconfig.node20.json
└── tsconfig.unit.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug, triage
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Version Info:**
- OS: [e.g. iOS]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement, triage
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Additional context**
Add any other context or screenshots about the feature request here.
================================================
FILE: .github/pull_request_template.md
================================================
## Description of Changes
Summarize changes this PR introduces.
## Testing
```jsonc
{
"emeraldwalk.runonsave": {
// Example settings.json to Test Changes
},
}
```
## Checklist
- [ ] Did you update any relevant docs / samples?
- [ ] Did you include details on how to test your changes?
- [ ] Did you run `npm test` and verify all tests pass?
================================================
FILE: .github/workflows/prettier-check.yml
================================================
name: Prettier Check
on:
pull_request:
branches: [main] # Run on PRs targeting the main branch
jobs:
prettier_check:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
- name: Install dependencies
run: npm ci
- name: Run Eslint / Prettier check
# This step will fail if any files are unformatted
run: npm run format:check
================================================
FILE: .github/workflows/test.yml
================================================
name: Test
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'npm'
- run: npm ci
- run: npm test
================================================
FILE: .gitignore
================================================
out
node_modules
================================================
FILE: .nvmrc
================================================
v22.8.0
================================================
FILE: .prettierignore
================================================
package-lock.json
================================================
FILE: .prettierrc.yaml
================================================
singleQuote: true
semi: true
tabWidth: 2
trailingComma: 'all'
bracketSameLine: true
================================================
FILE: .vscode/launch.json
================================================
// A launch configuration that compiles the extension and then opens it inside a new window
{
"version": "0.1.0",
"configurations": [
{
"name": "Launch Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceRoot}",
"--disable-extensions"
],
"stopOnEntry": false,
"sourceMaps": true,
"outDir": "${workspaceRoot}/out/src",
"preLaunchTask": "npm"
},
{
"name": "Launch Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceRoot}",
"--extensionTestsPath=${workspaceRoot}/out/test",
"--disable-extensions"
],
"stopOnEntry": false,
"sourceMaps": true,
"outDir": "${workspaceRoot}/out/test",
"preLaunchTask": "npm"
}
]
}
================================================
FILE: .vscode/settings.json
================================================
// Place your settings in this file to overwrite default and user settings.
{
"files.exclude": {
"out": false // set this to true to hide the "out" folder with the compiled JS files
},
"search.exclude": {
"out": true // set this to false to include "out" folder in search results
},
"typescript.tsdk": "./node_modules/typescript/lib" // we want to use the TS server from our node_modules folder to control its version
}
================================================
FILE: .vscode/tasks.json
================================================
// Available variables which can be used inside of strings.
// ${workspaceRoot}: the root folder of the team
// ${file}: the current opened file
// ${fileBasename}: the current opened file's basename
// ${fileDirname}: the current opened file's dirname
// ${fileExtname}: the current opened file's extension
// ${cwd}: the current working directory of the spawned process
// A task runner that calls a custom npm script that compiles the extension.
{
"version": "2.0.0",
// we want to run npm
"command": "npm",
// we run the custom script "compile" as defined in package.json
"args": ["run", "compile", "--loglevel", "silent"],
// The tsc compiler is started in watching mode
"isWatching": true,
// use the standard tsc in watch mode problem matcher to find compile problems in the output.
"problemMatcher": "$tsc-watch",
"tasks": [
{
"label": "npm",
"type": "shell",
"command": "npm",
"args": ["run", "compile", "--loglevel", "silent"],
"isBackground": true,
"problemMatcher": "$tsc-watch",
"group": {
"_id": "build",
"isDefault": false
}
}
]
}
================================================
FILE: .vscodeignore
================================================
### Ignore everything ####
**/*
#### Explicitly add things back ####
!LICENSE
!package.json
!README.md
!images/**
!out/**
================================================
FILE: CONTRIBUTING.md
================================================
## Testing
Unit tests run via `vitest`. The `src/test` folder is excluded from the extension build (`tsconfig.json`). They are included when running tests (`tsconfig.unit.json`).
Run tests by running:
```sh
npm test
```
## Release Process
1. Ensure on commit to be released
- For pre-release, this should be the latest `main` since `package.json` version will be updated
- For release, this will be a previously released pre-release tag. The version will not be updated in the `main` branch, only in the newly created release branch
1. Make sure all unit tests pass `npm test`
1. Verify contents to publish `vsce ls`
1. Package local `.vsix` for testing `npm run package:latest`
### Publishing
To verify auth token still works, run:
```sh
npx vsce login <publisher>
```
When prompted for PAT, can copy $VSCE_PAT value. If it still works, we're good, otherwise need to generate new one in Azure DevOps.
#### Pre-Release
1. Main branch should stay on pre-release versions
1. Checkout to latest commit on `main`
1. Run `npm install`
1. Run the following script to do a pre-release:
```sh
# Update the arg to the next patch version
scripts/pre-release.sh patch
```
#### Release
Releases will create a release/vX.X.X branch from a pre-release tag and increment the version there and tag the release commit.
1. Checkout to pre-release tag to publish
1. Adjust the tag version to corresponding release version.
e.g. v1.1.2-pre -> 1.0.2
```sh
./scripts/publish.sh 1.0.x
```
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# Run On Save for Visual Studio Code
This extension allows configuring commands that get run whenever a file is saved in vscode.
NOTE: Commands only get run when saving an existing file. Creating new files, and Save as... don't trigger the commands.
## Features
- Configure multiple commands that run when a file is saved
- Regex pattern matching for files that trigger commands running
- Sync and async support
## Configuration
Add "emeraldwalk.runonsave" configuration to user or workspace settings.
- `shell` - (optional) shell path to be used with child_process.exec options that runs commands.
- `autoClearConsole` - (optional) clear VSCode output console every time commands run. Defaults to false.
- `ignoreUnchangedFiles` - (optional) ignore files that have not changed since the last save. Defaults to false.
- `message` - Message to output before all commands.
- `messageAfter` - Message to output after all commands have finished.
- `showElapsed` - Show total elapsed time after all commands have finished.
- `commands` - array of commands that will be run whenever a file is saved.
- `match` - a regex for matching which files to run commands on (see [Notes on RegEx Options](#notes-on-regex-options)).
- `notMatch` - a regex for matching which files **NOT** to run. Files that match this pattern take precedence over ones that match the `match` option (see [Notes on RegEx Options](#notes-on-regex-options)).
- `cmd` - command to run. Can include parameters that will be replaced at runtime (see Placeholder Tokens section below).
- `isAsync` (optional) - defaults to false. If true, next command will be run before this one finishes.
- `message` - Message to output before this command. Can also include placeholders.
- `messageAfter` - Message to output after this command has finished. Can also include placeholders.
- `showElapsed` - Show total elapsed time after this command.
- `autoShowOutputPanel` - Automatically shows the output panel:
- `never` - Never changes the output panel visibility (default).
- `always` - Shows output panel when the first command starts.
- `error` - Shows output panel when a command fails.
### Notes on RegEx Options
The `match` and `notMatch` options expect RegEx patterns.
- The pattern will be run against the absolute file path. This means you usually don't want to start the pattern with `^` unless you are putting a full pattern to match the absolute path.
e.g. Use `"match": "somefile\\.txt$"` instead of `"match": "^somefile\\.txt$"` if you are targeting `somefile.txt` in your workspace.
- Since settings are defined in `json`, backslashes have to be double escaped.
e.g. If you were targeting a file path on a Windows system, you'd have to escape `\` once because it's a RegEx and a 2nd time since you are in a `json` string:
`"match": "some\\\\folder\\\\.*"`
### Sample Configurations
#### All Files
```jsonc
{
"emeraldwalk.runonsave": {
"commands": [
{
// Run whenever any file is saved
"match": ".*",
"cmd": "echo '${fileBasename}' saved.",
},
],
},
}
```
#### Specific File Extensions
```jsonc
{
"emeraldwalk.runonsave": {
"commands": [
{
// Run whenever html, css, or js files are saved
"match": "\\.(html|css|js)$",
"cmd": "echo '${fileBasename}' saved.",
},
],
},
}
```
#### Exclude a File
```jsonc
{
"emeraldwalk.runonsave": {
"commands": [
{
// Match all html, css, and js files
// except for `exclude-me.js`
"match": "\\.(html|css|js)$",
"notMatch": "exclude-me\\.js$",
"cmd": "echo '${fileBasename}' saved.",
},
],
},
}
```
#### Exclude .vscode Folder
```jsonc
{
"emeraldwalk.runonsave": {
"commands": [
{
// Match all .json files except for ones in
// .vscode directory
"match": "\\.json$",
"notMatch": "\\.vscode/.*$",
"cmd": "echo '${fileBasename}' saved.",
},
],
},
}
```
#### Mix of Parallel + Sequential Commands
```jsonc
{
"emeraldwalk.runonsave": {
"commands": [
{
"match": ".*",
// This tells next command to run immediately after
// this one starts instead of waiting for it to complete
"isAsync": true,
"cmd": "echo 'I run for all files.'",
},
{
"match": "\\.txt$",
"cmd": "echo 'I am a .txt file ${file}.'",
},
{
"match": "\\.js$",
"cmd": "echo 'I am a .js file ${file}.'",
},
{
"match": ".*",
"cmd": "echo 'I am ${env.USERNAME}.'",
},
],
},
}
```
#### Messages
```jsonc
{
"emeraldwalk.runonsave": {
// Messages to show before & after all commands
"message": "*** All Start ***",
"messageAfter": "*** All Complete ***",
// Show elapsed time for all commands
"showElapsed": true,
"commands": [
{
"match": ".*",
"cmd": "echo 1st Command",
// Messages to run before / after this cmd
"message": "- 1. Start",
"messageAfter": "- 1. Complete",
// Show elapsed time for this cmd
"showElapsed": true,
},
{
"message": "Message only",
},
{
"match": ".*",
"cmd": "echo 2nd Command",
// Messages to run before / after this cmd
"message": "- 2. Start",
"messageAfter": "- 2. Complete",
// Show elapsed time for this cmd
"showElapsed": true,
},
],
},
}
```
## Output of the commands
Please see the output in Output window and then switch the right side drop down to "Run On Save" to see the output of the commands stdout
## Commands
The following commands are exposed in the command palette:
- On Save: Enable
- On Save: Disable
- On Save: Toggle
## Placeholder Tokens
Commands and messages support placeholders similar to tasks.json.
- ~~`${workspaceRoot}`~~: DEPRECATED use `${workspaceFolder}` instead
- `${workspaceFolder}`: the path of the workspace folder of the saved file
- `${file}`: path of saved file
- `${fileBasename}`: saved file's basename
- `${fileDirname}`: directory name of saved file
- `${fileExtname}`: extension (including .) of saved file
- `${fileBasenameNoExt}`: saved file's basename without extension
- `${relativeFile}` - the current opened file relative to `${workspaceFolder}`
- `${cwd}`: current working directory (this is the working directory that vscode is running in not the project directory)
### Environment Variable Tokens
- `${env.Name}`
## Links
- [Marketplace](https://marketplace.visualstudio.com/items/emeraldwalk.RunOnSave)
- [Source Code](https://github.com/emeraldwalk/vscode-runonsave)
## License
[Apache](https://github.com/emeraldwalk/vscode-runonsave/blob/master/LICENSE)
================================================
FILE: __mocks__/child_process.ts
================================================
import { vi } from 'vitest';
export class ChildProcess {
on() {}
stdout = {
on() {},
};
stderr = {
on() {},
};
}
export const exec = vi.fn();
================================================
FILE: __mocks__/vscode.ts
================================================
import { vi } from 'vitest';
export const window = {
createOutputChannel: vi.fn(() => ({
appendLine: vi.fn(),
})),
};
export const workspace = {
getConfiguration: vi.fn(),
getWorkspaceFolder: vi.fn(),
};
================================================
FILE: eslint.config.mjs
================================================
import typescriptEslint from '@typescript-eslint/eslint-plugin';
import tsParser from '@typescript-eslint/parser';
import eslintConfigPrettier from 'eslint-config-prettier/flat';
export default [
{
files: ['**/*.ts'],
},
{
plugins: {
'@typescript-eslint': typescriptEslint,
},
languageOptions: {
parser: tsParser,
ecmaVersion: 2022,
sourceType: 'module',
},
rules: {
'@typescript-eslint/naming-convention': [
'warn',
{
selector: 'import',
format: ['camelCase', 'PascalCase'],
},
],
curly: 'warn',
'no-throw-literal': 'warn',
semi: 'warn',
},
},
eslintConfigPrettier,
];
================================================
FILE: package.json
================================================
{
"name": "RunOnSave",
"displayName": "Run on Save",
"description": "Run commands when a file is saved in vscode.",
"icon": "images/save-icon.png",
"galleryBanner": {
"color": "#3e136e",
"theme": "dark"
},
"version": "1.1.5",
"engines": {
"vscode": "^1.86.0"
},
"publisher": "emeraldwalk",
"license": "Apache-2.0",
"homepage": "https://github.com/emeraldwalk/vscode-runonsave/blob/master/README.md",
"repository": {
"type": "git",
"url": "https://github.com/emeraldwalk/vscode-runonsave.git"
},
"bugs": {
"url": "https://github.com/emeraldwalk/vscode-runonsave/issues"
},
"categories": [
"Other"
],
"activationEvents": [
"*"
],
"main": "./out/extension",
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"format": "eslint src && prettier . --write",
"format:check": "eslint src && prettier . --check",
"test": "vitest",
"package:latest": "npx vsce package -o releases/runonsave-latest.vsix"
},
"contributes": {
"commands": [
{
"command": "extension.emeraldwalk.enableRunOnSave",
"title": "Run On Save: Enable"
},
{
"command": "extension.emeraldwalk.disableRunOnSave",
"title": "Run On Save: Disable"
},
{
"command": "extension.emeraldwalk.toggleRunOnSave",
"title": "Run On Save: Toggle"
}
],
"configuration": {
"title": "Run On Save command configuration.",
"type": "object",
"properties": {
"emeraldwalk.runonsave": {
"type": "object",
"properties": {
"autoClearConsole": {
"type": "boolean",
"description": "Automatically clear the console on each save before running commands.",
"default": false
},
"ignoreUnchangedFiles": {
"type": "boolean",
"description": "Ignore files that have not changed since the last save.",
"default": false
},
"shell": {
"type": "string",
"description": "Shell to execute the command with (gets passed to child_process.exec as an options arg. e.g. child_process(cmd, { shell })."
},
"message": {
"type": "string",
"description": "Optional message to show before all commands run."
},
"messageAfter": {
"type": "string",
"description": "Optional message to show after all command runs."
},
"showElapsed": {
"type": "boolean",
"description": "Print elapsed time for all of the commands.",
"default": false
},
"commands": {
"type": "array",
"items": {
"type": "object",
"properties": {
"match": {
"type": "string",
"description": "Regex for matching files to run commands on \n\nNOTE: This is a regex and not a file path spce, so backslashes have to be escaped. They also have to be escaped in json strings, so you may have to double escape them in certain cases such as targetting contents of folders.\n\ne.g.\n\"match\": \"some\\\\\\\\directory\\\\\\\\.*\"",
"default": ".*"
},
"notMatch": {
"type": "string",
"description": "Regex for matching files *not* to run commands on.",
"default": ".*"
},
"cmd": {
"type": "string",
"description": "Command to execute on save."
},
"isAsync": {
"type": "boolean",
"description": "Run command asynchronously.",
"default": false
},
"message": {
"type": "string",
"description": "Optional message to show before command runs."
},
"messageAfter": {
"type": "string",
"description": "Optional message to show after command runs."
},
"showElapsed": {
"type": "boolean",
"description": "Print elapsed time for the command.",
"default": false
},
"autoShowOutputPanel": {
"description": "Automatically shows the output panel.",
"type": "string",
"default": "never",
"enum": [
"never",
"always",
"error"
]
}
}
}
}
}
}
}
}
},
"devDependencies": {
"@types/mocha": "^10.0.8",
"@types/node": "22.7.4",
"@types/vscode": "^1.86.0",
"@typescript-eslint/eslint-plugin": "^8.7.0",
"@typescript-eslint/parser": "^8.7.0",
"@vscode/test-cli": "^0.0.10",
"@vscode/test-electron": "^2.4.1",
"eslint": "^9.11.1",
"eslint-config-prettier": "^10.1.8",
"prettier": "3.7.4",
"typescript": "^5.6.2",
"vitest": "^4.0.14"
}
}
================================================
FILE: scripts/pre-release.sh
================================================
# Pre-release vscode extension. Requires version as argument.
if [ $# -ne 1 ]; then
echo "Pre-release version required."
exit 1
fi
set -e
# explicit version or minor/major/patch to increment
version=$1
vsce publish \
--allow-star-activation \
--no-git-tag-version \
--pre-release \
$version
# Read the actual version from package.json after publish
new_version=$(node -p "require('./package.json').version")
tag="v${new_version}-pre"
git add package*.json
git commit -m "$tag"
git tag "$tag"
git push --tags
git push
================================================
FILE: scripts/publish.sh
================================================
#!/bin/bash
#
# Publish Script for VS Code Run On Save Extension
#
# This script publishes a new version of the vscode-runonsave extension to the
# VS Code Marketplace. It creates a release branch, publishes the extension,
# and tags the release.
#
# Usage: ./scripts/publish.sh <version>
# Example: ./scripts/publish.sh 1.0.x
if [ $# -ne 1 ]; then
echo "Version required."
exit 1
fi
set -e
# explicit version
version=$1
tag=v$version-release
git checkout -b release/$version
vsce publish \
--allow-star-activation \
--no-git-tag-version \
$version
git add package*.json
git commit -m "$tag"
git tag "$tag"
git push --tags
git push -u origin HEAD
git checkout main
================================================
FILE: src/ExtensionController.ts
================================================
import { exec } from 'child_process';
import * as vscode from 'vscode';
import type { Document, ICommand, IConfig, IExecResult } from './model';
import {
doReplacement,
getReplacements,
getWorkspaceFolderPath,
} from './utils';
import { SaveTracker } from './SaveTracker';
export class ExtensionController {
private _outputChannel: vscode.OutputChannel;
private _context: vscode.ExtensionContext;
private _config: IConfig;
private _saveTracker: SaveTracker;
constructor(context: vscode.ExtensionContext) {
this._context = context;
this._outputChannel = vscode.window.createOutputChannel('Run On Save');
this.loadConfig();
this._saveTracker = new SaveTracker(
this.runCommands.bind(this),
() => this.ignoreUnchangedFiles,
);
}
/** Recursive call to run commands. */
private async _runCommands(
commandsOrig: Array<ICommand>,
document: Document,
): Promise<void> {
const cmds = [...commandsOrig];
const startMs = performance.now();
let pendingCount = cmds.length;
const onCmdComplete = (cfg: ICommand, res: IExecResult) => {
--pendingCount;
this.showOutputMessageIfDefined(cfg.messageAfter);
this.showOutputMessageIfDefined(
cfg.showElapsed && `Elapsed ms: ${res.elapsedMs}`,
);
if (cfg.autoShowOutputPanel === 'error' && res.statusCode !== 0) {
this._outputChannel.show(true);
}
if (pendingCount === 0) {
this.showOutputMessageIfDefined(this._config.messageAfter);
const totalElapsedMs = performance.now() - startMs;
this.showOutputMessageIfDefined(
this._config.showElapsed && `Total elapsed ms: ${totalElapsedMs}`,
);
}
};
this.showOutputMessageIfDefined(this._config?.message);
while (cmds.length > 0) {
const cfg = cmds.shift();
this.showOutputMessageIfDefined(cfg.message);
if (cfg.autoShowOutputPanel === 'always') {
this._outputChannel.show(true);
}
if (cfg.cmd == null) {
onCmdComplete(cfg, { elapsedMs: 0, statusCode: 0 });
continue;
}
const cmdPromise = this._getExecPromise(cfg, document);
// TODO: `isAsync` should probably be named something like `isParallel`,
// but will have to think about how to not make that a breaking change
const isParallel = cfg.isAsync;
if (isParallel) {
// If this is marked as parallel, don't `await` the promise
void cmdPromise.then((elapsedMs) => {
onCmdComplete(cfg, elapsedMs);
});
continue;
}
// for serial commands wait till complete
const elapsedMs = await cmdPromise;
onCmdComplete(cfg, elapsedMs);
}
}
private _getExecPromise(
cfg: ICommand,
document: Document,
): Promise<IExecResult> {
return new Promise((resolve) => {
const startMs = performance.now();
const child = exec(cfg.cmd, this._getExecOption(document));
child.stdout.on('data', (data) => this._outputChannel.append(data));
child.stderr.on('data', (data) => this._outputChannel.append(data));
child.on('error', (e) => {
this.showOutputMessage(e.message);
// Don't reject since we want to be able to chain and handle
// message properties even if this errors
// Returns a status code different than zero to optionally show output
// panel with error
resolve({ elapsedMs: performance.now() - startMs, statusCode: 1 });
});
child.on('exit', (statusCode) => {
resolve({ elapsedMs: performance.now() - startMs, statusCode });
});
});
}
private _getExecOption(document: Document): {
shell: string;
cwd: string;
} {
return {
shell: this.shell,
cwd: getWorkspaceFolderPath(document.uri),
};
}
public get isEnabled(): boolean {
return !!this._context.globalState.get('isEnabled', true);
}
public set isEnabled(value: boolean) {
this._context.globalState.update('isEnabled', value);
this.showOutputMessage();
}
public get shell(): string {
return this._config.shell;
}
public get autoClearConsole(): boolean {
return !!this._config.autoClearConsole;
}
public get ignoreUnchangedFiles(): boolean {
return !!this._config.ignoreUnchangedFiles;
}
public get commands(): Array<ICommand> {
return this._config.commands || [];
}
/**
* Handle a save for the given Document.
*/
public onDidSave(document: Document): void {
this._saveTracker.onDidSave(document);
}
/**
* Enqueue a save for the given Document.
*/
public onWillSave(document: Document): void {
this._saveTracker.onWillSave(document);
}
public loadConfig(): void {
this._config = <IConfig>(
(<any>vscode.workspace.getConfiguration('emeraldwalk.runonsave'))
);
}
/**
* Show message in output channel
*/
public showOutputMessage(message?: string): void {
message =
message || `Run On Save ${this.isEnabled ? 'enabled' : 'disabled'}.`;
this._outputChannel.appendLine(message);
}
/**
* Show message in output channel if it is defined and not `false`.
*/
public showOutputMessageIfDefined(message?: string | null | false): void {
if (!message) {
return;
}
this.showOutputMessage(message);
}
/**
* Show message in status bar and output channel.
* Return a disposable to remove status bar message.
*/
public showStatusMessage(message: string): vscode.Disposable {
this.showOutputMessage(message);
return vscode.window.setStatusBarMessage(message);
}
public runCommands(document: Document): Promise<void> {
if (this.autoClearConsole) {
this._outputChannel.clear();
}
if (!this.isEnabled || this.commands.length === 0) {
this.showOutputMessage();
return;
}
const match = (pattern: string) =>
pattern &&
pattern.length > 0 &&
new RegExp(pattern).test(document.uri.fsPath);
const commandConfigs = this.commands.filter((cfg) => {
const matchPattern = cfg.match || '';
const negatePattern = cfg.notMatch || '';
// if no match pattern was provided, or if match pattern succeeds
const isMatch = matchPattern.length === 0 || match(matchPattern);
// negation has to be explicitly provided
const isNegate = negatePattern.length > 0 && match(negatePattern);
// negation wins over match
return !isNegate && isMatch;
});
if (commandConfigs.length === 0) {
return;
}
// build our commands by replacing parameters with values
const commands: Array<ICommand> = [];
for (const cfg of commandConfigs) {
const replacements = getReplacements(document.uri);
commands.push({
message: doReplacement(cfg.message, replacements),
messageAfter: doReplacement(cfg.messageAfter, replacements),
cmd: doReplacement(cfg.cmd, replacements),
isAsync: !!cfg.isAsync,
showElapsed: cfg.showElapsed,
autoShowOutputPanel: cfg.autoShowOutputPanel,
});
}
return this._runCommands(commands, document);
}
}
================================================
FILE: src/SaveTracker.ts
================================================
import * as vscode from 'vscode';
import type { Document, UriString } from './model';
/**
* Tracks pending saves for documents and determines when to execute commands
* based on the ignoreUnchangedFiles setting.
*/
export class SaveTracker {
private _pendingSaveMap = new Map<UriString, number>();
private _getIgnoreUnchangedFiles: () => boolean;
private _runner: (document: Document) => void;
constructor(
runner: (document: Document) => void,
getIgnoreUnchangedFiles: () => boolean,
) {
this._runner = runner;
this._getIgnoreUnchangedFiles = getIgnoreUnchangedFiles;
}
/**
* Get the number of pending saves for a given URI.
*/
public getPendingSaveCount(uri: vscode.Uri): number {
return this._pendingSaveMap.get(uri.fsPath) ?? 0;
}
/**
* Enqueue a save for the given Document.
*/
public onWillSave(document: Document): void {
if (!document.isDirty) {
return;
}
const count = this._pendingSaveMap.get(document.uri.fsPath) || 0;
this._pendingSaveMap.set(document.uri.fsPath, count + 1);
}
/**
* Handle a save for the given Document.
*/
public onDidSave(document: Document): void {
const prevCount = this.getPendingSaveCount(document.uri);
if (prevCount > 1) {
this._pendingSaveMap.set(document.uri.fsPath, prevCount - 1);
} else {
this._pendingSaveMap.delete(document.uri.fsPath);
}
const isUnchanged = prevCount <= 0;
if (isUnchanged && this._getIgnoreUnchangedFiles()) {
return;
}
this._runner(document);
}
}
================================================
FILE: src/extension.ts
================================================
import * as vscode from 'vscode';
import { ExtensionController } from './ExtensionController';
export function activate(context: vscode.ExtensionContext): void {
const extension = new ExtensionController(context);
extension.showOutputMessage();
vscode.workspace.onDidChangeConfiguration(() => {
const disposeStatus = extension.showStatusMessage(
'Run On Save: Reloading config.',
);
extension.loadConfig();
disposeStatus.dispose();
});
vscode.commands.registerCommand(
'extension.emeraldwalk.enableRunOnSave',
() => {
extension.isEnabled = true;
},
);
vscode.commands.registerCommand(
'extension.emeraldwalk.disableRunOnSave',
() => {
extension.isEnabled = false;
},
);
vscode.commands.registerCommand(
'extension.emeraldwalk.toggleRunOnSave',
() => {
extension.isEnabled = !extension.isEnabled;
},
);
vscode.workspace.onWillSaveTextDocument(
(event: vscode.TextDocumentWillSaveEvent) => {
extension.onWillSave(event.document);
},
);
vscode.workspace.onDidSaveTextDocument((document: vscode.TextDocument) => {
extension.onDidSave(document);
});
vscode.workspace.onWillSaveNotebookDocument(
(event: vscode.NotebookDocumentWillSaveEvent) => {
extension.onWillSave(event.notebook);
},
);
vscode.workspace.onDidSaveNotebookDocument(
(notebookDocument: vscode.NotebookDocument) => {
extension.onDidSave(notebookDocument);
},
);
}
================================================
FILE: src/model.ts
================================================
import * as vscode from 'vscode';
/**
* A union of `vscode.TextDocument` and `vscode.NotebookDocument`
* to support both types in command execution and event handling.
*/
export type Document = vscode.TextDocument | vscode.NotebookDocument;
export type UriString = string;
export interface IMessageConfig {
message?: string;
messageAfter?: string;
showElapsed: boolean;
}
export interface ICommand extends IMessageConfig {
match?: string;
notMatch?: string;
cmd?: string;
isAsync: boolean;
autoShowOutputPanel?: 'always' | 'error' | 'never';
}
export interface IConfig extends IMessageConfig {
shell: string;
autoClearConsole: boolean;
ignoreUnchangedFiles: boolean;
commands: Array<ICommand>;
}
export interface IExecResult {
statusCode: number;
elapsedMs: number;
}
export type StringReplacer = Parameters<String['replace']>[1];
export type StringReplaceParams =
| [RegExp, string]
| [RegExp, (substring: string, envName: string) => string];
================================================
FILE: src/test/ExtensionController.spec.ts
================================================
import * as vscode from 'vscode';
import { expect, it, vi } from 'vitest';
import { exec } from 'child_process';
import { ExtensionController } from '../ExtensionController';
import {
MockChildProcess,
createUri,
createDocument,
createWorkspaceFolder,
} from './testUtils';
vi.mock('child_process');
vi.mock('vscode');
const cmd = {
sequentialMatchAll: (status: number | string) => ({
match: '.*',
isAsync: false,
cmd: 'sequentialMatchAll:${file}',
status,
}),
sequentialMatchTxt: (status: number | string) => ({
match: '.*\\.txt',
isAsync: false,
cmd: 'sequentialMatchTxt:${file}',
status,
}),
parallelMatchAll: (status: number | string) => ({
match: '.*',
isAsync: true,
cmd: 'parallelMatchAll:${file}',
status,
}),
parallelMatchTxt: (status: number | string) => ({
match: '.*\\.txt',
isAsync: true,
cmd: 'parallelMatchTxt:${file}',
status,
}),
};
const file = {
txt1: createUri('file1.txt'),
txt2: createUri('file2.txt'),
};
const doc = {
txt1: createDocument(file.txt1),
txt2: createDocument(file.txt2),
};
const wksp = {
a: createWorkspaceFolder('/workspace/a'),
};
const globalState = {
get: vi.fn(),
update: vi.fn(),
} as unknown as vscode.Memento;
const context = { globalState } as vscode.ExtensionContext;
it.each([
{
label: 'Sequential commands with single document',
commands: [cmd.sequentialMatchAll(0), cmd.sequentialMatchTxt(0)],
docs: [doc.txt1],
wksp: wksp.a,
expected: [
'sequentialMatchAll:file1.txt:start',
'sequentialMatchAll:file1.txt:end',
'sequentialMatchTxt:file1.txt:start',
'sequentialMatchTxt:file1.txt:end',
],
},
{
label: 'Sequential commands with multiple documents',
commands: [cmd.sequentialMatchAll(0), cmd.sequentialMatchTxt(0)],
docs: [doc.txt1, doc.txt2],
wksp: wksp.a,
expected: [
'sequentialMatchAll:file1.txt:start',
'sequentialMatchAll:file2.txt:start',
'sequentialMatchAll:file1.txt:end',
'sequentialMatchAll:file2.txt:end',
'sequentialMatchTxt:file1.txt:start',
'sequentialMatchTxt:file2.txt:start',
'sequentialMatchTxt:file1.txt:end',
'sequentialMatchTxt:file2.txt:end',
],
},
{
label: 'Parallel commands with single document',
commands: [cmd.parallelMatchAll(0), cmd.parallelMatchTxt(0)],
docs: [doc.txt1],
wksp: wksp.a,
expected: [
'parallelMatchAll:file1.txt:start',
'parallelMatchTxt:file1.txt:start',
'parallelMatchAll:file1.txt:end',
'parallelMatchTxt:file1.txt:end',
],
},
{
label: 'Parallel commands with multiple documents',
commands: [cmd.parallelMatchAll(0), cmd.parallelMatchTxt(0)],
docs: [doc.txt1, doc.txt2],
wksp: wksp.a,
expected: [
'parallelMatchAll:file1.txt:start',
'parallelMatchTxt:file1.txt:start',
'parallelMatchAll:file2.txt:start',
'parallelMatchTxt:file2.txt:start',
'parallelMatchAll:file1.txt:end',
'parallelMatchTxt:file1.txt:end',
'parallelMatchAll:file2.txt:end',
'parallelMatchTxt:file2.txt:end',
],
},
{
label: 'Mixed sequential and parallel commands with single document',
commands: [
cmd.sequentialMatchAll(0),
cmd.parallelMatchAll(0),
cmd.sequentialMatchTxt(0),
],
docs: [doc.txt1],
wksp: wksp.a,
expected: [
'sequentialMatchAll:file1.txt:start',
'sequentialMatchAll:file1.txt:end',
'parallelMatchAll:file1.txt:start',
'sequentialMatchTxt:file1.txt:start',
'parallelMatchAll:file1.txt:end',
'sequentialMatchTxt:file1.txt:end',
],
},
{
label: 'Mixed sequential and parallel commands with multiple documents',
commands: [
cmd.sequentialMatchAll(0),
cmd.parallelMatchAll(0),
cmd.sequentialMatchTxt(0),
],
docs: [doc.txt1, doc.txt2],
wksp: wksp.a,
expected: [
'sequentialMatchAll:file1.txt:start',
'sequentialMatchAll:file2.txt:start',
'sequentialMatchAll:file1.txt:end',
'sequentialMatchAll:file2.txt:end',
'parallelMatchAll:file1.txt:start',
'sequentialMatchTxt:file1.txt:start',
'parallelMatchAll:file2.txt:start',
'sequentialMatchTxt:file2.txt:start',
'parallelMatchAll:file1.txt:end',
'sequentialMatchTxt:file1.txt:end',
'parallelMatchAll:file2.txt:end',
'sequentialMatchTxt:file2.txt:end',
],
},
])(
'should run commands: $label',
async ({ commands, docs, wksp, expected }) => {
const config = {
commands,
} as unknown as vscode.WorkspaceConfiguration;
vi.mocked(globalState.get).mockReturnValue(true);
vi.mocked(vscode.workspace.getConfiguration).mockReturnValue(config);
vi.mocked(vscode.workspace.getWorkspaceFolder).mockReturnValue(wksp);
// Note: this works as long as each cmd is unique
const statusMap = new Map(
commands.map(({ cmd, status }) => [cmd.split(':')[0], status]),
);
const logs: string[] = [];
vi.mocked(exec).mockImplementation((command: string, options) => {
logs.push(`${command}:start:${JSON.stringify(options)}`);
const status = statusMap.get(command.split(':')[0]);
const promise =
typeof status === 'number'
? Promise.resolve(status)
: Promise.reject(status);
promise.finally(() => {
logs.push(`${command}:end:${JSON.stringify(options)}`);
});
return new MockChildProcess(promise);
});
const instance = new ExtensionController(context);
await Promise.all(docs.map((doc) => instance.runCommands(doc)));
expect(logs).toEqual(
expected.map((ex) => `${ex}:${JSON.stringify({ cwd: wksp.uri.fsPath })}`),
);
},
);
================================================
FILE: src/test/SaveTracker.spec.ts
================================================
import { describe, expect, it, vi } from 'vitest';
import { SaveTracker } from '../SaveTracker';
import { createDocument } from './testUtils';
describe('SaveTracker', () => {
it.each([
{
isDirty: true,
ignoreUnchanged: false,
shouldEnqueue: true,
shouldRun: true,
filename: 'file1.txt',
},
{
isDirty: true,
ignoreUnchanged: true,
shouldEnqueue: true,
shouldRun: true,
filename: 'file1.txt',
},
{
isDirty: false,
ignoreUnchanged: false,
shouldEnqueue: false,
shouldRun: true,
filename: 'file1.txt',
},
{
isDirty: false,
ignoreUnchanged: true,
shouldEnqueue: false,
shouldRun: false,
filename: 'file1.txt',
},
])(
'isDirty=$isDirty ignore=$ignoreUnchanged -> enqueue=$shouldEnqueue run=$shouldRun',
({ isDirty, ignoreUnchanged, shouldEnqueue, shouldRun, filename }) => {
const runner = vi.fn();
const getIgnoreUnchangedFiles = vi.fn().mockReturnValue(ignoreUnchanged);
const tracker = new SaveTracker(runner, getIgnoreUnchangedFiles);
const doc = createDocument(`/${filename}`, isDirty);
tracker.onWillSave(doc);
expect(tracker.getPendingSaveCount(doc.uri)).toBe(shouldEnqueue ? 1 : 0);
tracker.onDidSave(doc);
expect(tracker.getPendingSaveCount(doc.uri)).toBe(0);
if (shouldRun) {
expect(runner).toHaveBeenCalledWith(doc);
} else {
expect(runner).not.toHaveBeenCalled();
}
},
);
});
================================================
FILE: src/test/testUtils.ts
================================================
import * as vscode from 'vscode';
import { ChildProcess } from 'child_process';
import { type Document } from '../model';
export class MockChildProcess extends ChildProcess {
constructor(private _promise: Promise<number>) {
super();
this._init();
}
private _eventHandlers = new Map<string, Function[]>();
private async _init() {
try {
const statusCode = await this._promise;
this.emit('exit', statusCode);
} catch (err) {
this.emit('exit', err);
}
}
emit(event: string, ...args: any[]): boolean {
const handlers = this._eventHandlers.get(event);
if (handlers == null || handlers.length === 0) {
return false;
}
for (const handler of handlers) {
handler(...args);
}
return true;
}
on(event: string, callback: Function): this {
if (!this._eventHandlers.has(event)) {
this._eventHandlers.set(event, []);
}
this._eventHandlers.get(event)?.push(callback);
return this;
}
}
/** Create a mock Document */
export function createDocument(
fsPathOrUri: string | vscode.Uri,
isDirty = false,
): Document {
return {
uri: ensureUri(fsPathOrUri),
isDirty,
} as Document;
}
/** Create a mock Uri */
export function createUri(fsPath: string): vscode.Uri {
return {
fsPath,
} as vscode.Uri;
}
/** Create a mock WorkspaceFolder */
export function createWorkspaceFolder(fsPath: string): vscode.WorkspaceFolder {
return {
uri: ensureUri(fsPath),
} as vscode.WorkspaceFolder;
}
/** Normalize a path or Uri to a Uri */
export function ensureUri(fsPathOrUri: vscode.Uri | string): vscode.Uri {
if (typeof fsPathOrUri === 'string') {
return createUri(fsPathOrUri);
}
return fsPathOrUri;
}
================================================
FILE: src/test/utils.spec.ts
================================================
import * as vscode from 'vscode';
import { describe, expect, it, vi } from 'vitest';
import { getReplacements, doReplacement } from '../utils';
import { createUri, createWorkspaceFolder } from './testUtils';
vi.mock('vscode');
describe('getReplacements', () => {
it('should return all token replacements', () => {
// Mock vscode.workspace.getWorkspaceFolder
const mockGetWorkspaceFolder = vi.mocked(
vscode.workspace.getWorkspaceFolder,
);
const workspaceFolder = createWorkspaceFolder('/workspace');
mockGetWorkspaceFolder.mockReturnValue(workspaceFolder);
// Mock process.cwd
const mockCwd = vi.spyOn(process, 'cwd');
mockCwd.mockReturnValue('/cwd');
// Set up environment variable
process.env.TEST_VAR = 'test_value';
// Create a URI for a file
const uri = createUri('/workspace/src/file.ts');
// Get replacements
const replacements = getReplacements(uri);
// Create a test string with all tokens
const testString =
'${file} ${workspaceRoot} ${workspaceFolder} ${fileBasename} ${fileDirname} ${fileExtname} ${fileBasenameNoExt} ${relativeFile} ${cwd} ${env.TEST_VAR}';
// Apply replacements
const result = doReplacement(testString, replacements);
// Expected result
const expected =
'/workspace/src/file.ts /workspace /workspace file.ts /workspace/src .ts file src/file.ts /cwd test_value';
expect(result).toBe(expected);
// Clean up
mockCwd.mockRestore();
delete process.env.TEST_VAR;
});
});
================================================
FILE: src/utils.ts
================================================
import * as path from 'path';
import * as vscode from 'vscode';
import type { Document, StringReplaceParams, StringReplacer } from './model';
/**
* Perform string replacements on the given text using the provided replacers.
*/
export function doReplacement(
text: string | null,
replacers: Array<StringReplaceParams>,
): string | null {
if (!text) {
return text;
}
for (const [searchValue, replacer] of replacers) {
text = text.replace(searchValue, replacer as StringReplacer);
}
return text;
}
/**
* Get the list of replacements for a given Uri.
*/
export function getReplacements(uri: vscode.Uri): Array<StringReplaceParams> {
const extName = path.extname(uri.fsPath);
const workspaceFolderPath = getWorkspaceFolderPath(uri);
const relativeFile = path.relative(workspaceFolderPath, uri.fsPath);
return [
[/\${file}/g, `${uri.fsPath}`],
// DEPRECATED: workspaceFolder is more inline with vscode variables,
// but leaving old version in place for any users already using it.
[/\${workspaceRoot}/g, workspaceFolderPath],
[/\${workspaceFolder}/g, workspaceFolderPath],
[/\${fileBasename}/g, path.basename(uri.fsPath)],
[/\${fileDirname}/g, path.dirname(uri.fsPath)],
[/\${fileExtname}/g, extName],
[/\${fileBasenameNoExt}/g, path.basename(uri.fsPath, extName)],
[/\${relativeFile}/g, relativeFile],
[/\${cwd}/g, process.cwd()],
// replace environment variables ${env.Name}
[
/\${env\.([^}]+)}/g,
(_sub: string, envName: string): string => {
// TODO: This is likely a bug and should be:
// process.env[envName] ?? ''. I just want to avoid
// a runtime change as part of this refactor.
return process.env[envName]!;
},
],
];
}
/**
* Get the workspace folder path for a given URI.
* If the URI does not belong to any workspace, return its directory path.
*/
export function getWorkspaceFolderPath(uri: vscode.Uri) {
const workspaceFolder = vscode.workspace.getWorkspaceFolder(uri);
// If file doesn't belong to a workspace, use the file's directory
return workspaceFolder
? workspaceFolder.uri.fsPath
: path.dirname(uri.fsPath);
}
================================================
FILE: tsconfig.json
================================================
{
"extends": "./tsconfig.node20.json",
"compilerOptions": {
"module": "CommonJS",
"outDir": "out",
"sourceMap": true,
"rootDir": "src",
"esModuleInterop": true
},
"include": ["src"],
"exclude": ["node_modules", "src/test"]
}
================================================
FILE: tsconfig.node20.json
================================================
// Based on https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping#node-20
{
"compilerOptions": {
"lib": ["ES2023", "DOM"],
"target": "ES2023"
}
}
================================================
FILE: tsconfig.unit.json
================================================
{
"extends": "./tsconfig.json",
"compilerOptions": {
"skipLibCheck": true
},
"include": ["src/test/**/*.ts"],
// Override ./tsconfig `exclude` so that *.spec.ts files are included
"exclude": ["node_modules"]
}
gitextract_tk17q1u7/ ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.md │ │ └── feature_request.md │ ├── pull_request_template.md │ └── workflows/ │ ├── prettier-check.yml │ └── test.yml ├── .gitignore ├── .nvmrc ├── .prettierignore ├── .prettierrc.yaml ├── .vscode/ │ ├── launch.json │ ├── settings.json │ └── tasks.json ├── .vscodeignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── __mocks__/ │ ├── child_process.ts │ └── vscode.ts ├── eslint.config.mjs ├── package.json ├── scripts/ │ ├── pre-release.sh │ └── publish.sh ├── src/ │ ├── ExtensionController.ts │ ├── SaveTracker.ts │ ├── extension.ts │ ├── model.ts │ ├── test/ │ │ ├── ExtensionController.spec.ts │ │ ├── SaveTracker.spec.ts │ │ ├── testUtils.ts │ │ └── utils.spec.ts │ └── utils.ts ├── tsconfig.json ├── tsconfig.node20.json └── tsconfig.unit.json
SYMBOL INDEX (48 symbols across 7 files)
FILE: __mocks__/child_process.ts
class ChildProcess (line 3) | class ChildProcess {
method on (line 4) | on() {}
method on (line 6) | on() {}
method on (line 9) | on() {}
FILE: src/ExtensionController.ts
class ExtensionController (line 11) | class ExtensionController {
method constructor (line 17) | constructor(context: vscode.ExtensionContext) {
method _runCommands (line 28) | private async _runCommands(
method _getExecPromise (line 96) | private _getExecPromise(
method _getExecOption (line 120) | private _getExecOption(document: Document): {
method isEnabled (line 130) | public get isEnabled(): boolean {
method isEnabled (line 133) | public set isEnabled(value: boolean) {
method shell (line 138) | public get shell(): string {
method autoClearConsole (line 142) | public get autoClearConsole(): boolean {
method ignoreUnchangedFiles (line 146) | public get ignoreUnchangedFiles(): boolean {
method commands (line 150) | public get commands(): Array<ICommand> {
method onDidSave (line 157) | public onDidSave(document: Document): void {
method onWillSave (line 164) | public onWillSave(document: Document): void {
method loadConfig (line 168) | public loadConfig(): void {
method showOutputMessage (line 177) | public showOutputMessage(message?: string): void {
method showOutputMessageIfDefined (line 186) | public showOutputMessageIfDefined(message?: string | null | false): vo...
method showStatusMessage (line 198) | public showStatusMessage(message: string): vscode.Disposable {
method runCommands (line 203) | public runCommands(document: Document): Promise<void> {
FILE: src/SaveTracker.ts
class SaveTracker (line 8) | class SaveTracker {
method constructor (line 13) | constructor(
method getPendingSaveCount (line 24) | public getPendingSaveCount(uri: vscode.Uri): number {
method onWillSave (line 31) | public onWillSave(document: Document): void {
method onDidSave (line 43) | public onDidSave(document: Document): void {
FILE: src/extension.ts
function activate (line 4) | function activate(context: vscode.ExtensionContext): void {
FILE: src/model.ts
type Document (line 7) | type Document = vscode.TextDocument | vscode.NotebookDocument;
type UriString (line 9) | type UriString = string;
type IMessageConfig (line 11) | interface IMessageConfig {
type ICommand (line 17) | interface ICommand extends IMessageConfig {
type IConfig (line 25) | interface IConfig extends IMessageConfig {
type IExecResult (line 32) | interface IExecResult {
type StringReplacer (line 37) | type StringReplacer = Parameters<String['replace']>[1];
type StringReplaceParams (line 38) | type StringReplaceParams =
FILE: src/test/testUtils.ts
class MockChildProcess (line 5) | class MockChildProcess extends ChildProcess {
method constructor (line 6) | constructor(private _promise: Promise<number>) {
method _init (line 13) | private async _init() {
method emit (line 22) | emit(event: string, ...args: any[]): boolean {
method on (line 35) | on(event: string, callback: Function): this {
function createDocument (line 46) | function createDocument(
function createUri (line 57) | function createUri(fsPath: string): vscode.Uri {
function createWorkspaceFolder (line 64) | function createWorkspaceFolder(fsPath: string): vscode.WorkspaceFolder {
function ensureUri (line 71) | function ensureUri(fsPathOrUri: vscode.Uri | string): vscode.Uri {
FILE: src/utils.ts
function doReplacement (line 8) | function doReplacement(
function getReplacements (line 26) | function getReplacements(uri: vscode.Uri): Array<StringReplaceParams> {
function getWorkspaceFolderPath (line 59) | function getWorkspaceFolderPath(uri: vscode.Uri) {
Condensed preview — 34 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (62K chars).
[
{
"path": ".github/ISSUE_TEMPLATE/bug_report.md",
"chars": 601,
"preview": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: bug, triage\nassignees: ''\n---\n\n**Descri"
},
{
"path": ".github/ISSUE_TEMPLATE/feature_request.md",
"chars": 474,
"preview": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: enhancement, triage\nassignees: ''\n--"
},
{
"path": ".github/pull_request_template.md",
"chars": 354,
"preview": "## Description of Changes\n\nSummarize changes this PR introduces.\n\n## Testing\n\n```jsonc\n{\n \"emeraldwalk.runonsave\": {\n "
},
{
"path": ".github/workflows/prettier-check.yml",
"chars": 533,
"preview": "name: Prettier Check\n\non:\n pull_request:\n branches: [main] # Run on PRs targeting the main branch\n\njobs:\n prettier_"
},
{
"path": ".github/workflows/test.yml",
"chars": 322,
"preview": "name: Test\n\non:\n pull_request:\n branches: [main]\n\njobs:\n test:\n runs-on: ubuntu-latest\n\n steps:\n - uses:"
},
{
"path": ".gitignore",
"chars": 16,
"preview": "out\nnode_modules"
},
{
"path": ".nvmrc",
"chars": 8,
"preview": "v22.8.0\n"
},
{
"path": ".prettierignore",
"chars": 17,
"preview": "package-lock.json"
},
{
"path": ".prettierrc.yaml",
"chars": 84,
"preview": "singleQuote: true\nsemi: true\ntabWidth: 2\ntrailingComma: 'all'\nbracketSameLine: true\n"
},
{
"path": ".vscode/launch.json",
"chars": 968,
"preview": "// A launch configuration that compiles the extension and then opens it inside a new window\n{\n \"version\": \"0.1.0\",\n \"c"
},
{
"path": ".vscode/settings.json",
"chars": 438,
"preview": "// Place your settings in this file to overwrite default and user settings.\n{\n \"files.exclude\": {\n \"out\": false // s"
},
{
"path": ".vscode/tasks.json",
"chars": 1140,
"preview": "// Available variables which can be used inside of strings.\n// ${workspaceRoot}: the root folder of the team\n// ${file}:"
},
{
"path": ".vscodeignore",
"chars": 125,
"preview": "### Ignore everything ####\n**/*\n\n#### Explicitly add things back ####\n\n!LICENSE\n!package.json\n!README.md\n!images/**\n!out"
},
{
"path": "CONTRIBUTING.md",
"chars": 1491,
"preview": "## Testing\n\nUnit tests run via `vitest`. The `src/test` folder is excluded from the extension build (`tsconfig.json`). T"
},
{
"path": "LICENSE",
"chars": 11358,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 6825,
"preview": "# Run On Save for Visual Studio Code\n\nThis extension allows configuring commands that get run whenever a file is saved i"
},
{
"path": "__mocks__/child_process.ts",
"chars": 162,
"preview": "import { vi } from 'vitest';\n\nexport class ChildProcess {\n on() {}\n stdout = {\n on() {},\n };\n stderr = {\n on()"
},
{
"path": "__mocks__/vscode.ts",
"chars": 218,
"preview": "import { vi } from 'vitest';\n\nexport const window = {\n createOutputChannel: vi.fn(() => ({\n appendLine: vi.fn(),\n }"
},
{
"path": "eslint.config.mjs",
"chars": 710,
"preview": "import typescriptEslint from '@typescript-eslint/eslint-plugin';\nimport tsParser from '@typescript-eslint/parser';\nimpor"
},
{
"path": "package.json",
"chars": 5437,
"preview": "{\n \"name\": \"RunOnSave\",\n \"displayName\": \"Run on Save\",\n \"description\": \"Run commands when a file is saved in vscode.\""
},
{
"path": "scripts/pre-release.sh",
"chars": 534,
"preview": "# Pre-release vscode extension. Requires version as argument.\nif [ $# -ne 1 ]; then\n echo \"Pre-release version requir"
},
{
"path": "scripts/publish.sh",
"chars": 682,
"preview": "#!/bin/bash\n#\n# Publish Script for VS Code Run On Save Extension\n#\n# This script publishes a new version of the vscode-r"
},
{
"path": "src/ExtensionController.ts",
"chars": 7173,
"preview": "import { exec } from 'child_process';\nimport * as vscode from 'vscode';\nimport type { Document, ICommand, IConfig, IExec"
},
{
"path": "src/SaveTracker.ts",
"chars": 1564,
"preview": "import * as vscode from 'vscode';\nimport type { Document, UriString } from './model';\n\n/**\n * Tracks pending saves for d"
},
{
"path": "src/extension.ts",
"chars": 1492,
"preview": "import * as vscode from 'vscode';\nimport { ExtensionController } from './ExtensionController';\n\nexport function activate"
},
{
"path": "src/model.ts",
"chars": 986,
"preview": "import * as vscode from 'vscode';\n\n/**\n * A union of `vscode.TextDocument` and `vscode.NotebookDocument`\n * to support b"
},
{
"path": "src/test/ExtensionController.spec.ts",
"chars": 5761,
"preview": "import * as vscode from 'vscode';\nimport { expect, it, vi } from 'vitest';\nimport { exec } from 'child_process';\nimport "
},
{
"path": "src/test/SaveTracker.spec.ts",
"chars": 1542,
"preview": "import { describe, expect, it, vi } from 'vitest';\nimport { SaveTracker } from '../SaveTracker';\nimport { createDocument"
},
{
"path": "src/test/testUtils.ts",
"chars": 1734,
"preview": "import * as vscode from 'vscode';\nimport { ChildProcess } from 'child_process';\nimport { type Document } from '../model'"
},
{
"path": "src/test/utils.spec.ts",
"chars": 1526,
"preview": "import * as vscode from 'vscode';\nimport { describe, expect, it, vi } from 'vitest';\nimport { getReplacements, doReplace"
},
{
"path": "src/utils.ts",
"chars": 2191,
"preview": "import * as path from 'path';\nimport * as vscode from 'vscode';\nimport type { Document, StringReplaceParams, StringRepla"
},
{
"path": "tsconfig.json",
"chars": 255,
"preview": "{\n \"extends\": \"./tsconfig.node20.json\",\n \"compilerOptions\": {\n \"module\": \"CommonJS\",\n \"outDir\": \"out\",\n \"sour"
},
{
"path": "tsconfig.node20.json",
"chars": 169,
"preview": "// Based on https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping#node-20\n{\n \"compilerOptions\": {\n \"lib\":"
},
{
"path": "tsconfig.unit.json",
"chars": 226,
"preview": "{\n \"extends\": \"./tsconfig.json\",\n \"compilerOptions\": {\n \"skipLibCheck\": true\n },\n \"include\": [\"src/test/**/*.ts\"]"
}
]
About this extraction
This page contains the full source code of the emeraldwalk/vscode-runonsave GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 34 files (55.8 KB), approximately 14.3k tokens, and a symbol index with 48 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.