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