Repository: ScoopInstaller/Scoop Branch: master Commit: b588a06e41d9 Files: 134 Total size: 583.4 KB Directory structure: gitextract_ros1r64f/ ├── .editorconfig ├── .gitattributes ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── Bug_report.md │ │ ├── Feature_request.md │ │ └── config.yml │ ├── PULL_REQUEST_TEMPLATE.md │ ├── dependabot.yml │ └── workflows/ │ └── ci.yml ├── .gitignore ├── .vscode/ │ ├── extensions.json │ └── settings.json ├── CHANGELOG.md ├── LICENSE ├── PSScriptAnalyzerSettings.psd1 ├── README.md ├── appveyor.yml ├── bin/ │ ├── auto-pr.ps1 │ ├── checkhashes.ps1 │ ├── checkurls.ps1 │ ├── checkver.ps1 │ ├── describe.ps1 │ ├── formatjson.ps1 │ ├── install.ps1 │ ├── missing-checkver.ps1 │ ├── refresh.ps1 │ ├── scoop.ps1 │ ├── test.ps1 │ └── uninstall.ps1 ├── buckets.json ├── lib/ │ ├── autoupdate.ps1 │ ├── buckets.ps1 │ ├── commands.ps1 │ ├── core.ps1 │ ├── database.ps1 │ ├── decompress.ps1 │ ├── depends.ps1 │ ├── description.ps1 │ ├── diagnostic.ps1 │ ├── download.ps1 │ ├── getopt.ps1 │ ├── help.ps1 │ ├── install.ps1 │ ├── json.ps1 │ ├── manifest.ps1 │ ├── psmodules.ps1 │ ├── shortcuts.ps1 │ ├── system.ps1 │ └── versions.ps1 ├── libexec/ │ ├── scoop-alias.ps1 │ ├── scoop-bucket.ps1 │ ├── scoop-cache.ps1 │ ├── scoop-cat.ps1 │ ├── scoop-checkup.ps1 │ ├── scoop-cleanup.ps1 │ ├── scoop-config.ps1 │ ├── scoop-create.ps1 │ ├── scoop-depends.ps1 │ ├── scoop-download.ps1 │ ├── scoop-export.ps1 │ ├── scoop-help.ps1 │ ├── scoop-hold.ps1 │ ├── scoop-home.ps1 │ ├── scoop-import.ps1 │ ├── scoop-info.ps1 │ ├── scoop-install.ps1 │ ├── scoop-list.ps1 │ ├── scoop-prefix.ps1 │ ├── scoop-reset.ps1 │ ├── scoop-search.ps1 │ ├── scoop-shim.ps1 │ ├── scoop-status.ps1 │ ├── scoop-unhold.ps1 │ ├── scoop-uninstall.ps1 │ ├── scoop-update.ps1 │ ├── scoop-virustotal.ps1 │ └── scoop-which.ps1 ├── schema.json ├── supporting/ │ ├── formats/ │ │ └── ScoopTypes.Format.ps1xml │ ├── shims/ │ │ ├── 71/ │ │ │ ├── checksum.sha256 │ │ │ └── checksum.sha512 │ │ ├── kiennq/ │ │ │ ├── checksum.sha256 │ │ │ ├── checksum.sha512 │ │ │ └── version.txt │ │ └── scoopcs/ │ │ ├── checksum.sha256 │ │ ├── checksum.sha512 │ │ └── version.txt │ └── validator/ │ ├── .gitignore │ ├── Scoop.Validator.cs │ ├── bin/ │ │ ├── checksum.sha256 │ │ └── checksum.sha512 │ ├── build.ps1 │ ├── install.ps1 │ ├── packages.config │ ├── update.ps1 │ ├── validator.cs │ └── validator.csproj └── test/ ├── Import-Bucket-Tests.ps1 ├── Scoop-00File.Tests.ps1 ├── Scoop-00Linting.Tests.ps1 ├── Scoop-Commands.Tests.ps1 ├── Scoop-Config.Tests.ps1 ├── Scoop-Core.Tests.ps1 ├── Scoop-Decompress.Tests.ps1 ├── Scoop-Depends.Tests.ps1 ├── Scoop-Download.Tests.ps1 ├── Scoop-GetOpts.Tests.ps1 ├── Scoop-Install.Tests.ps1 ├── Scoop-Manifest.Tests.ps1 ├── Scoop-TestLib.ps1 ├── Scoop-Versions.Tests.ps1 ├── bin/ │ ├── init.ps1 │ └── test.ps1 └── fixtures/ ├── format/ │ ├── formatted/ │ │ ├── 1-easy.json │ │ ├── 2-whitespaces-mess.json │ │ ├── 3-array-with-single-and-multi.json │ │ └── 4-script-block.json │ └── unformatted/ │ ├── 1-easy.json │ ├── 2-whitespaces-mess.json │ ├── 3-array-with-single-and-multi.json │ └── 4-script-block.json ├── is_directory/ │ ├── i_am_a_directory/ │ │ └── .gitkeep │ └── i_am_a_file.txt ├── manifest/ │ ├── broken_schema.json │ ├── broken_wget.json │ ├── invalid_wget.json │ └── wget.json ├── movedir/ │ ├── user/ │ │ └── _tmp/ │ │ ├── subdir/ │ │ │ └── test.txt │ │ └── test.txt │ ├── user with 'quote/ │ │ └── _tmp/ │ │ ├── subdir/ │ │ │ └── test.txt │ │ └── test.txt │ └── user with space/ │ └── _tmp/ │ ├── subdir/ │ │ └── test.txt │ └── test.txt └── shim/ ├── shim-test.ps1 └── user with 'quote/ └── shim-test.ps1 ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ # EditorConfig (is awesome): http://EditorConfig.org # * top-most EditorConfig file root = true # default style settings [*] charset = utf-8 end_of_line = crlf indent_size = 4 indent_style = space insert_final_newline = true trim_trailing_whitespace = true [*.{[Bb][Aa][Tt],[Cc][Mm][Dd]}] # DOS/Win *requires* BAT/CMD files to have CRLF newlines end_of_line = crlf [*.{yml, yaml}] indent_size = 2 # Makefiles require tab indentation [{{M,m,GNU}akefile{,.*},*.mak,*.mk}] indent_style = tab end_of_line = lf ================================================ FILE: .gitattributes ================================================ # retain windows line-endings in case checked out on mac or linux * text eol=crlf *.exe -text *.zip -text *.dll -text ================================================ FILE: .github/ISSUE_TEMPLATE/Bug_report.md ================================================ --- name: "Bug Report" about: "I am facing some problems." title: '[Bug] ' labels: "bug" --- ## Bug Report #### Current Behavior #### Expected Behavior #### Additional context/output #### Possible Solution ### System details **Windows version:** [e.g. 7, 8, 10, 11] **OS architecture:** [e.g. 32bit, 64bit, arm64] **PowerShell version:** [output of `"$($PSVersionTable.PSVersion)"`] **Additional software:** [(optional) e.g. ConEmu, Git] #### Scoop Configuration ```json //# Your configuration here ``` ================================================ FILE: .github/ISSUE_TEMPLATE/Feature_request.md ================================================ --- name: "Feature Request" about: "I have a suggestion (and may want to implement it)!" title: '[Feature] ' labels: "enhancement" --- ## Feature Request #### Is your feature request related to a problem? Please describe. #### Describe the solution you'd like #### Describe alternatives you've considered ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ #### Description #### Motivation and Context Closes #XXXX Relates to #XXXX #### How Has This Been Tested? #### Checklist: - [ ] I have read the [Contributing Guide](https://github.com/ScoopInstaller/.github/blob/main/.github/CONTRIBUTING.md). - [ ] I have ensured that I am targeting the `develop` branch. - [ ] I have updated the documentation accordingly. - [ ] I have updated the tests accordingly. - [ ] I have added an entry in the CHANGELOG. ================================================ FILE: .github/dependabot.yml ================================================ --- # ~/.github/dependabot.yml version: 2 updates: - package-ecosystem: "github-actions" directory: "/" # == /.github/workflows/ schedule: interval: "daily" ================================================ FILE: .github/workflows/ci.yml ================================================ name: Scoop Core CI Tests on: pull_request: workflow_dispatch: jobs: test_powershell: name: WindowsPowerShell runs-on: windows-latest steps: - name: Checkout uses: actions/checkout@main with: fetch-depth: 2 - name: Init Test Suite uses: potatoqualitee/psmodulecache@main with: modules-to-cache: BuildHelpers shell: powershell - name: Test Scoop Core shell: powershell run: ./test/bin/test.ps1 test_pwsh: name: PowerShell runs-on: windows-latest steps: - name: Checkout uses: actions/checkout@main with: fetch-depth: 2 - name: Init Test Suite uses: potatoqualitee/psmodulecache@main with: modules-to-cache: BuildHelpers shell: pwsh - name: Test Scoop Core shell: pwsh run: ./test/bin/test.ps1 ================================================ FILE: .gitignore ================================================ *.log .DS_Store ._.DS_Store scoop.sublime-workspace test/installer/tmp/* test/tmp/* *~ TestResults.xml supporting/sqlite/* ================================================ FILE: .vscode/extensions.json ================================================ { "recommendations": [ "EditorConfig.EditorConfig", "ms-vscode.PowerShell" ] } ================================================ FILE: .vscode/settings.json ================================================ // Configure PSScriptAnalyzer settings { "powershell.scriptAnalysis.settingsPath": "PSScriptAnalyzerSettings.psd1", "powershell.codeFormatting.preset": "OTBS", "powershell.codeFormatting.alignPropertyValuePairs": true, "powershell.codeFormatting.ignoreOneLineBlock": true, "powershell.codeFormatting.useConstantStrings": true, "powershell.codeFormatting.useCorrectCasing": true, "powershell.codeFormatting.whitespaceBetweenParameters": true, "files.exclude": { "**/.git": true, "**/.svn": true, "**/.hg": true, "**/CVS": true, "**/.DS_Store": true, "**/tmp": true } } ================================================ FILE: CHANGELOG.md ================================================ ## [v0.5.3](https://github.com/ScoopInstaller/Scoop/compare/v0.5.2...v0.5.3) - 2025-08-11 ### Features **autoupdate:** GitHub predefined hashes support ([#6416](https://github.com/ScoopInstaller/Scoop/issues/6416), [#6435](https://github.com/ScoopInstaller/Scoop/issues/6435)) ### Bug Fixes - **scoop-download|install|update:** Fallback to default downloader when aria2 fails ([#4292](https://github.com/ScoopInstaller/Scoop/issues/4292)) - **decompress**: `Expand-7zipArchive` only delete temp dir / `$extractDir` if it is empty ([#6092](https://github.com/ScoopInstaller/Scoop/issues/6092)) - **decompress**: Replace deprecated 7ZIPEXTRACT_USE_EXTERNAL config with USE_EXTERNAL_7ZIP ([#6327](https://github.com/ScoopInstaller/Scoop/issues/6327)) - **commands**: Handling broken aliases ([#6141](https://github.com/ScoopInstaller/Scoop/issues/6141)) - **shim:** Do not suppress `stderr`, properly check `wslpath`/`cygpath` command first ([#6114](https://github.com/ScoopInstaller/Scoop/issues/6114)) - **scoop-bucket:** Add missing import for `no_junction` envs ([#6181](https://github.com/ScoopInstaller/Scoop/issues/6181)) - **scoop-uninstall:** Fix uninstaller does not gain Global state ([#6430](https://github.com/ScoopInstaller/Scoop/issues/6430)) - **scoop-depends-tests:** Mocking `USE_EXTERNAL_7ZIP` as $false to avoding error when it is $true ([#6431](https://github.com/ScoopInstaller/Scoop/issues/6431)) ### Code Refactoring - **download:** Move download-related functions to 'download.ps1' ([#6095](https://github.com/ScoopInstaller/Scoop/issues/6095)) - **Get-Manifest:** Select actual source for manifest ([#6142](https://github.com/ScoopInstaller/Scoop/issues/6142)) ### Performance Improvements - **shim:** Update kiennq-shim to v3.1.2 ([#6261](https://github.com/ScoopInstaller/Scoop/issues/6261)) ## [v0.5.2](https://github.com/ScoopInstaller/Scoop/compare/v0.5.1...v0.5.2) - 2024-07-26 ### Bug Fixes - **scoop-alias:** Fix 'Option --verbose not recognized.' ([#6062](https://github.com/ScoopInstaller/Scoop/issues/6062)) - **scoop-hold:** Use 'foreach' loop to allow 'continue' statement ([#6078](https://github.com/ScoopInstaller/Scoop/issues/6078)) - **core:** Use 'Join-Path' to construct cache file path ([#6079](https://github.com/ScoopInstaller/Scoop/issues/6079)) - **json:** Don't serialize jsonpath return if only one result ([#6066](https://github.com/ScoopInstaller/Scoop/issues/6066), [#6073](https://github.com/ScoopInstaller/Scoop/issues/6073)) ### Builds - **supporting:** Update Json.Schema to 4.0.1 ([#6072](https://github.com/ScoopInstaller/Scoop/issues/6072)) ## [v0.5.1](https://github.com/ScoopInstaller/Scoop/compare/v0.5.0...v0.5.1) - 2024-07-16 ### Bug Fixes - **scoop-alias:** Pass options correctly ([#6003](https://github.com/ScoopInstaller/Scoop/issues/6003)) - **scoop-virustotal:** Adjust `json_path` parameters to retrieve correct analysis stats ([#6044](https://github.com/ScoopInstaller/Scoop/issues/6044)) - **bucket:** Implement error handling for failed bucket addition ([#6051](https://github.com/ScoopInstaller/Scoop/issues/6051)) - **database:** Fix compatibility with Windows PowerShell ([#6045](https://github.com/ScoopInstaller/Scoop/issues/6045)) - **install:** Expand `env_set` items before setting Environment Variables ([#6050](https://github.com/ScoopInstaller/Scoop/issues/6050)) - **install:** Fix parsing error when installing multiple apps w/ specific version ([#6039](https://github.com/ScoopInstaller/Scoop/issues/6039)) ## [v0.5.0](https://github.com/ScoopInstaller/Scoop/compare/v0.4.2...v0.5.0) - 2024-07-01 ### Features - **scoop-search:** Use SQLite for caching apps to speed up local search ([#5851](https://github.com/ScoopInstaller/Scoop/issues/5851), [#5918](https://github.com/ScoopInstaller/Scoop/issues/5918), [#5946](https://github.com/ScoopInstaller/Scoop/issues/5946), [#5949](https://github.com/ScoopInstaller/Scoop/issues/5949), [#5955](https://github.com/ScoopInstaller/Scoop/issues/5955), [#5966](https://github.com/ScoopInstaller/Scoop/issues/5966), [#5967](https://github.com/ScoopInstaller/Scoop/issues/5967), [#5981](https://github.com/ScoopInstaller/Scoop/issues/5981)) - **core:** New cache filename format ([#5929](https://github.com/ScoopInstaller/Scoop/issues/5929), [#5944](https://github.com/ScoopInstaller/Scoop/issues/5944)) - **decompress:** Use innounp-unicode as default Inno Setup Unpacker ([#6028](https://github.com/ScoopInstaller/Scoop/issues/6028)) - **install:** Added the ability to install specific version of app from URL/file link ([#5988](https://github.com/ScoopInstaller/Scoop/issues/5988)) ### Bug Fixes - **scoop-download|install|update:** Use consistent options ([#5956](https://github.com/ScoopInstaller/Scoop/issues/5956)) - **scoop-info:** Fix download size estimating ([#5958](https://github.com/ScoopInstaller/Scoop/issues/5958)) - **scoop-search:** Catch error of parsing invalid manifest ([#5930](https://github.com/ScoopInstaller/Scoop/issues/5930)) - **checkver:** Correct variable 'regex' to 'regexp' ([#5993](https://github.com/ScoopInstaller/Scoop/issues/5993)) - **checkver:** Correct error messages ([#6024](https://github.com/ScoopInstaller/Scoop/issues/6024)) - **core:** Search for Git executable instead of any cmdlet ([#5998](https://github.com/ScoopInstaller/Scoop/issues/5998)) - **core:** Use correct path in 'bash' ([#6006](https://github.com/ScoopInstaller/Scoop/issues/6006)) - **core:** Limit the number of commands to get when search for git executable ([#6013](https://github.com/ScoopInstaller/Scoop/issues/6013)) - **decompress:** Match `extract_dir`/`extract_to` and archives ([#5983](https://github.com/ScoopInstaller/Scoop/issues/5983)) - **json:** Serialize jsonpath return ([#5921](https://github.com/ScoopInstaller/Scoop/issues/5921)) - **shim:** Restore original path for JAR cmd ([#6030](https://github.com/ScoopInstaller/Scoop/issues/6030)) ### Code Refactoring - **decompress:** Use 7zip to extract Zstd archive ([#5973](https://github.com/ScoopInstaller/Scoop/issues/5973)) - **install:** Separate archive extraction from downloader ([#5951](https://github.com/ScoopInstaller/Scoop/issues/5951)) - **install:** Replace 'run_(un)installer()' with 'Invoke-Installer()' ([#5968](https://github.com/ScoopInstaller/Scoop/issues/5968), [#5971](https://github.com/ScoopInstaller/Scoop/issues/5971)) ## [v0.4.2](https://github.com/ScoopInstaller/Scoop/compare/v0.4.1...v0.4.2) - 2024-05-14 ### Bug Fixes - **autoupdate:** Copy `PSCustomObject`-type properties within `substitute()` to prevent reference changes ([#5934](https://github.com/ScoopInstaller/Scoop/issues/5934), [#5962](https://github.com/ScoopInstaller/Scoop/issues/5962)) - **core:** Fix `Invoke-ExternalCommand` quoting rules ([#5945](https://github.com/ScoopInstaller/Scoop/issues/5945)) - **system:** Fix argument passing to `Split-PathLikeEnvVar()` in deprecated `strip_path()` ([#5937](https://github.com/ScoopInstaller/Scoop/issues/5937)) ## [v0.4.1](https://github.com/ScoopInstaller/Scoop/compare/v0.4.0...v0.4.1) - 2024-04-25 ### Bug Fixes - **core:** Fix `Invoke-ExternalCommand` regression ([#5923](https://github.com/ScoopInstaller/Scoop/issues/5923)) ## [v0.4.0](https://github.com/ScoopInstaller/Scoop/compare/v0.3.1...v0.4.0) - 2024-04-18 ### Features - **scoop-update:** Add support for parallel syncing buckets in PowerShell 7 and improve output ([#5122](https://github.com/ScoopInstaller/Scoop/issues/5122)) - **bucket:** Switch nirsoft bucket to ScoopInstaller/Nirsoft ([#5328](https://github.com/ScoopInstaller/Scoop/issues/5328)) - **bucket:** Make official buckets higher priority ([#5398](https://github.com/ScoopInstaller/Scoop/issues/5398)) - **config:** Support portable config file ([#5369](https://github.com/ScoopInstaller/Scoop/issues/5369)) - **core:** Add `-Quiet` switch for `Invoke-ExternalCommand` ([#5346](https://github.com/ScoopInstaller/Scoop/issues/5346)) - **core:** Allow global install of PowerShell modules ([#5611](https://github.com/ScoopInstaller/Scoop/issues/5611)) - **path:** Isolate Scoop apps' PATH ([#5840](https://github.com/ScoopInstaller/Scoop/issues/5840)) ### Bug Fixes - **scoop-alias:** Prevent overwrite existing file when adding alias ([#5577](https://github.com/ScoopInstaller/Scoop/issues/5577)) - **scoop-checkup:** Skip defender check in Windows Sandbox ([#5519](https://github.com/ScoopInstaller/Scoop/issues/5519)) - **scoop-checkup:** Change the message level of helpers from ERROR to WARN ([#5614](https://github.com/ScoopInstaller/Scoop/issues/5614)) - **scoop-checkup:** Don't throw 7zip error when external 7zip is used ([#5703](https://github.com/ScoopInstaller/Scoop/issues/5703)) - **scoop-(un)hold:** Correct output the messages when manifest not found, (already|not) held ([#5519](https://github.com/ScoopInstaller/Scoop/issues/5519)) - **scoop-info:** Fix errors in file size collection when `--verbose` ([#5352](https://github.com/ScoopInstaller/Scoop/issues/5352)) - **scoop-reset:** Don't abort when multiple apps are passed and an app is running ([#5687](https://github.com/ScoopInstaller/Scoop/issues/5687)) - **scoop-update:** Change error message to a better instruction ([#5677](https://github.com/ScoopInstaller/Scoop/issues/5677)) - **scoop-virustotal:** Fix `scoop-virustotal` when `--all` has been passed without app ([#5593](https://github.com/ScoopInstaller/Scoop/issues/5593)) - **scoop-virustotal:** Fix the issue that escape character not available in PowerShell 5.1 ([#5870](https://github.com/ScoopInstaller/Scoop/issues/5870)) - **autoupdate:** Fix file hash extraction ([#5295](https://github.com/ScoopInstaller/Scoop/issues/5295)) - **autoupdate:** Fix bug that 'WebClient' doesn't auto-extract 'gzip' ([#5901](https://github.com/ScoopInstaller/Scoop/issues/5901)) - **buckets:** Avoid error messages for unexpected dir ([#5549](https://github.com/ScoopInstaller/Scoop/issues/5549)) - **config:** Warn users about misconfigured GitHub token ([#5777](https://github.com/ScoopInstaller/Scoop/issues/5777)) - **core:** Fix scripts' calling parameters ([#5365](https://github.com/ScoopInstaller/Scoop/issues/5365)) - **core:** Fix `is_in_dir` under Unix ([#5391](https://github.com/ScoopInstaller/Scoop/issues/5391)) - **core:** Rewrite config file when needed ([#5439](https://github.com/ScoopInstaller/Scoop/issues/5439)) - **core:** Prevents leaking HTTP(S)_PROXY env vars to current sessions after Invoke-Git in parallel execution ([#5436](https://github.com/ScoopInstaller/Scoop/issues/5436)) - **core:** Handle scoop aliases and broken(edited,copied) shim ([#5551](https://github.com/ScoopInstaller/Scoop/issues/5551)) - **core:** Avoid error messages when deleting non-existent environment variable ([#5547](https://github.com/ScoopInstaller/Scoop/issues/5547)) - **core:** Use relative path as fallback of `$scoopdir` ([#5544](https://github.com/ScoopInstaller/Scoop/issues/5544)) - **core:** Fix detection of Git ([#5545](https://github.com/ScoopInstaller/Scoop/issues/5545)) - **core:** Do not call `scoop` externally from inside the code ([#5695](https://github.com/ScoopInstaller/Scoop/issues/5695)) - **core:** Fix arguments parsing method of `Invoke-ExternalCommand()` ([#5839](https://github.com/ScoopInstaller/Scoop/issues/5839)) - **decompress:** Exclude '*.nsis' that may cause error ([#5294](https://github.com/ScoopInstaller/Scoop/issues/5294)) - **decompress:** Remove unused parent dir w/ 'extract_dir' ([#5682](https://github.com/ScoopInstaller/Scoop/issues/5682)) - **decompress:** Use `wix.exe` in WiX Toolset v4+ as primary extractor of `Expand-DarkArchive()` ([#5871](https://github.com/ScoopInstaller/Scoop/issues/5871)) - **env:** Avoid automatic expansion of `%%` in env ([#5395](https://github.com/ScoopInstaller/Scoop/issues/5395), [#5452](https://github.com/ScoopInstaller/Scoop/issues/5452), [#5631](https://github.com/ScoopInstaller/Scoop/issues/5631)) - **getopt:** Stop split arguments in `getopt()` and ensure array by explicit arguments type ([#5326](https://github.com/ScoopInstaller/Scoop/issues/5326)) - **install:** Fix download from private GitHub repositories ([#5361](https://github.com/ScoopInstaller/Scoop/issues/5361)) - **install:** Avoid error when unlinking non-existent junction/hardlink ([#5552](https://github.com/ScoopInstaller/Scoop/issues/5552)) - **manifest:** Correct source of manifest ([#5575](https://github.com/ScoopInstaller/Scoop/issues/5575)) - **shim:** Remove console window for GUI applications ([#5559](https://github.com/ScoopInstaller/Scoop/issues/5559)) - **shim:** Use bash executable directly ([#5433](https://github.com/ScoopInstaller/Scoop/issues/5433)) - **shim:** Check literal path in `Get-ShimPath` ([#5680](https://github.com/ScoopInstaller/Scoop/issues/5680)) - **shim:** Avoid unexpected output of `list` subcommand ([#5681](https://github.com/ScoopInstaller/Scoop/issues/5681)) - **shim:** Allow GUI applications to attach to the shell's console when launched using the GUI shim ([#5721](https://github.com/ScoopInstaller/Scoop/issues/5721)) - **shim:** Run JAR file from app's root directory ([#5872](https://github.com/ScoopInstaller/Scoop/issues/5872)) - **shortcuts:** Output correctly formatted path ([#5333](https://github.com/ScoopInstaller/Scoop/issues/5333)) - **update/uninstall:** Remove items from PATH correctly ([#5833](https://github.com/ScoopInstaller/Scoop/issues/5833)) ### Performance Improvements - **scoop-search:** Improve performance for local search ([#5644](https://github.com/ScoopInstaller/Scoop/issues/5644)) - **scoop-update:** Check for running process before wasting time on download ([#5799](https://github.com/ScoopInstaller/Scoop/issues/5799)) - **decompress:** Disable progress bar to improve `Expand-Archive` performance ([#5410](https://github.com/ScoopInstaller/Scoop/issues/5410)) - **shim:** Update kiennq-shim to v3.1.1 ([#5841](https://github.com/ScoopInstaller/Scoop/issues/5841), [#5847](https://github.com/ScoopInstaller/Scoop/issues/5847)) ### Code Refactoring - **scoop-download:** Output more detailed manifest information ([#5277](https://github.com/ScoopInstaller/Scoop/issues/5277)) - **core:** Cleanup some old codes, e.g., msi section and config migration ([#5715](https://github.com/ScoopInstaller/Scoop/issues/5715), [#5824](https://github.com/ScoopInstaller/Scoop/issues/5824)) - **core:** Rewrite and separate path-related functions to `system.ps1` ([#5836](https://github.com/ScoopInstaller/Scoop/issues/5836), [#5858](https://github.com/ScoopInstaller/Scoop/issues/5858), [#5864](https://github.com/ScoopInstaller/Scoop/issues/5864)) - **core:** Get rid of 'fullpath' ([#3533](https://github.com/ScoopInstaller/Scoop/issues/3533)) - **git:** Use Invoke-Git() with direct path to git.exe to prevent spawning shim subprocesses ([#5122](https://github.com/ScoopInstaller/Scoop/issues/5122), [#5375](https://github.com/ScoopInstaller/Scoop/issues/5375)) - **helper:** Remove 7zip's fallback '7zip-zstd' ([#5548](https://github.com/ScoopInstaller/Scoop/issues/5548)) - **shim:** Remove CS shim codebase ([#5903](https://github.com/ScoopInstaller/Scoop/issues/5903)) ### Builds - **checkver:** Read the private_host config variable ([#5381](https://github.com/ScoopInstaller/Scoop/issues/5381)) - **supporting:** Update Json to 13.0.3, Json.Schema to 3.0.15 ([#5835](https://github.com/ScoopInstaller/Scoop/issues/5835)) ### Continuous Integration - **dependabot:** Add dependabot.yml for GitHub Actions ([#5377](https://github.com/ScoopInstaller/Scoop/issues/5377)) - **module:** Update 'psmodulecache' version to 'main' ([#5828](https://github.com/ScoopInstaller/Scoop/issues/5828)) ### Tests - **bucket:** Skip manifest validation if no manifest changes ([#5270](https://github.com/ScoopInstaller/Scoop/issues/5270)) ### Documentation - **scoop-info:** Fix help message([#5445](https://github.com/ScoopInstaller/Scoop/issues/5445)) - **readme:** Improve documentation language ([#5638](https://github.com/ScoopInstaller/Scoop/issues/5638)) ## [v0.3.1](https://github.com/ScoopInstaller/Scoop/compare/v0.3.0...v0.3.1) - 2022-11-15 ### Features - **config:** Allow Scoop to check if apps versioned as 'nightly' are outdated ([#5166](https://github.com/ScoopInstaller/Scoop/issues/5166)) - **checkup:** Add Windows Developer Mode check ([#5233](https://github.com/ScoopInstaller/Scoop/issues/5233)) - **bucket:** Add 'sysinternals' bucket to known ([#5237](https://github.com/ScoopInstaller/Scoop/issues/5237)) ### Bug Fixes - **decompress:** Use PS's default 'Expand-Archive()' ([#5185](https://github.com/ScoopInstaller/Scoop/issues/5185)) - **hash:** Fix SourceForge's hash extraction ([#5189](https://github.com/ScoopInstaller/Scoop/issues/5189)) - **decompress:** Trim ending '/' ([#5195](https://github.com/ScoopInstaller/Scoop/issues/5195)) - **shim:** Exit if shim creating failed 'cause no git ([#5225](https://github.com/ScoopInstaller/Scoop/issues/5225)) - **scoop-import:** Add correct architecture argument ([#5210](https://github.com/ScoopInstaller/Scoop/issues/5210)) - **scoop-config:** Output `[DateTime]` as `[String]` ([#5232](https://github.com/ScoopInstaller/Scoop/issues/5232)) - **shim:** fixed shim add bug related to Resolve-Path ([#5492](https://github.com/ScoopInstaller/Scoop/issues/5492)) ### Code Refactoring - **hash:** Use `Get-FileHash()` directly ([#5177](https://github.com/ScoopInstaller/Scoop/issues/5177)) - **installer:** Drop the old installer ([#5186](https://github.com/ScoopInstaller/Scoop/issues/5186)) - **unix:** Remove `unix.ps1` ([#5235](https://github.com/ScoopInstaller/Scoop/issues/5235)) ### Builds - **auto-pr:** Add `CommitMessageFormat` option ([#5171](https://github.com/ScoopInstaller/Scoop/issues/5171)) - **checkver:** Support XML default namespace ([#5191](https://github.com/ScoopInstaller/Scoop/issues/5191)) - **pssa:** Remove unused 'ExcludeRules' ([#5201](https://github.com/ScoopInstaller/Scoop/issues/5201)) - **schema:** Add 'installer' and 'shortcuts' to 'autoupdate' ([#5220](https://github.com/ScoopInstaller/Scoop/issues/5220)) - **checkhashes:** Use correct version number if `UseCache` ([#5240](https://github.com/ScoopInstaller/Scoop/issues/5240)) ### Continuous Integration - **module:** Update modules version ([#5209](https://github.com/ScoopInstaller/Scoop/issues/5209)) ### Tests - **unix:** Fix tests in Linux and macOS ([#5179](https://github.com/ScoopInstaller/Scoop/issues/5179)) - **pester:** Update to Pester 5 ([#5222](https://github.com/ScoopInstaller/Scoop/issues/5222)) - **bucket:** Use BuildHelpers' EnvVars ([#5226](https://github.com/ScoopInstaller/Scoop/issues/5226)) ### Documentation - **scoop-cat:** Fix help message([#5224](https://github.com/ScoopInstaller/Scoop/issues/5224)) ## [v0.3.0](https://github.com/ScoopInstaller/Scoop/compare/v0.2.4...v0.3.0) - 2022-10-10 ### Features - **install:** Add support for ARM64 architecture ([#5154](https://github.com/ScoopInstaller/Scoop/issues/5154)) - **install:** Show the running process ([#5102](https://github.com/ScoopInstaller/Scoop/issues/5102)) - **getopt:** Support option terminator (`--`) ([#5121](https://github.com/ScoopInstaller/Scoop/issues/5121)) - **subdir:** Allow subdir in 'bucket' ([#5119](https://github.com/ScoopInstaller/Scoop/issues/5119)) - **scoop-config:** Allow 'hold_update_until' be set manually ([#5100](https://github.com/ScoopInstaller/Scoop/issues/5100)) - **scoop-(un)hold:** Support `scoop (un)hold scoop` ([#5089](https://github.com/ScoopInstaller/Scoop/issues/5089)) - **scoop-update:** Stash uncommitted changes before update ([#5091](https://github.com/ScoopInstaller/Scoop/issues/5091)) ### Bug Fixes - **config:** Change config option to snake_case in file and SCREAMING_CASE in code ([#5116](https://github.com/ScoopInstaller/Scoop/issues/5116)) - **jsonpath:** Prevent converting date string to DateTime in JSONPath ([#5130](https://github.com/ScoopInstaller/Scoop/issues/5130)) - **psmodule:** Remove folder recursively when unlinking previous module path ([#5127](https://github.com/ScoopInstaller/Scoop/issues/5127)) - **scoop-update:** Add `uninstall_psmodule` to update process ([#5136](https://github.com/ScoopInstaller/Scoop/issues/5136)) ### Code Refactoring - **download:** Rename `dl()` to `Invoke-Download()` ([#5143](https://github.com/ScoopInstaller/Scoop/issues/5143)) - **path:** Use 'Convert-Path()' instead of 'Resolve-Path()' ([#5109](https://github.com/ScoopInstaller/Scoop/issues/5109)) - **scoop-shim:** Use `getopt` to parse arguments ([#5125](https://github.com/ScoopInstaller/Scoop/issues/5125)) ### Builds - **checkver:** Implement SourceForge checkver functionality ([#5113](https://github.com/ScoopInstaller/Scoop/issues/5113), [#5163](https://github.com/ScoopInstaller/Scoop/issues/5163)) - **checkurls:** Allow checking URLs from private_hosts ([#5152](https://github.com/ScoopInstaller/Scoop/issues/5152)) - **schema:** Set manifest schema to be stricter ([#5093](https://github.com/ScoopInstaller/Scoop/issues/5093)) - **vscode:** Tweak VSCode setting ([#5149](https://github.com/ScoopInstaller/Scoop/issues/5149)) ## [v0.2.4](https://github.com/ScoopInstaller/Scoop/compare/v0.2.3...v0.2.4) - 2022-08-08 ### Features - **core:** Create no window by default in `Invoke-ExternalCommand` ([#5066](https://github.com/ScoopInstaller/Scoop/issues/5066)) - **core:** Improve argument concatenation in `Invoke-ExternalCommand` ([#5065](https://github.com/ScoopInstaller/Scoop/issues/5065)) - **install:** Show bucket name while installing an app ([#5075](https://github.com/ScoopInstaller/Scoop/issues/5075)) - **scoop-status:** Add flag to disable remote checking ([#5073](https://github.com/ScoopInstaller/Scoop/issues/5073)) - **scoop-update:** Add support for `pre_uninstall` and `post_uninstall` ([#5085](https://github.com/ScoopInstaller/Scoop/issues/5085)) ### Bug Fixes - **core:** Avoid deadlock in `Invoke-ExternalCommand` ([#5064](https://github.com/ScoopInstaller/Scoop/issues/5064)) - **core:** Use 'System.Nullable' for param 'global' ([#5088](https://github.com/ScoopInstaller/Scoop/issues/5088)) - **install:** Move from cache when `--no-cache` is specified ([#5039](https://github.com/ScoopInstaller/Scoop/issues/5039)) - **scoop-status:** Correct formatting of `Info` output ([#5047](https://github.com/ScoopInstaller/Scoop/issues/5047)) ### Builds - **checkver:** Load page content before running 'script' ([#5080](https://github.com/ScoopInstaller/Scoop/issues/5080)) - **json:** Update Newtonsoft.Json.Schema to 3.0.15-beta2 ([#5053](https://github.com/ScoopInstaller/Scoop/issues/5053)) ## [v0.2.3](https://github.com/ScoopInstaller/Scoop/compare/v0.2.2...v0.2.3) - 2022-07-07 ### Features - **chore:** Add missing -a/--all param to all commands ([#5004](https://github.com/ScoopInstaller/Scoop/issues/5004)) - **scoop-status:** Check bucket status, improve output ([#5011](https://github.com/ScoopInstaller/Scoop/issues/5011)) - **scoop-info:** Show app installed/download size ([#4886](https://github.com/ScoopInstaller/Scoop/issues/4886)) - **scoop-import:** Import a Scoop installation from JSON ([#5014](https://github.com/ScoopInstaller/Scoop/issues/5014), [#5034](https://github.com/ScoopInstaller/Scoop/issues/5034)) ### Bug Fixes - **chore:** Update help documentation ([#5002](https://github.com/ScoopInstaller/Scoop/issues/5002), [#5029](https://github.com/ScoopInstaller/Scoop/issues/5029)) - **decompress:** Handle split RAR archives ([#4994](https://github.com/ScoopInstaller/Scoop/issues/4994)) - **shortcuts:** Fix network drive shortcut creation ([#4410](https://github.com/ScoopInstaller/Scoop/issues/4410), [#5006](https://github.com/ScoopInstaller/Scoop/issues/5006)) ### Code Refactoring - **scoop-search:** Output PSObject, use API token ([#4997](https://github.com/ScoopInstaller/Scoop/issues/4997)) ### Builds - **checkver,auto-pr:** Allow passing file path ([#5019](https://github.com/ScoopInstaller/Scoop/issues/5019)) - **checkver:** Exit routine earlier if error ([#5025](https://github.com/ScoopInstaller/Scoop/issues/5025)) - **json:** Update Newton.Json to 13.0.1 ([#5026](https://github.com/ScoopInstaller/Scoop/issues/5026)) ### Tests - **typo:** Fix typo ('formated' -> 'formatted') ([#4217](https://github.com/ScoopInstaller/Scoop/issues/4217)) ## [v0.2.2](https://github.com/ScoopInstaller/Scoop/compare/v0.2.1...v0.2.2) - 2022-06-21 ### Features - **core:** Add `Get-Encoding` function to fix missing webclient encoding ([#4956](https://github.com/ScoopInstaller/Scoop/issues/4956)) - **scoop-(un)hold:** Add `-g`/`--global` flag ([#4991](https://github.com/ScoopInstaller/Scoop/issues/4991)) - **scoop-update:** Support `scoop update scoop` ([#4992](https://github.com/ScoopInstaller/Scoop/issues/4992)) - **scoop-virustotal:** Migrate to VirusTotal API v3 ([#4983](https://github.com/ScoopInstaller/Scoop/issues/4983)) ### Bug Fixes - **manifest:** Fix bugs in 'Get-Manifest()' ([#4986](https://github.com/ScoopInstaller/Scoop/issues/4986)) ## [v0.2.1](https://github.com/ScoopInstaller/Scoop/compare/v0.2.0...v0.2.1) - 2022-06-10 ### Features - **core:** Add pre_uninstall and post_uninstall hooks ([#4957](https://github.com/ScoopInstaller/Scoop/issues/4957), [#4962](https://github.com/ScoopInstaller/Scoop/issues/4962)) ### Bug Fixes - **bucket:** Make sure `list_buckets` return array ([#4979](https://github.com/ScoopInstaller/Scoop/issues/4979)) - **chore:** Deprecate tls1 and tls1.1 ([#4950](https://github.com/ScoopInstaller/Scoop/issues/4950)) - **chore:** Update Nonportable bucket URL ([#4955](https://github.com/ScoopInstaller/Scoop/issues/4955)) - **core:** Using `Invoke-Command` instead of `Invoke-Expression` ([#4941](https://github.com/ScoopInstaller/Scoop/issues/4941)) - **core:** Load config file before initialization ([#4932](https://github.com/ScoopInstaller/Scoop/issues/4932)) - **core:** Allow to use '_' and '.' in bucket name ([#4952](https://github.com/ScoopInstaller/Scoop/issues/4952)) - **depends:** Avoid digits in archive file extension (except for .7z and .001) ([#4915](https://github.com/ScoopInstaller/Scoop/issues/4915)) - **bucket:** Don't check remote URL of non-git buckets ([#4923](https://github.com/ScoopInstaller/Scoop/issues/4923)) - **bucket:** Don't write message OK before bucket is cloned ([#4925](https://github.com/ScoopInstaller/Scoop/issues/4925)) - **shim:** Add 'Get-CommandPath()' to find git ([#4913](https://github.com/ScoopInstaller/Scoop/issues/4913)) - **shim:** Remove character replacement in .cmd -> .ps1 shims ([#4914](https://github.com/ScoopInstaller/Scoop/issues/4914)) - **scoop:** Pass CLI arguments as string objects ([#4931](https://github.com/ScoopInstaller/Scoop/issues/4931)) - **scoop-info:** Fix error message when manifest is not found ([#4935](https://github.com/ScoopInstaller/Scoop/issues/4935)) - **scoop-search:** Require files in 'bucket' dir for remote known buckets ([#4944](https://github.com/ScoopInstaller/Scoop/issues/4944)) - **update:** Prevent uninstall when update ([#4949](https://github.com/ScoopInstaller/Scoop/issues/4949)) - **scoop-download:** Use correct Args when calling `Get-Manifest` ([#4970](https://github.com/ScoopInstaller/Scoop/issues/4970)) ### Code Refactoring - **manifest:** Rename 'Find-Manifest()' to 'Get-Manifest() ([#4966](https://github.com/ScoopInstaller/Scoop/issues/4966), [#4981](https://github.com/ScoopInstaller/Scoop/issues/4981)) ### Documentation - **readme:** Update license badge ([#4929](https://github.com/ScoopInstaller/Scoop/issues/4929)) ## [v0.2.0](https://github.com/ScoopInstaller/Scoop/compare/v0.1.0...v0.2.0) - 2022-05-10 ### Features - **relicense:** Relicense to dual-license (Unlicense or MIT) ([#4903](https://github.com/ScoopInstaller/Scoop/issues/4903), [#4870](https://github.com/ScoopInstaller/Scoop/issues/4870)) - **install:** Allow downloading from private repositories ([#4254](https://github.com/ScoopInstaller/Scoop/issues/4254)) - **scoop-cleanup:** Add `-a/--all` switch to cleanup all apps ([#4906](https://github.com/ScoopInstaller/Scoop/issues/4906)) ### Bug Fixes - **bucket:** Return empty list correctly in `Get-LocalBucket` ([#4885](https://github.com/ScoopInstaller/Scoop/issues/4885)) - **install:** Fix issue with installation inside containers ([#4837](https://github.com/ScoopInstaller/Scoop/issues/4837)) - **installed:** If no `$global`, check both local and global installed ([#4798](https://github.com/ScoopInstaller/Scoop/issues/4798)) - **shim:** Manipulating shims with UTF8 encoding ([#4791](https://github.com/ScoopInstaller/Scoop/issues/4791), [#4813](https://github.com/ScoopInstaller/Scoop/issues/4813)) - **shim:** Correctly quote $@ in sh->ps1 shims ([#4809](https://github.com/ScoopInstaller/Scoop/issues/4809)) - **update:** Skip logs starting with `(chore)` ([#4800](https://github.com/ScoopInstaller/Scoop/issues/4800)) - **scoop-download:** Add failure check ([#4822](https://github.com/ScoopInstaller/Scoop/issues/4822)) - **scoop-list:** Fix date in 'Updated' column showing the months in the place of minutes ([#4880](https://github.com/ScoopInstaller/Scoop/issues/4880)) - **scoop-prefix:** Fix typo that breaks global installed apps ([#4795](https://github.com/ScoopInstaller/Scoop/issues/4795)) ### Performance Improvements - **scoop:** Load libs only once ([#4839](https://github.com/ScoopInstaller/Scoop/issues/4839), [#4884](https://github.com/ScoopInstaller/Scoop/issues/4884)) ### Code Refactoring - **bucket:** Move 'Find-Manifest' and 'list_buckets' to 'buckets' ([#4814](https://github.com/ScoopInstaller/Scoop/issues/4814)) - **relpath:** Use `$PSScriptRoot` instead of `relpath` ([#4793](https://github.com/ScoopInstaller/Scoop/issues/4793)) - **reset_aliases:** Move core function of `reset_aliases` to `scoop` ([#4794](https://github.com/ScoopInstaller/Scoop/issues/4794)) - **config:** Rename checkver_token to gh_token and SCOOP_CHECKVER_TOKEN to SCOOP_GH_TOKEN ([#4832](https://github.com/ScoopInstaller/Scoop/issues/4832), [#4842](https://github.com/ScoopInstaller/Scoop/issues/4842)) ### Builds - **checkver:** Add option to throw error as exception ([#4867](https://github.com/ScoopInstaller/Scoop/issues/4867)) - **schema:** Remove 'description' from required fields ([#4853](https://github.com/ScoopInstaller/Scoop/issues/4853), [#4874](https://github.com/ScoopInstaller/Scoop/issues/4874)) ### Documentation - **changelog:** Rearrange CHANGELOG ([#4897](https://github.com/ScoopInstaller/Scoop/issues/4897)) - **readme:** Update installation instruction ([#4825](https://github.com/ScoopInstaller/Scoop/issues/4825)) - **readme:** Fix badges for Gitter and CI Tests ([#4830](https://github.com/ScoopInstaller/Scoop/issues/4830)) - **scoop-shim:** Fix typo ([#4836](https://github.com/ScoopInstaller/Scoop/issues/4836)) ## [v0.1.0](https://github.com/ScoopInstaller/Scoop/compare/2021-12-26...v0.1.0) - 2022-03-01 ### Features - **scoop-bucket:** List more detailed information for buckets ([#4704](https://github.com/ScoopInstaller/Scoop/issues/4704), [#4756](https://github.com/ScoopInstaller/Scoop/issues/4756), [#4759](https://github.com/ScoopInstaller/Scoop/issues/4759)) - **scoop-cache:** Handle multiple apps and show detailed information ([#4738](https://github.com/ScoopInstaller/Scoop/issues/4738)) - **scoop-cat:** Use `bat` to pretty-print JSON ([#4742](https://github.com/ScoopInstaller/Scoop/issues/4742)) - **scoop-config:** Allow Scoop to ignore running processes during reset/uninstall/update ([#4713](https://github.com/ScoopInstaller/Scoop/issues/4713), [#4731](https://github.com/ScoopInstaller/Scoop/issues/4731)) - **scoop-config:** Show all settings ([#4765](https://github.com/ScoopInstaller/Scoop/issues/4765)) - **scoop-download:** Add `scoop download` command ([#4621](https://github.com/ScoopInstaller/Scoop/issues/4621)) - **scoop-(install|virustotal):** Allow skipping update check ([#4634](https://github.com/ScoopInstaller/Scoop/issues/4634)) - **scoop-list:** Allow list manipulation ([#4718](https://github.com/ScoopInstaller/Scoop/issues/4718)) - **scoop-list:** Show last-updated time ([#4723](https://github.com/ScoopInstaller/Scoop/issues/4723)) - **scoop-info:** Revamp details and show more information ([#4747](https://github.com/ScoopInstaller/Scoop/issues/4747)) - **scoop-shim:** Add `scoop shim` to manipulate shims ([#4727](https://github.com/ScoopInstaller/Scoop/issues/4727), [#4736](https://github.com/ScoopInstaller/Scoop/issues/4736)) ### Bug Fixes - **autoupdate:** Allow checksum file that contains whitespaces ([#4619](https://github.com/ScoopInstaller/Scoop/issues/4619)) - **autoupdate:** Rename $response to $res ([#4706](https://github.com/ScoopInstaller/Scoop/issues/4706)) - **config:** Ensure manipulating config with UTF8 encoding ([#4644](https://github.com/ScoopInstaller/Scoop/issues/4644)) - **config:** Allow scoop config use Unicode characters ([#4631](https://github.com/ScoopInstaller/Scoop/issues/4631)) - **config:** Fix `set_config` bugs ([#3681](https://github.com/ScoopInstaller/Scoop/issues/3681)) - **current:** Remove 'current' while it's not a junction ([#4687](https://github.com/ScoopInstaller/Scoop/issues/4687)) - **depends:** Prevent error on no URL ([#4595](https://github.com/ScoopInstaller/Scoop/issues/4595)) - **depends:** Check if extractor is available ([#4042](https://github.com/ScoopInstaller/Scoop/issues/4042)) - **decompress:** Fix nested Zstd archive extraction ([#4608](https://github.com/ScoopInstaller/Scoop/issues/4608), [#4639](https://github.com/ScoopInstaller/Scoop/issues/4639)) - **installed:** Fix 'core/installed' that mark failed app as 'installed' ([#4650](https://github.com/ScoopInstaller/Scoop/issues/4650), [#4676](https://github.com/ScoopInstaller/Scoop/issues/4676), [#4689](https://github.com/ScoopInstaller/Scoop/issues/4689), [#4785](https://github.com/ScoopInstaller/Scoop/issues/4785)) - **no-junctions:** Fix error when `NO_JUNCTIONS` is been set ([#4722](https://github.com/ScoopInstaller/Scoop/issues/4722), [#4726](https://github.com/ScoopInstaller/Scoop/issues/4726)) - **shim:** Fix PS1 shim error when in different drive in PS7 ([#4614](https://github.com/ScoopInstaller/Scoop/issues/4614)) - **shim:** Fix `sh` shim error in WSL ([#4637](https://github.com/ScoopInstaller/Scoop/issues/4637)) - **shim:** Use `-file` instead of `-command` in ps1 script shims ([#4721](https://github.com/ScoopInstaller/Scoop/issues/4721)) - **shim:** Fix exe shim when app path has white spaces ([#4734](https://github.com/ScoopInstaller/Scoop/issues/4734), [#4780](https://github.com/ScoopInstaller/Scoop/issues/4780)) - **versions:** Fix wrong version number when only one version dir ([#4679](https://github.com/ScoopInstaller/Scoop/issues/4679)) - **versions:** Get current version from failed installation if possible ([#4720](https://github.com/ScoopInstaller/Scoop/issues/4720), [#4725](https://github.com/ScoopInstaller/Scoop/issues/4725)) - **scoop-alias:** Fix alias initialization ([#4737](https://github.com/ScoopInstaller/Scoop/issues/4737)) - **scoop-checkup:** Skip 'check_windows_defender' when have not admin privileges ([#4699](https://github.com/ScoopInstaller/Scoop/issues/4699)) - **scoop-cleanup:** Remove apps other than current version ([#4665](https://github.com/ScoopInstaller/Scoop/issues/4665)) - **scoop-search:** Remove redundant 'bucket/' in search result ([#4773](https://github.com/ScoopInstaller/Scoop/issues/4773)) - **scoop-update:** Skip updating non git buckets ([#4670](https://github.com/ScoopInstaller/Scoop/issues/4670), [#4672](https://github.com/ScoopInstaller/Scoop/issues/4672)) ### Performance Improvements - **uninstall:** Avoid checking all files for unlinking persisted data ([#4681](https://github.com/ScoopInstaller/Scoop/issues/4681), [#4763](https://github.com/ScoopInstaller/Scoop/issues/4763)) ### Code Refactoring - **depends:** Rewrite 'depends.ps1' ([#4638](https://github.com/ScoopInstaller/Scoop/issues/4638), [#4673](https://github.com/ScoopInstaller/Scoop/issues/4673)) - **mklink:** Use 'New-Item' instead of 'mklink' ([#4690](https://github.com/ScoopInstaller/Scoop/issues/4690)) - **rmdir:** Use 'Remove-Item' instead of 'rmdir' ([#4691](https://github.com/ScoopInstaller/Scoop/issues/4691)) - **COMSPEC:** Deprecate use of subshell cmd.exe ([#4692](https://github.com/ScoopInstaller/Scoop/issues/4692)) - **git:** Use 'git -C' to specify the work directory instead of 'Push-Location'/'Pop-Location' ([#4697](https://github.com/ScoopInstaller/Scoop/issues/4697)) - **scoop-info:** Use List View for output ([#4741](https://github.com/ScoopInstaller/Scoop/issues/4741)) - **scoop-config:** Use underscores everywhere ([#4745](https://github.com/ScoopInstaller/Scoop/issues/4745)) ### Builds - **checkver:** Fix output with '-Version' ([#3774](https://github.com/ScoopInstaller/Scoop/issues/3774)) - **schema:** Add '$schema' property ([#4623](https://github.com/ScoopInstaller/Scoop/issues/4623)) - **schema:** Add explicit escape to opening bracket matcher in jp/jsonpath regex ([#3719](https://github.com/ScoopInstaller/Scoop/issues/3719)) - **schema:** Fix typo ('note' -> 'notes') ([#4678](https://github.com/ScoopInstaller/Scoop/issues/4678)) - **tests:** Support both AppVeyor and GitHub Actions ([#4655](https://github.com/ScoopInstaller/Scoop/issues/4655)) - **tests:** Run GitHub Actions CI on each commit ([#4664](https://github.com/ScoopInstaller/Scoop/issues/4664)) - **tests:** Use cache in GitHub Actions ([#4671](https://github.com/ScoopInstaller/Scoop/issues/4671)) - **tests:** Disable CI test on 'push' ([#4677](https://github.com/ScoopInstaller/Scoop/issues/4677)) - **vscode-settings:** Remove 'formatOnSave' trigger ([#4635](https://github.com/ScoopInstaller/Scoop/issues/4635)) ### Styles - **test:** Format scripts by VSCode's PowerShell extension ([#4609](https://github.com/ScoopInstaller/Scoop/issues/4609)) - **style:** Use correct casing for `$PSScriptRoot` ([#4775](https://github.com/ScoopInstaller/Scoop/issues/4775)) ### Tests - **test-bin:** Only write output file in CI and fix trailing whitespaces ([#4613](https://github.com/ScoopInstaller/Scoop/issues/4613)) - **manifest:** Fix manifests validation ([#4620](https://github.com/ScoopInstaller/Scoop/issues/4620)) - **zstd:** Fix 'zstd' extraction error in test ([#4651](https://github.com/ScoopInstaller/Scoop/issues/4651)) ### Documentation - **changelog:** Add 'CHANGLOG.md' ([#4600](https://github.com/ScoopInstaller/Scoop/issues/4600)) - **changelog:** Rearrange CHANGELOG ([#4729](https://github.com/ScoopInstaller/Scoop/issues/4729)) - **changelog:** Link CHANGELOG headers to 'releases/tag' ([#4730](https://github.com/ScoopInstaller/Scoop/issues/4730)) ## [2021-12-26](https://github.com/ScoopInstaller/Scoop/compare/2021-11-22...2021-12-26) ### Features - **core:** Redirect 'StandardError' in `Invoke-ExternalCommand()` ([#4570](https://github.com/ScoopInstaller/Scoop/issues/4570), [#4582](https://github.com/ScoopInstaller/Scoop/issues/4582)) - **install:** Add portableapps.com to strip_filename skips ([#3244](https://github.com/ScoopInstaller/Scoop/issues/3244)) - **install:** Show manifest on installation ([#4155](https://github.com/ScoopInstaller/Scoop/issues/4155), [fb496c48](https://github.com/ScoopInstaller/Scoop/commit/fb496c482bec4063e01b328f943224ab703dbbd8), [#4581](https://github.com/ScoopInstaller/Scoop/issues/4581)) - **template:** Add issue/PR templates ([#4572](https://github.com/ScoopInstaller/Scoop/issues/4572)) - **scoop-cat:** Add `scoop cat` command ([#4532](https://github.com/ScoopInstaller/Scoop/issues/4532)) - **scoop-config:** Document all configuration options ([#4579](https://github.com/ScoopInstaller/Scoop/issues/4579)) ### Bug Fixes - **bucket:** Remove JetBrains bucket ([dec25980](https://github.com/ScoopInstaller/Scoop/commit/dec25980525a81c176b3fd5f238e964db00f3be3)) - **bucket:** Remove nightlies bucket ([48b035d7](https://github.com/ScoopInstaller/Scoop/commit/48b035d7f99baa2e81d87ead4ff03a9594e49c3d)) - **core:** Escape '.' in 'parse_app()'. ([#4578](https://github.com/ScoopInstaller/Scoop/issues/4578)) - **core:** Use '-Encoding ASCII' in 'Out-File' ([#4571](https://github.com/ScoopInstaller/Scoop/issues/4571)) - **depends:** Specify function scope ([4d5fee36](https://github.com/ScoopInstaller/Scoop/commit/4d5fee36e1ed13fc850fd22a5414186aec030c6e)) - **install:** Use `Select-CurrentVersion` ([#4535](https://github.com/ScoopInstaller/Scoop/issues/4535)) - **install:** 'env_add_path' doesn't append '.' ([#4550](https://github.com/ScoopInstaller/Scoop/issues/4550)) - **repo:** Update repo links ([cbe29edd](https://github.com/ScoopInstaller/Scoop/commit/cbe29eddb3475e34740300eb1c2c52715446e3be)) - **scoop-update:** Update apps with '--all' ([ac71fccb](https://github.com/ScoopInstaller/Scoop/commit/ac71fccbecb3d4158f249db9c1b9bb043cb8e966)) - **scoop-update:** Fix scoop update -a requiring arguments ([#4531](https://github.com/ScoopInstaller/Scoop/issues/4531)) ### Code Refactoring - **shim:** Rework shimming logic ([#4543](https://github.com/ScoopInstaller/Scoop/issues/4543), [#4555](https://github.com/ScoopInstaller/Scoop/issues/4555), [3c90d1a0](https://github.com/ScoopInstaller/Scoop/commit/3c90d1a0701b0b64730dbf9ebc8d31f9b9c238f1), [2ec00d57](https://github.com/ScoopInstaller/Scoop/commit/2ec00d576c7e594dc5c0f1eac4536c5310ce6f17)) ### Builds - **auto-pr:** Remove hardcoded 'master' branch ([#4567](https://github.com/ScoopInstaller/Scoop/issues/4567)) - **checkver:** Improve JSONPath extraction support ([#4522](https://github.com/ScoopInstaller/Scoop/issues/4522)) - **checkver:** Use GitHub token from environment ([#4557](https://github.com/ScoopInstaller/Scoop/issues/4557)) - **schema:** Enable autoupdate for 'license' ([#4528](https://github.com/ScoopInstaller/Scoop/issues/4528), [#4596](https://github.com/ScoopInstaller/Scoop/issues/4596)) ### Documentation - **readme:** Add link to Contributing Guide ([5e11c94a](https://github.com/ScoopInstaller/Scoop/commit/5e11c94a544ff2adbdbec5072c32a94d3e5acb9c)) - **readme:** Fix links ([3bb7036e](https://github.com/ScoopInstaller/Scoop/commit/3bb7036ee111bfe58e82ba3d0fd39189b058776a)) ### Reverts - **shim:** Revert [#4229](https://github.com/ScoopInstaller/Scoop/issues/4229) ([#4553](https://github.com/ScoopInstaller/Scoop/issues/4553)) ## [2021-11-22](https://github.com/ScoopInstaller/Scoop/compare/2020-11-26...2021-11-22) ### Features - **bucket:** Move extras bucket to [@ScoopInstaller](https://github.com/ScoopInstaller) ([3e9a4d4e](https://github.com/ScoopInstaller/Scoop/commit/3e9a4d4ea0e7e4d6489099c46a763f58db07e633)) - **decompress:** Support Zstandard archive ([#4372](https://github.com/ScoopInstaller/Scoop/issues/4372), [e35ff313](https://github.com/ScoopInstaller/Scoop/commit/e35ff313a5d35cab1049024938c3423a5f6bf060), [47ebc6f1](https://github.com/ScoopInstaller/Scoop/commit/47ebc6f176b0db0afeb51b4ee237a20b2d8649e9)) - **install:** Handle arch-specific env_add_path ([#4013](https://github.com/ScoopInstaller/Scoop/issues/4013)) - **install:** s/lukesamson/ScoopInstaller in install.ps1 ([5226f26f](https://github.com/ScoopInstaller/Scoop/commit/5226f26f18157ed78f1529144404ec682374452e)) - **message:** Add config to disable aria2 warning message ([#4422](https://github.com/ScoopInstaller/Scoop/issues/4422)) - **shim:** Add another alternative shim written in rust ([#4229](https://github.com/ScoopInstaller/Scoop/issues/4229)) - **scoop-prefix:** Remove unused imports and functions ([#4494](https://github.com/ScoopInstaller/Scoop/issues/4494)) - **scoop-install:** Auto uninstall previous failed installation ([#3281](https://github.com/ScoopInstaller/Scoop/issues/3281)) - **scoop-update:** Add flags `--all` as an alternative to '*' to update all ([#3871](https://github.com/ScoopInstaller/Scoop/issues/3871)) ### Bug Fixes - **core:** Change url() scope to avoid conflict with global aliases ([#4342](https://github.com/ScoopInstaller/Scoop/issues/4342), [#4492](https://github.com/ScoopInstaller/Scoop/issues/4492)) - **install:** Fix `aria2`'s resume download feature ([#3292](https://github.com/ScoopInstaller/Scoop/issues/3292)) - **shim:** Fixed trailing whitespace issue ([#4307](https://github.com/ScoopInstaller/Scoop/issues/4307)) - **scoop-reset:** Skip when app instance is running ([#4359](https://github.com/ScoopInstaller/Scoop/issues/4359)) ### Code Refactoring - **versions:** Refactor 'versions.ps1' ([#3721](https://github.com/ScoopInstaller/Scoop/issues/3721), [e6630272](https://github.com/ScoopInstaller/Scoop/commit/e663027299d03ca768a252fa4bcbc51d124d4cae), [ae892138](https://github.com/ScoopInstaller/Scoop/commit/ae892138423bb9bbf54c8f0bed8331b93199f6b8)) ### Builds - **autoupdate:** Add multiple URL/hash/extract_dir... support ([#3518](https://github.com/ScoopInstaller/Scoop/issues/3518), [#4502](https://github.com/ScoopInstaller/Scoop/issues/4502)) - **schema:** Fix Schema to support `+` in version ([#4504](https://github.com/ScoopInstaller/Scoop/issues/4504)) - **supporting:** Update Json to 12.0.3, Json.Schema to 3.0.14 ([#3352](https://github.com/ScoopInstaller/Scoop/issues/3352)) ### Documentation - **readme:** Capitalize to prevent redirect ([#4483](https://github.com/ScoopInstaller/Scoop/issues/4483)) - **readme:** s/lukesampson/ScoopInstaller in readme ([4f5acd72](https://github.com/ScoopInstaller/Scoop/commit/4f5acd72109a98a148d1bfa269c23a2d43644d23)) - **readme:** Update extras bucket url in readme ([f1a46e10](https://github.com/ScoopInstaller/Scoop/commit/f1a46e109596c55c7e83c77fc1fc9daedbe71636)) - **readme:** Update Java bucket text ([#4514](https://github.com/ScoopInstaller/Scoop/issues/4514)) - **readme:** Update notes about the NirSoft bucket ([#4524](https://github.com/ScoopInstaller/Scoop/issues/4524)) ## [2020-11-26](https://github.com/ScoopInstaller/Scoop/compare/2020-10-22...2020-11-26) ### Bug Fixes - **shim:** Fix Makefile typo ([0948824e](https://github.com/ScoopInstaller/Scoop/commit/0948824ec7269c979882d09342d9a269193cd674)) ([227de6cf](https://github.com/ScoopInstaller/Scoop/commit/227de6cfb8433a86ac0f0a279e691327ae04554c)) ## [2020-10-22](https://github.com/ScoopInstaller/Scoop/compare/2019-10-23...2020-10-22) ### Features - **aria2:** Inline progress ([#3987](https://github.com/ScoopInstaller/Scoop/issues/3987)) - **autoupdate:** Add $urlNoExt and $basenameNoExt substitutions ([#3742](https://github.com/ScoopInstaller/Scoop/issues/3742)) - **config:** Add configuration option for default architecture ([#3778](https://github.com/ScoopInstaller/Scoop/issues/3778)) - **install:** Follow HTTP redirections when downloading a file ([#3902](https://github.com/ScoopInstaller/Scoop/issues/3902)) - **install:** Let pathes in 'env_add_path' be added ascendantly ([#3788](https://github.com/ScoopInstaller/Scoop/issues/3788), [#3976](https://github.com/ScoopInstaller/Scoop/issues/3976)) - **list:** Display main bucket name ([#3759](https://github.com/ScoopInstaller/Scoop/issues/3759)) - **shim:** Add alt-shim support ([#3998](https://github.com/ScoopInstaller/Scoop/issues/3998)) - **scoop-checkup:** Add check_envs_requirements ([#3860](https://github.com/ScoopInstaller/Scoop/issues/3860)) ### Bug Fixes - **bucket:** Update scoop-nonportable URL ([#3776](https://github.com/ScoopInstaller/Scoop/issues/3776)) - **download:** Fosshub download ([#4051](https://github.com/ScoopInstaller/Scoop/issues/4051)) - **download:** Progress bar on small files ([96de9c14](https://github.com/ScoopInstaller/Scoop/commit/96de9c14bb483f9278e4b0a9e22b1923ee752901)) - **hold:** Replace "locked" terminology with "held" for consistency ([#3917](https://github.com/ScoopInstaller/Scoop/issues/3917)) - **git:** Don't execute autostart programs when executing git commands ([#3993](https://github.com/ScoopInstaller/Scoop/issues/3993)) - **git:** Enforce pull without rebase ([#3765](https://github.com/ScoopInstaller/Scoop/issues/3765)) - **install:** Aria2 inline progress negative values ([#4053](https://github.com/ScoopInstaller/Scoop/issues/4053)) - **install:** Fix wrong output of 'install/failed' ([#3784](https://github.com/ScoopInstaller/Scoop/issues/3784), [#3867](https://github.com/ScoopInstaller/Scoop/issues/3867)) - **install:** Re-add "Don't send referer to portableapps.com" ([#3961](https://github.com/ScoopInstaller/Scoop/issues/3961)) - **scoop:** Remove temporary code from the scoop executable ([#3898](https://github.com/ScoopInstaller/Scoop/issues/3898)) - **update:** Update outdated PowerShell 5 warning ([#3986](https://github.com/ScoopInstaller/Scoop/issues/3986)) - **scoop-info:** Check bucket of installed app ([#3740](https://github.com/ScoopInstaller/Scoop/issues/3740)) ### Builds - **checkver:** Present script property ([#3900](https://github.com/ScoopInstaller/Scoop/issues/3900)) ### Tests - **init:** Force pester v4 ([#4040](https://github.com/ScoopInstaller/Scoop/issues/4040)) ## [2019-10-23](https://github.com/ScoopInstaller/Scoop/compare/2019-10-18...2019-10-23) ### Features - **update:** Support $persist_dir in uninstaller.script ([#3692](https://github.com/ScoopInstaller/Scoop/issues/3692)) ### Bug Fixes - **core:** Use [Environment]::Is64BitOperatingSystem instead of [intptr]::size ([#3690](https://github.com/ScoopInstaller/Scoop/issues/3690)) - **git:** Remove unnecessary git_proxy_cmd() calls for local commands ([8ee45a57](https://github.com/ScoopInstaller/Scoop/commit/8ee45a57dc01a525dcf8776bf9bb45263992c81f)) - **install:** Check execution policy ([#3619](https://github.com/ScoopInstaller/Scoop/issues/3619)) - **update:** Fix scoop update changelog output ([e997017f](https://github.com/ScoopInstaller/Scoop/commit/e997017f1a03e2eefef2157acdfefe2e4fced896)) ## [2019-10-18](https://github.com/ScoopInstaller/Scoop/compare/2019-06-24...2019-10-18) ### Features - **core:** Tweak Invoke-ExternalCommand parameters ([#3547](https://github.com/ScoopInstaller/Scoop/issues/3547)) - **install:** Use 7zip when available for faster zip file extraction ([#3460](https://github.com/ScoopInstaller/Scoop/issues/3460)) - **install:** Add arch support to `env_add_path` and `env_set` ([#3503](https://github.com/ScoopInstaller/Scoop/issues/3503)) - **install:** Allow $version to be used in uninstaller scripts ([#3592](https://github.com/ScoopInstaller/Scoop/issues/3592)) - **install:** Allow installing specific version if latest is installed ([11c42d78](https://github.com/ScoopInstaller/Scoop/commit/11c42d782f8adb29fbe0d94daa5f121cdda935ab)) - **update:** Allow updating apps from local manifest or URL ([#3685](https://github.com/ScoopInstaller/Scoop/issues/3685)) ### Bug Fixes - **autoupdate:** Decode basename when extract hash ([#3615](https://github.com/ScoopInstaller/Scoop/issues/3615)) - **autoupdate:** Remove any whitespace from hash ([#3579](https://github.com/ScoopInstaller/Scoop/issues/3579)) - **bucket:** Only lookup directories in buckets folder ([#3631](https://github.com/ScoopInstaller/Scoop/issues/3631)) - **comspec:** Escape variables when calling COMSPEC commands ([#3538](https://github.com/ScoopInstaller/Scoop/issues/3538)) - **decompress:** Fix bugs on extract_dir ([#3540](https://github.com/ScoopInstaller/Scoop/issues/3540)) - **editorconfig:** Add missing } to bat/cmd regex ([#3529](https://github.com/ScoopInstaller/Scoop/issues/3529)) - **help:** Rename help() to scoop_help() ([#3564](https://github.com/ScoopInstaller/Scoop/issues/3564)) - **install:** Use Join-Path instead of string gluing. ([#3566](https://github.com/ScoopInstaller/Scoop/issues/3566)) - **scoop-info:** Fix output for single binaries with alias ([#3651](https://github.com/ScoopInstaller/Scoop/issues/3651)) - **scoop-info:** Remove a whitespace ([#3652](https://github.com/ScoopInstaller/Scoop/issues/3652)) ### Builds - **auto-pr:** Fix git status detection ([7decfd4c](https://github.com/ScoopInstaller/Scoop/commit/7decfd4c107b8d8a59d7eedfe8a56e1801120c2f)) - **auto-pr:** Hard reset bucket after running ([79f8538b](https://github.com/ScoopInstaller/Scoop/commit/79f8538b57b9021db71a279879b9032fefd1ae52)) - **checkurls:** Trim renaming suffix in url ([#3677](https://github.com/ScoopInstaller/Scoop/issues/3677)) ### Continuous Integration - **appveyor:** use VS2019 image to fix PS6 issues ([#3646](https://github.com/ScoopInstaller/Scoop/issues/3646)) - **tests:** Do not force maintainers to have SCOOP_HELPERS ([#3604](https://github.com/ScoopInstaller/Scoop/issues/3604)) ### Documentation - **readme:** Improve installation instructions ([#3600](https://github.com/ScoopInstaller/Scoop/issues/3600)) ## [2019-06-24](https://github.com/ScoopInstaller/Scoop/compare/2019-05-15...2019-06-24) ### Features - **decompress:** Add 'ExtractDir' to 'Expand-...' functions ([#3466](https://github.com/ScoopInstaller/Scoop/issues/3466), [#3470](https://github.com/ScoopInstaller/Scoop/issues/3470), [#3472](https://github.com/ScoopInstaller/Scoop/issues/3472)) - **decompress:** Allow 'Expand-InnoArchive -ExtractDir' to accept '{xxx}' ([#3487](https://github.com/ScoopInstaller/Scoop/issues/3487)) ### Bug Fixes - **config:** Show correct output when removing a config value ([#3462](https://github.com/ScoopInstaller/Scoop/issues/3462)) - **decompress:** Change dark.exe parameter order ([6141e46d](https://github.com/ScoopInstaller/Scoop/commit/6141e46d6ae74b3ccf65e02a1c3fc92e1b4d3e7a)) - **proxy:** Rename parameters for Net.NetworkCredential ([#3483](https://github.com/ScoopInstaller/Scoop/issues/3483)) ### Code Refactoring - **core:** `run()` -> 'Invoke-ExternalCommand()' ([#3432](https://github.com/ScoopInstaller/Scoop/issues/3432)) ### Builds - **checkhashes:** Checkhashes downloading twice when architecture properties does hot have url property ([#3479](https://github.com/ScoopInstaller/Scoop/issues/3479)) - **checkhashes:** Do not call scoop directly ([#3527](https://github.com/ScoopInstaller/Scoop/issues/3527)) ### Documentation - **readme:** Add known buckets to end of readme ([2849e0f9](https://github.com/ScoopInstaller/Scoop/commit/2849e0f96099004f761d7d8c715377e0d2c105f2)) - **readme:** Adjust URL of `runat.json` ([#3484](https://github.com/ScoopInstaller/Scoop/issues/3484)) - **readme:** Fix a small typo ([#3512](https://github.com/ScoopInstaller/Scoop/issues/3512)) - **readme:** Fix typo in readme ([03bb07c8](https://github.com/ScoopInstaller/Scoop/commit/03bb07c8231563fa3a2092b9b52d4dde372f2a8e)) - **readme:** Update readme with correct count of nirsoft apps ([e8d0be66](https://github.com/ScoopInstaller/Scoop/commit/e8d0be663b3bab25d9ee55c597b90bf922f4ec5d)) ## [2019-05-15](https://github.com/ScoopInstaller/Scoop/compare/2019-05-12...2019-05-15) ### Features - **manifest:** XPath support in checkver and autoupdate ([#3458](https://github.com/ScoopInstaller/Scoop/issues/3458)) - **update:** Support changing scoop tracking repository ([#3459](https://github.com/ScoopInstaller/Scoop/issues/3459)) ### Bug Fixes - **autoupdate:** Handle xml namespace in xpath mode ([#3465](https://github.com/ScoopInstaller/Scoop/issues/3465)) ## [2019-05-12](https://github.com/ScoopInstaller/Scoop/releases/tag/2019-05-12) ### BREAKING CHANGE - **core:** Finalize bucket extraction ([#3399](https://github.com/ScoopInstaller/Scoop/issues/3399)) - **core:** Bucket extraction and refactoring ([#3449](https://github.com/ScoopInstaller/Scoop/issues/3449)) ### Features - **autoupdate:** Add 'regex' alias for 'find' ([3453487e](https://github.com/ScoopInstaller/Scoop/commit/3453487ed65378cc9ba2efc658ed6bc1431ef463)) - **autoupdate:** Allow simple metalink and meta4 hash extraction ([ecf627c3](https://github.com/ScoopInstaller/Scoop/commit/ecf627c3b8493b3ccf7ddb882b0c946533774d76)) - **autoupdate:** Add version variables to autoupdate.hash.regex ([#2966](https://github.com/ScoopInstaller/Scoop/issues/2996)) - **autoupdate:** Autoupdate improvements ([#1371](https://github.com/ScoopInstaller/Scoop/issues/1371)) - **autoupdate:** Convert base64 encoded hash values ([04c9ddeb](https://github.com/ScoopInstaller/Scoop/commit/04c9ddeb6d3b99496c39543ad468d34f4f1adeff)) - **autoupdate:** Improve base64 hash detection ([310096e2](https://github.com/ScoopInstaller/Scoop/commit/310096e2386ff3bf9082d547b140a98b92b87a83)) - **core:** Add basic WSL support by appending .exe to powershell ([#2323](https://github.com/ScoopInstaller/Scoop/issues/2323)) - **core:** Add Expand-DarkArchive and some other dependency features ([#3450](https://github.com/ScoopInstaller/Scoop/issues/3450)) - **core:** Enable TLS 1.2 in core.ps1 ([#2074](https://github.com/ScoopInstaller/Scoop/issues/2074)) - **core:** Prepare extraction of main bucket ([#3060](https://github.com/ScoopInstaller/Scoop/issues/3060)) - **core:** Support loading basedirs from config ([#3121](https://github.com/ScoopInstaller/Scoop/issues/3121)) - **core:** Update requirement to version 5 or greater ([#3330](https://github.com/ScoopInstaller/Scoop/issues/3330)) - **core:** Use consistent User-Agent Header on all webrequests ([12962acf](https://github.com/ScoopInstaller/Scoop/commit/12962acfa853593e371d09186e51660aece331e5)) - **core:** Warn on shim overwrite ([#2033](https://github.com/ScoopInstaller/Scoop/issues/2033)) - **debug:** Add option to indent debug output ([bf54a978](https://github.com/ScoopInstaller/Scoop/commit/bf54a978a1bc2efcde52513a60ec5bcb7bb1a44e)) - **decompress:** Allow other args to be passthrough ([#3411](https://github.com/ScoopInstaller/Scoop/issues/3411)) - **download:** Add support for multi-connection downloads via aria2c ([#2312](https://github.com/ScoopInstaller/Scoop/issues/2312)) - **download:** Convert sourceforge urls to use downloads mirror ([#3340](https://github.com/ScoopInstaller/Scoop/issues/3340)) - **install:** Add .NET 4.5 check to scoop install script ([e52c24c9](https://github.com/ScoopInstaller/Scoop/commit/e52c24c94ec805a327440cc07aec699afc7cc308)) - **install:** Set file write permission to global persist dir ([#2524](https://github.com/ScoopInstaller/Scoop/issues/2524)) - **json:** Normalize multi-line strings to string arrays on format ([#2444](https://github.com/ScoopInstaller/Scoop/issues/2444)) - **persist:** Support persisting files without a file extension ([#2408](https://github.com/ScoopInstaller/Scoop/issues/2408)) - **shim:** Add '.com'-type shim ([#3366](https://github.com/ScoopInstaller/Scoop/issues/3366)) - **shim:** Enabled applications which require elevated privileges ([#2053](https://github.com/ScoopInstaller/Scoop/issues/2053)) - **shim:** Enabled shimming of external applications ([#2072](https://github.com/ScoopInstaller/Scoop/issues/2072)) - **shim:** Enabled wide characters forwarding in shims ([#2106](https://github.com/ScoopInstaller/Scoop/issues/2106)) - **shim:** Make shim support PowerShell 2.0 ([#2562](https://github.com/ScoopInstaller/Scoop/issues/2562)) - **shim:** Create sh shim ([#1951](https://github.com/ScoopInstaller/Scoop/issues/1951)) - **shortcuts:** Add subdirectories/arguments for shortcuts ([#1945](https://github.com/ScoopInstaller/Scoop/issues/1945)) - **shortcuts:** Allow $dir, $original_dir and $persist_dir substitutions for shortcuts ([f3ddf0c0](https://github.com/ScoopInstaller/Scoop/commit/f3ddf0c0f81ee2a11466edf5d9f6e38a0fc2b9d4)) - **shortcuts:** Get start menu folder location from environment rather than predefined user profile path ([c245a7fe](https://github.com/ScoopInstaller/Scoop/commit/c245a7fe96ffa0b0fba23bd47f31480ea93cc183)) - **uninstall:** Print purge step to console ([#3123](https://github.com/ScoopInstaller/Scoop/issues/3123)) - **uninstall:** Add support for soft/purge uninstalling of scoop itself ([#2781](https://github.com/ScoopInstaller/Scoop/issues/2781)) - **update:** Add hold/unhold command ([#3444](https://github.com/ScoopInstaller/Scoop/issues/3444)) - **scoop-checkup:** Add NTFS check to checkup command ([#1944](https://github.com/ScoopInstaller/Scoop/issues/1944)) - **scoop-checkup:** Check for LongPaths setting ([#3387](https://github.com/ScoopInstaller/Scoop/issues/3387)) - **scoop-info:** Add scoop-info command ([#2165](https://github.com/ScoopInstaller/Scoop/issues/2165)) - **scoop-info:** Support url manifest ([#2538](https://github.com/ScoopInstaller/Scoop/issues/2538)) - **scoop-prefix:** Add scoop prefix command ([#2117](https://github.com/ScoopInstaller/Scoop/issues/2117)) - **scoop-update:** Add notification for new main bucket ([#3392](https://github.com/ScoopInstaller/Scoop/issues/3392)) - **scoop-update:** Show changelog after updating scoop and buckets ([56c35f8f](https://github.com/ScoopInstaller/Scoop/commit/56c35f8f05ed387997ef1a80ec0362adec6e51a5)) - **scoop-which:** Also show other applications in PATH with 'scoop which' ([79bf99c3](https://github.com/ScoopInstaller/Scoop/commit/79bf99c3c110494d799e147263db7b6f2f921d4e)) ### Bug Fixes - **autoupdate:** Fix base64 hash extraction ([98afb999](https://github.com/ScoopInstaller/Scoop/commit/98afb99990561c4f98f1e1334f348e52b4bee4e7)) - **autoupdate:** Fix base64 hash extraction length ([#2852](https://github.com/ScoopInstaller/Scoop/issues/2852)) - **autoupdate:** Fix metalink hash extraction ([2ad54747](https://github.com/ScoopInstaller/Scoop/commit/2ad547477b1432e7a269c90b393d62d88dce9803)) - **autoupdate:** Fix single line hash extraction ([#3015](https://github.com/ScoopInstaller/Scoop/issues/3015)) - **autoupdate:** Improve auto-update hash extraction regex ([21bf0dea](https://github.com/ScoopInstaller/Scoop/commit/21bf0dea561db021aa59bcd9363792436ac7c162)) - **autoupdate:** Linter fix ([c9539b65](https://github.com/ScoopInstaller/Scoop/commit/c9539b6575e8842a8f895d82b4119c3aef01d7c2)) - **autoupdate:** Use normal variable instead of magic $matches variable name ([d74e0a85](https://github.com/ScoopInstaller/Scoop/commit/d74e0a85b4081745bd1ab107a45794f02299737d)) - **bucket:** Change wording of new_issue_msg() ([e82587df](https://github.com/ScoopInstaller/Scoop/commit/e82587dfc41618474e03347df333e847dfaffc70)) - **bucket:** Fix new_issue_msg ([#3375](https://github.com/ScoopInstaller/Scoop/issues/3375)) - **bucket:** Use $_.Name on gci result ([1eb2609d](https://github.com/ScoopInstaller/Scoop/commit/1eb2609db51587772a4b5d1b6f58114f52639568)) - **config:** Enable writing to hidden .scoop file ([#1982](https://github.com/ScoopInstaller/Scoop/issues/1982)) - **config:** Save and load true/false values as booleans in scoops config ([16aec1a4](https://github.com/ScoopInstaller/Scoop/commit/16aec1a40b45ba241ef2ac45ccf89de7206891be)) - **core:** Allowed underscores in package names ([#2930](https://github.com/ScoopInstaller/Scoop/issues/2930)) - **core:** Clean up some error messages ([#2032](https://github.com/ScoopInstaller/Scoop/issues/2032)) - **core:** Change sf regex not to break some manifests ([#2476](https://github.com/ScoopInstaller/Scoop/issues/2476)) - **core:** Check if 7zip installed via Scoop instead of using 7z.exe from PATH ([55ce0c0b](https://github.com/ScoopInstaller/Scoop/commit/55ce0c0b0c481ec3807655cb7aeac6dfcf9ef271)) - **core:** Filter null or empty string from Scoops directory settings ([5d5c7fa9](https://github.com/ScoopInstaller/Scoop/commit/5d5c7fa91c03f05b705d3420618ec96d8e870174)) - **core:** Fix "enable-encryptionscheme" for OSes before Windows 10 ([#2084](https://github.com/ScoopInstaller/Scoop/issues/2084)) - **core:** Fix bug with Start-Process -Wait, exclusive to PowerShell Core on Windows 7 ([#3415](https://github.com/ScoopInstaller/Scoop/issues/3415)) - **core:** Fix for relative paths ([ff9c0c3d](https://github.com/ScoopInstaller/Scoop/commit/ff9c0c3dafb3567ee958379b83205da84a925ecf)) - **core:** Fix robocopy not releasing a directory after moving it ([e2792f2e](https://github.com/ScoopInstaller/Scoop/commit/e2792f2e02adee5947ebb95022a62282fb61024f)) - **core:** Fix substitute() for arrays ([#2048](https://github.com/ScoopInstaller/Scoop/issues/2048)) - **core:** Format hashes to lowercase ([5d56f8ff](https://github.com/ScoopInstaller/Scoop/commit/5d56f8ff5760ddedaf44eaf9652000e833b0944e)) - **core:** Invoke powershell with -noprofile flag from bash shims ([#3165](https://github.com/ScoopInstaller/Scoop/issues/3165)) - **core:** Removed the bucket from the app name when checking directories ([#2435](https://github.com/ScoopInstaller/Scoop/issues/2435)) - **core:** Return true for checking if a directory is 'in' itself ([ac8a1567](https://github.com/ScoopInstaller/Scoop/commit/ac8a156796cb6d3d9cba24a2839271d924ab8fea)) - **core:** Store last update time as String ([e8af15cc](https://github.com/ScoopInstaller/Scoop/commit/e8af15cc0615b707aee79be95f9c00e3ae0bfd9b)) - **decompress:** Add .bz2 files to decompression ([#2085](https://github.com/ScoopInstaller/Scoop/issues/2085)) - **decompress:** Added retry when unzip fail because of AV ([#1822](https://github.com/ScoopInstaller/Scoop/issues/1822)) - **decompress:** Catch unzip failures from bad file names ([#2472](https://github.com/ScoopInstaller/Scoop/issues/2472)) - **decompress:** Compatible Expand-ZipArchive() with Pscx ([#3425](https://github.com/ScoopInstaller/Scoop/issues/3425)) - **decompress:** Correct deprecation function name ([#3406](https://github.com/ScoopInstaller/Scoop/issues/3406)) - **decompress:** Fix dark parameter order ([87a1e784](https://github.com/ScoopInstaller/Scoop/commit/87a1e784d7463fea36fa41fcb7cb5537cbcfdc52)) - **depends:** Don't force adding dark dependency ([#3453](https://github.com/ScoopInstaller/Scoop/issues/3453)) - **depends:** Don't include the requested app in the list of dependencies ([1bc6a479](https://github.com/ScoopInstaller/Scoop/commit/1bc6a479ee969e44e2b0d83ed6ff19efd86c6ae9)) - **depends:** Fix empty bucket name ([#2827](https://github.com/ScoopInstaller/Scoop/issues/2827)) - **depends:** Fix null reference error when no buckets are configured ([88040972](https://github.com/ScoopInstaller/Scoop/commit/88040972a30b459a3859c7c2f883e47e19da9f84)) - **depends:** Show message about missing bucket when installing dependencies ([7a6218c5](https://github.com/ScoopInstaller/Scoop/commit/7a6218c58677170fe32cf1c2bfcfe7488e4c3655)) - **download:** Don't send referer to portableapps.com ([0c2b3da3](https://github.com/ScoopInstaller/Scoop/commit/0c2b3da3ff639722ad3ddf587219bb3155e97c7f)) - **download:** Fix fosshub downloads with aria2c ([803525a8](https://github.com/ScoopInstaller/Scoop/commit/803525a8661ffaa39fc4ad6f0dc776cccad4c45e)) - **download:** Interrupt download causes partial cache file to be used for next install ([5be02865](https://github.com/ScoopInstaller/Scoop/commit/5be0286561398debfee2c0610e51f006ef2dc2fb)) - **download:** Overwrite any existing files when extracting ([58cca68f](https://github.com/ScoopInstaller/Scoop/commit/58cca68f7565bd5e8f63e08ad052c0029b98a23d)) - **download:** Show warning about SourceForge.net hash validation fails ([8504338b](https://github.com/ScoopInstaller/Scoop/commit/8504338bc5faab3235cef2e1c2f41abd7ae496eb)) - **getopt:** Don't try to parse int arguments ([23fe5a53](https://github.com/ScoopInstaller/Scoop/commit/23fe5a5319d4ede84c532df04f576c3854fd5826)) - **getopt:** Don't try to parse array arguments ([9b6e7b5e](https://github.com/ScoopInstaller/Scoop/commit/9b6e7b5e0f7f6ddecdb139f932ad7d582fe639a4)) - **getopt:** Return remaining args, use getopt for scoop install ([b7cfd6fd](https://github.com/ScoopInstaller/Scoop/commit/b7cfd6fdb0e18a623ceacfa6fc824241dabc6d01)) - **getopt:** Skip if arg is $null ([f2d9f0d7](https://github.com/ScoopInstaller/Scoop/commit/f2d9f0d79fdf4a63879c1b87a6c0f5317a40a1d9)) - **getopt:** Skip arg if it's decimal ([5f0c8cfb](https://github.com/ScoopInstaller/Scoop/commit/5f0c8cfb0a34078bb8118a21191cf046ddad18ac)) - **git:** Disable git pager when running git log ([cac99759](https://github.com/ScoopInstaller/Scoop/commit/cac9975924691fe6e608789218b06be56bb8c658)) - **git:** Fix update log output ([0daa25c6](https://github.com/ScoopInstaller/Scoop/commit/0daa25c6300cd2ab605d63b71037d741c9c904c6)) - **json:** Catch JsonReaderException ([fb58e92c](https://github.com/ScoopInstaller/Scoop/commit/fb58e92c13552199f19f5df112801fc41321eee2)) - **install:** Add filename to warning for files without hash in the manifest ([4c9beee8](https://github.com/ScoopInstaller/Scoop/commit/4c9beee8f2df891b2ec314e1efffb2ee9d5cca20)) - **install:** Add multi-line support to pre/post_install ([#1980](https://github.com/ScoopInstaller/Scoop/issues/1980)) - **install:** Added exclusion for sourceforge. [#METR-21516] ([#2109](https://github.com/ScoopInstaller/Scoop/issues/2109)) - **install:** Ignore url fragment for PowerShell Core 6.1.0 ([#2602](https://github.com/ScoopInstaller/Scoop/issues/2602)) - **install:** Fix fail when installing from non-default bucket ([#2247](https://github.com/ScoopInstaller/Scoop/issues/2247)) - **install:** Fix PowerShell core crash ([#2554](https://github.com/ScoopInstaller/Scoop/issues/2554)) - **install:** Option to skip hash validation and error message improvements ([#2260](https://github.com/ScoopInstaller/Scoop/issues/2260)) - **install:** Remove env_ensure_home ([#1967](https://github.com/ScoopInstaller/Scoop/issues/1967)) - **install:** Show first 8 bytes of file in the hash check error message ([e4cbb42e](https://github.com/ScoopInstaller/Scoop/commit/e4cbb42e64843e53b5b24de92f43062bca98c474)) - **persist:** Fix condition for persist_permission() ([eb7b7cbf](https://github.com/ScoopInstaller/Scoop/commit/eb7b7cbf4f30e4122762856723155f3c1e980d1b)) ([1a2598bc](https://github.com/ScoopInstaller/Scoop/commit/1a2598bc3082a2e3fffac1a6bea0b42032e388f0)) - **persist:** Fixed persisting bug when force update app with same version ([#2774](https://github.com/ScoopInstaller/Scoop/issues/2774)) - **persist:** Fix the target didn't be created ([#3008](https://github.com/ScoopInstaller/Scoop/issues/3008)) - **persist:** Prevent directory creation from being output ([#1999](https://github.com/ScoopInstaller/Scoop/issues/1999)) - **scoop:** Force to add new main bucket ([#3419](https://github.com/ScoopInstaller/Scoop/issues/3419)) - **shim:** Fix .ps1 shim parsing logic ([#2564](https://github.com/ScoopInstaller/Scoop/issues/2564)) - **shim:** Fixed ps1/jar->ps1 shims args handling ([#2120](https://github.com/ScoopInstaller/Scoop/issues/2120)) - **shortcuts:** Improve Shortcut creation ([83b82386](https://github.com/ScoopInstaller/Scoop/commit/83b823868f5ef5256d3dcfbecff278bb355fefc8)) - **uninstall:** Better error handling during uninstallation ([#2079](https://github.com/ScoopInstaller/Scoop/issues/2079)) - **uninstall:** Uninstall fails to remove architecture-specific shims ([8b1871b2](https://github.com/ScoopInstaller/Scoop/commit/8b1871b20df4dbf1b603d4066937ba213c03bb32)) - **update:** Rewording PowerShell update notice ([d006fb93](https://github.com/ScoopInstaller/Scoop/commit/d006fb9315b55a9d8e6a36218cf5dbdde51433ec)) - **versions:** Improvements for the reset command to deal with empty current alias dir correctly ([#2896](https://github.com/ScoopInstaller/Scoop/issues/2896)) - **scoop-alias:** Improve "scoop alias list" output ([#2163](https://github.com/ScoopInstaller/Scoop/issues/2163)) - **scoop-cache:** Display help on incorrect cache command ([#3431](https://github.com/ScoopInstaller/Scoop/issues/3431)) - **scoop-cache:** scoop cache command not using $SCOOP_CACHE ([#1990](https://github.com/ScoopInstaller/Scoop/issues/1990)) - **scoop-info:** Improve scoop-info license attributes output ([#2397](https://github.com/ScoopInstaller/Scoop/issues/2397)) - **scoop-install:** Prevent installing programs from JSON multiple times ([936cf9cb](https://github.com/ScoopInstaller/Scoop/commit/936cf9cbb0c4dd3a594fbaf5c696ce519e586d8c)) - **scoop-reset:** Persist data on reset ([#2773](https://github.com/ScoopInstaller/Scoop/issues/2773)) - **scoop-reset:** Re-create shortcuts ([6e5b7e57](https://github.com/ScoopInstaller/Scoop/commit/6e5b7e57bb0628f072872d9a5b8c8a0fa58389e1)) - **scoop-search:** Better handling for invalid query ([bf024705](https://github.com/ScoopInstaller/Scoop/commit/bf024705a8cc38592571aa3026dca2471f19ac5a)) - **scoop-uninstall:** Checked if uninstaller removed its directory ([#2078](https://github.com/ScoopInstaller/Scoop/issues/2078)) - **scoop-update:** Add config option "show_update_log" ([d68cb3ce](https://github.com/ScoopInstaller/Scoop/commit/d68cb3ce52acaa9983f278822febd506f54ebe02)) - **scoop-update:** First scoop update fails because scoop deletes itself too early ([376630fd](https://github.com/ScoopInstaller/Scoop/commit/376630fd80a3f9012fd6e673460b9e28e375e951)) - **scoop-update:** Fix branch switching ([#3372](https://github.com/ScoopInstaller/Scoop/issues/3372)) - **scoop-update:** Fix update with cookies ([#3261](https://github.com/ScoopInstaller/Scoop/issues/3261)) - **scoop-update:** Improve is_scoop_outdated() and add last_scoop_update() ([f3f559c4](https://github.com/ScoopInstaller/Scoop/commit/f3f559c460406689dab2375310fb1026e2be58bd)) - **scoop-update:** Resolve linting, fix appveyor tests error ([#2148](https://github.com/ScoopInstaller/Scoop/issues/2148)) ### Code Refactoring - **bucket:** Move function into lib from lib-exec ([#3062](https://github.com/ScoopInstaller/Scoop/issues/3062)) - **bucket:** Optimize buckets function ([#3341](https://github.com/ScoopInstaller/Scoop/issues/3341)) - **config:** Move configuration handling to core.ps1 ([#3242](https://github.com/ScoopInstaller/Scoop/issues/3242)) - **core:** aria2_path() -> file_path() ([0f464016](https://github.com/ScoopInstaller/Scoop/commit/0f4640168da8d68a52eb2b80af2f3ffa01c9b658)) - **core:** cmd_available() -> Test-CommandAvailable() ([#3314](https://github.com/ScoopInstaller/Scoop/issues/3314)) - **core:** ensure_all_installed() -> Confirm-InstallationStatus() ([#3293](https://github.com/ScoopInstaller/Scoop/issues/3293)) - **core:** Move default_aliases into the scoped function ([#3233](https://github.com/ScoopInstaller/Scoop/issues/3233)) - **core:** Refactor function names and fix installing 7zip locally if already globally available ([#3416](https://github.com/ScoopInstaller/Scoop/issues/3416)) - **core:** Simplified last_scoop_update() ([#2931](https://github.com/ScoopInstaller/Scoop/issues/2931)) - **core:** Tweak SecurityProtocol usage ([#3065](https://github.com/ScoopInstaller/Scoop/issues/3065)) - **decompress:** Refactored (w/ install.ps1, core.ps1) ([#3169](https://github.com/ScoopInstaller/Scoop/issues/3169)) - **decompress:** Refactor extraction handling functions ([#3204](https://github.com/ScoopInstaller/Scoop/issues/3204)) - **download:** Download functionality refactor ([#1329](https://github.com/ScoopInstaller/Scoop/issues/1329)) - **install:** Rename locate() to Find-Manifest() ([9eed3d89](https://github.com/ScoopInstaller/Scoop/commit/9eed3d8914c7a0fa294110eb0761776a01adf034)) ### Builds - **auto-pr:** Add -App parameter ([#3157](https://github.com/ScoopInstaller/Scoop/issues/3157)) - **auto-pr:** Add SkipUpdated parameter ([#3168](https://github.com/ScoopInstaller/Scoop/issues/3168)) - **checkhashes:** Add bin\checkhashes.ps1 ([#2766](https://github.com/ScoopInstaller/Scoop/issues/2766)) - **checkurls:** Add SkipValid Parameter ([#2845](https://github.com/ScoopInstaller/Scoop/issues/2845)) - **checkurls:** Import config.ps1 in checkurls.ps1 ([126e9c97](https://github.com/ScoopInstaller/Scoop/commit/126e9c97d2ef7db537a5137167089a97f343e98e)) - **checkver:** Add 'useragent' property ([8feb3867](https://github.com/ScoopInstaller/Scoop/commit/8feb3867a74ea0340585e3e695934d96cf483a05)) - **checkver:** Add 'jsonpath' alias for 'jp' ([76fdb6b7](https://github.com/ScoopInstaller/Scoop/commit/76fdb6b74c1772bf607d2dad5f6c50269369ff88)) - **checkver:** Add 're' alias 'regex' ([468649c8](https://github.com/ScoopInstaller/Scoop/commit/468649c88dea9c1ff9614f2cdf29a521d572664e)) - **checkver:** Allow using the current version in checkver URL ([607ac9ca](https://github.com/ScoopInstaller/Scoop/commit/607ac9ca7c185da61e2c746ea87d28c2abe62adc)) - **checkver:** Fix example parameters ([#3413](https://github.com/ScoopInstaller/Scoop/issues/3413)) - **checkver:** GitHub checkver case-insensitive version check ([2e2633e9](https://github.com/ScoopInstaller/Scoop/commit/2e2633e9640f6cab5c2f895b680345cd6ca)) - **checkver:** Remove old commented code ([72754036](https://github.com/ScoopInstaller/Scoop/commit/72754036a251fffd2f2eb0e242edfd9895543e3c)) - **checkver:** Resolve issue on Powershell >6.1.0 ([#2592](https://github.com/ScoopInstaller/Scoop/issues/2592)) - **checkver:** Support skipping up to date manifests ([#2624](https://github.com/ScoopInstaller/Scoop/issues/2624)) - **schema:** Add shortcutsArray definition to schema.json ([0c7e6002](https://github.com/ScoopInstaller/Scoop/commit/0c7e60024a06e122331b17a204a158e4c5800a3d)) - **schema:** extract_to property is on active duty (not deprecated) ([59e994c5](https://github.com/ScoopInstaller/Scoop/commit/59e994c5fdeb8dffe6037ca6767d56ad13bf04da)) - **schema:** Improve comments in schema.json ([b5ed0761](https://github.com/ScoopInstaller/Scoop/commit/b5ed0761aef4f3e864533dc0460d110115850ba7)) - **supporting:** Update validator.exe and shim.exe ([#2024](https://github.com/ScoopInstaller/Scoop/issues/2024), [#2034](https://github.com/ScoopInstaller/Scoop/issues/2034)) - **supporting:** Update Newtonsoft.Json to 11.0.2, Newtonsoft.Json.Schema to 3.0.10 ([#3043](https://github.com/ScoopInstaller/Scoop/issues/3043)) - **validator:** Improve error reporting, add support for multiple files ([#3134](https://github.com/ScoopInstaller/Scoop/issues/3134)) ### Continuous Integration - **appveyor:** Rebuild cache ([7311b41b](https://github.com/ScoopInstaller/Scoop/commit/7311b41b8d1e2e010175fb7d079662bbcba5bac8)) - **appveyor:** Run tests for PowerShell 5 and 6 ([#2603](https://github.com/ScoopInstaller/Scoop/issues/2603)) - **test:** Improve installation of lessmsi and innounp ([#3409](https://github.com/ScoopInstaller/Scoop/issues/3409)) ### Styles - **lint:** PSAvoidUsingCmdletAliases ([#2075](https://github.com/ScoopInstaller/Scoop/issues/2075)) ### Tests - **bucket:** Add importable tests for Buckets ([478f52c4](https://github.com/ScoopInstaller/Scoop/commit/478f52c421ca35ea35b5fd0b2df2631cf7d82487)) - **bucket:** Fix manifest tests for buckets ([589303fa](https://github.com/ScoopInstaller/Scoop/commit/589303facc5284f6f95c1305191e0558c0169691)) - **bucket:** Handle JSON.NET schema validation limit exceeded. ([139813a8](https://github.com/ScoopInstaller/Scoop/commit/139813a8f50ace85e2752d9b6c9f82fc64ff3e48)) - **file:** Move style constraints tests to separate test file ([7b7113fc](https://github.com/ScoopInstaller/Scoop/commit/7b7113fc3bf962aaeba625f58341c30a80f0fe6a)) - **linux:** Fix some tests on linux ([#2153](https://github.com/ScoopInstaller/Scoop/issues/2153)) - **manifest:** Expose bucketdir variable in manifest test script ([#2182](https://github.com/ScoopInstaller/Scoop/issues/2182)) - **test:** Add -TestPath param to test.ps1 ([f857dce9](https://github.com/ScoopInstaller/Scoop/commit/f857dce9f59a490f6dd07085c3abaa51e9577fda)) - **test:** Force install PSScriptAnalyzer and BuildHelpers ([7a1b5a18](https://github.com/ScoopInstaller/Scoop/commit/7a1b5a1840e30321951fa0f5333c34d10f57fa94)) - **test:** Require BuildHelpers version 2.0.0 ([ac3ee766](https://github.com/ScoopInstaller/Scoop/commit/ac3ee766722e99c1f15dc60a1f1dfb0a48428c55)) - **test:** Update BuildHelpers to version 2.0.1 ([dde4d0f9](https://github.com/ScoopInstaller/Scoop/commit/dde4d0f93f260191af5524c0ecab927f3e252361)) - **core:** Use Pester 4.0 syntax in core tests ([#2712](https://github.com/ScoopInstaller/Scoop/issues/2712)) - **install:** Use Pester 4.0 syntax to the install tests ([#2713](https://github.com/ScoopInstaller/Scoop/issues/2713)) - **test:** Use Pester 4.0 syntax to multiple files ([#2714](https://github.com/ScoopInstaller/Scoop/issues/2714)) ### Documentation - **readme:** Add discord chat badge ([#3241](https://github.com/ScoopInstaller/Scoop/issues/3241)) - **readme:** Add more details about scoops installation ([#2273](https://github.com/ScoopInstaller/Scoop/issues/2273)) - **readme:** Corrected enable powershell executionpolicy ([#2020](https://github.com/ScoopInstaller/Scoop/issues/2020)) - **readme:** Update Discord invite link ([5f269249](https://github.com/ScoopInstaller/Scoop/commit/5f269249609b43f5c4fa9aba4def999e7ee05fe1)) - **readme:** Update requirements note ([#2509](https://github.com/ScoopInstaller/Scoop/issues/2509)) - **readme:** Fix typo (you -> your), (it's -> its) ([#2698](https://github.com/ScoopInstaller/Scoop/issues/2698)) - **readme:** Remove trailing whitespaces ([d25186bf](https://github.com/ScoopInstaller/Scoop/commit/d25186bf1f833e30d8c5b530b7c260fe399b75ed)) - **readme:** Remove "tail" from example (is coreutils) ([#2158](https://github.com/ScoopInstaller/Scoop/issues/2158)) ## *Commits before 2018 are trimmed* ================================================ FILE: LICENSE ================================================ SPDX-License-Identifier: UNLICENSE or MIT INFORMATION ABOUT THIS PROJECT'S LICENSE (SHORT) ============================================================================================ This project is licensed under the Unlicense or the MIT license, at your option. INFORMATION ABOUT THIS PROJECT'S LICENSE (LONG) ============================================================================================ This project ("Scoop") is free software, licensed under the Unlicense or the MIT license, at your option. Scoop was previously licensed under only the Unlicense, but was dual-licensed from version 0.2.0. Scoop comes with ABSOLUTELY NO WARRANTY. Use it at your own risk. Scoop is provided on an AS-IS BASIS and its contributors disclaim all warranties. You may use, modify, distribute, sell, copy, compile, or merge Scoop by any means. Copies of both licenses can be found below. THE LICENSE OF SCOOP ============================================================================================ Unlicense --------- This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to MIT license ----------- The MIT License (MIT) Copyright (c) 2013-2017 Luke Sampson (https://github.com/lukesampson) Copyright (c) 2013-present Scoop contributors (https://github.com/ScoopInstaller/Scoop/graphs/contributors) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: PSScriptAnalyzerSettings.psd1 ================================================ @{ # Only diagnostic records of the specified severity will be generated. # Uncomment the following line if you only want Errors and Warnings but # not Information diagnostic records. Severity = @('Error') # Analyze **only** the following rules. Use IncludeRules when you want # to invoke only a small subset of the defualt rules. # IncludeRules = @('PSAvoidDefaultValueSwitchParameter', # 'PSMisleadingBacktick', # 'PSMissingModuleManifestField', # 'PSReservedCmdletChar', # 'PSReservedParams', # 'PSShouldProcess', # 'PSUseApprovedVerbs', # 'PSAvoidUsingCmdletAliases', # 'PSUseDeclaredVarsMoreThanAssignments') # Do not analyze the following rules. Use ExcludeRules when you have # commented out the IncludeRules settings above and want to include all # the default rules except for those you exclude below. # Note: if a rule is in both IncludeRules and ExcludeRules, the rule # will be excluded. ExcludeRules = @( # Currently Scoop widely uses Write-Host to output colored text. 'PSAvoidUsingWriteHost' ) } ================================================ FILE: README.md ================================================

Scoop

Features | Installation | Documentation

---

Code Size Repository size Scoop Core CI Tests Discord Chat Gitter Chat License

Scoop is a command-line installer for Windows. ## What does Scoop do? Scoop installs apps from the command line with a minimal amount of friction. It: - Eliminates [User Account Control](https://learn.microsoft.com/windows/security/application-security/application-control/user-account-control/) (UAC) prompt notifications. - Hides the graphical user interface (GUI) of wizard-style installers. - Prevents polluting the `PATH` environment variable. Normally, this variable gets cluttered as different apps are installed on the device. - Avoids unexpected side effects from installing and uninstalling apps. - Resolves and installs dependencies automatically. - Performs all the necessary steps to get an app to a working state. Scoop is quite script-friendly. Your environment can become the way you like by using repeatable setups. For example: ```console scoop install sudo sudo scoop install 7zip git openssh --global scoop install aria2 curl grep sed less touch scoop install python ruby go perl ``` If you have built software that you would like others to use, Scoop is an alternative to building an installer (like MSI or InnoSetup). You just need to compress your app to a `.zip` file and provide a JSON manifest that describes how to install it. ## Installation Run the following commands from a regular (non-admin) PowerShell terminal to install Scoop: ```powershell Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser Invoke-RestMethod -Uri https://get.scoop.sh | Invoke-Expression ``` **Note**: The first command makes your device allow running the installation and management scripts. This is necessary because Windows 10 client devices restrict execution of any PowerShell scripts by default. It will install Scoop to its default location: `C:\Users\\scoop` You can find the complete documentation about the installer, including advanced installation configurations, in [ScoopInstaller/Install](https://github.com/ScoopInstaller/Install). Please create new issues there if you have questions about the installation. ## Multi-connection downloads with `aria2` Scoop can utilize [`aria2`](https://github.com/aria2/aria2) to use multi-connection downloads. Simply install `aria2` through Scoop and it will be used for all downloads afterward. ```console scoop install aria2 ``` By default, `scoop` displays a warning when running `scoop install` or `scoop update` while `aria2` is enabled. This warning can be suppressed by running `scoop config aria2-warning-enabled false`. You can tweak the following `aria2` settings with the `scoop config` command: - aria2-enabled (default: true) - aria2-warning-enabled (default: true) - [aria2-retry-wait](https://aria2.github.io/manual/en/html/aria2c.html#cmdoption-retry-wait) (default: 2) - [aria2-split](https://aria2.github.io/manual/en/html/aria2c.html#cmdoption-s) (default: 5) - [aria2-max-connection-per-server](https://aria2.github.io/manual/en/html/aria2c.html#cmdoption-x) (default: 5) - [aria2-min-split-size](https://aria2.github.io/manual/en/html/aria2c.html#cmdoption-k) (default: 5M) - [aria2-options](https://aria2.github.io/manual/en/html/aria2c.html#options) (default: ) ## Inspiration - [Homebrew](https://brew.sh/) - [Sub](https://signalvnoise.com/posts/3264-automating-with-convention-introducing-sub) ## What sort of apps can Scoop install? The apps that are most likely to get installed fine with Scoop are those referred to as "portable" apps. These apps are compressed files which can run standalone after being extracted. This type of apps does not produce side effects like changing the Windows Registry or placing files outside the app directory. Scoop also supports installer files and their uninstallation methods. Likewise, it can handle single-file apps and PowerShell scripts. These do not even need to be compressed. See the [runat](https://github.com/ScoopInstaller/Main/blob/master/bucket/runat.json) package for an example: it is simply a GitHub gist. ### Contribute to this project If you would like to improve Scoop by adding features or fixing bugs, please read our [Contributing Guide](https://github.com/ScoopInstaller/.github/blob/main/.github/CONTRIBUTING.md). ### Support this project If you find Scoop useful and would like to support the ongoing development and maintenance of this project, you can donate here: - [PayPal](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=DM2SUH9EUXSKJ) (one-time donations) ## Known application buckets The following buckets are known to Scoop: - [main](https://github.com/ScoopInstaller/Main) - Default bucket which contains popular non-GUI apps. - [extras](https://github.com/ScoopInstaller/Extras) - Apps that do not fit the main bucket's [criteria](https://github.com/ScoopInstaller/Scoop/wiki/Criteria-for-including-apps-in-the-main-bucket). - [games](https://github.com/Calinou/scoop-games) - Open-source and freeware video games and game-related tools. - [nerd-fonts](https://github.com/matthewjberger/scoop-nerd-fonts) - Nerd Fonts. - [nirsoft](https://github.com/ScoopInstaller/Nirsoft) - A collection of over 250+ apps from [Nirsoft](https://nirsoft.net). - [sysinternals](https://github.com/niheaven/scoop-sysinternals) - The Sysinternals suite from [Microsoft](https://learn.microsoft.com/sysinternals/). - [java](https://github.com/ScoopInstaller/Java) - A collection of Java development kits (JDKs) and Java runtime engines (JREs), Java's virtual machine debugging tools and Java based runtime engines. - [nonportable](https://github.com/ScoopInstaller/Nonportable) - Non-portable apps (may trigger UAC prompts). - [php](https://github.com/ScoopInstaller/PHP) - Installers for most versions of PHP. - [versions](https://github.com/ScoopInstaller/Versions) - Alternative versions of apps found in other buckets. The `main` bucket is installed by default. You can make use of more buckets by typing: ```console scoop bucket add ``` For example, to add the `extras` bucket, type: ```console scoop bucket add extras ``` You would be able to install apps from the `extras` bucket now. ## Other application buckets Many other application buckets hosted on GitHub can be found on [ScoopSearch](https://scoop.sh/) or via [other search engines](https://rasa.github.io/scoop-directory/#other-search-engines). ================================================ FILE: appveyor.yml ================================================ version: "{build}-{branch}" branches: except: - gh-pages build: false deploy: false clone_depth: 2 image: Visual Studio 2022 environment: matrix: - PowerShell: 5 - PowerShell: 7 matrix: fast_finish: true for: - matrix: only: - PowerShell: 5 cache: - '%USERPROFILE%\Documents\WindowsPowerShell\Modules -> appveyor.yml, test\bin\*.ps1' - C:\projects\helpers -> appveyor.yml, test\bin\*.ps1 install: - ps: .\test\bin\init.ps1 test_script: - ps: .\test\bin\test.ps1 - matrix: only: - PowerShell: 7 cache: - '%USERPROFILE%\Documents\PowerShell\Modules -> appveyor.yml, test\bin\*.ps1' - C:\projects\helpers -> appveyor.yml, test\bin\*.ps1 install: - pwsh: .\test\bin\init.ps1 test_script: - pwsh: .\test\bin\test.ps1 ================================================ FILE: bin/auto-pr.ps1 ================================================ <# .SYNOPSIS Updates manifests and pushes them or creates pull-requests. .DESCRIPTION Updates manifests and pushes them directly to the origin branch or creates pull-requests for upstream. .PARAMETER Upstream Upstream repository with the target branch. Must be in format '/:' .PARAMETER OriginBranch Origin (local) branch name. .PARAMETER App Manifest name to search. Placeholders are supported. .PARAMETER CommitMessageFormat The format of the commit message. will be replaced with the file name of manifest. will be replaced with the version of the latest manifest. .PARAMETER Dir The directory where to search for manifests. .PARAMETER Push Push updates directly to 'origin branch'. .PARAMETER Request Create pull-requests on 'upstream branch' for each update. .PARAMETER Help Print help to console. .PARAMETER SpecialSnowflakes An array of manifests, which should be updated all the time. (-ForceUpdate parameter to checkver) .PARAMETER SkipUpdated Updated manifests will not be shown. .PARAMETER ThrowError Throw error as exception instead of just printing it. .EXAMPLE PS BUCKETROOT > .\bin\auto-pr.ps1 'someUsername/repository:branch' -Request .EXAMPLE PS BUCKETROOT > .\bin\auto-pr.ps1 -Push Update all manifests inside 'bucket/' directory. #> param( [Parameter(Mandatory = $true)] [ValidateScript( { if (!($_ -match '^(.*)\/(.*):(.*)$')) { throw 'Upstream must be in this format: /:' } $true })] [String] $Upstream, [String] $OriginBranch = 'master', [String] $App = '*', [String] $CommitMessageFormat = ': Update to version ', [ValidateScript( { if (!(Test-Path $_ -Type Container)) { throw "$_ is not a directory!" } else { $true } })] [String] $Dir, [Switch] $Push, [Switch] $Request, [Switch] $Help, [string[]] $SpecialSnowflakes, [Switch] $SkipUpdated, [Switch] $ThrowError ) . "$PSScriptRoot\..\lib\manifest.ps1" . "$PSScriptRoot\..\lib\json.ps1" if ($App -ne '*' -and (Test-Path $App -PathType Leaf)) { $Dir = Split-Path $App } elseif ($Dir) { $Dir = Convert-Path $Dir } else { throw "'-Dir' parameter required if '-App' is not a filepath!" } if ((!$Push -and !$Request) -or $Help) { Write-Host @' Usage: auto-pr.ps1 [OPTION] Mandatory options: -p, -push push updates directly to 'origin branch' -r, -request create pull-requests on 'upstream branch' for each update Optional options: -u, -upstream upstream repository with target branch -o, -originbranch origin (local) branch name -h, -help '@ exit 0 } if ($IsLinux -or $IsMacOS) { if (!(which hub)) { Write-Host "Please install hub ('brew install hub' or visit: https://hub.github.com/)" -ForegroundColor Yellow exit 1 } } else { if (!(scoop which hub)) { Write-Host "Please install hub 'scoop install hub'" -ForegroundColor Yellow exit 1 } } function execute($cmd) { Write-Host $cmd -ForegroundColor Green $output = Invoke-Command ([scriptblock]::Create($cmd)) if ($LASTEXITCODE -gt 0) { abort "^^^ Error! See above ^^^ (last command: $cmd)" } return $output } function pull_requests($json, [String] $app, [String] $upstream, [String] $manifest, [String] $commitMessage) { $version = $json.version $homepage = $json.homepage $branch = "manifest/$app-$version" execute "hub checkout $OriginBranch" Write-Host "hub rev-parse --verify $branch" -ForegroundColor Green hub rev-parse --verify $branch if ($LASTEXITCODE -eq 0) { Write-Host "Skipping update $app ($version) ..." -ForegroundColor Yellow return } Write-Host "Creating update $app ($version) ..." -ForegroundColor DarkCyan execute "hub checkout -b $branch" execute "hub add $manifest" execute "hub commit -m '$commitMessage" Write-Host "Pushing update $app ($version) ..." -ForegroundColor DarkCyan execute "hub push origin $branch" if ($LASTEXITCODE -gt 0) { error "Push failed! (hub push origin $branch)" execute 'hub reset' return } Start-Sleep 1 Write-Host "Pull-Request update $app ($version) ..." -ForegroundColor DarkCyan Write-Host "hub pull-request -m '' -b '$upstream' -h '$branch'" -ForegroundColor Green $msg = @" $commitMessage Hello lovely humans, a new version of [$app]($homepage) is available. | State | Update :rocket: | | :---------- | :-------------- | | New version | $version | "@ hub pull-request -m "$msg" -b "$upstream" -h "$branch" if ($LASTEXITCODE -gt 0) { execute 'hub reset' abort "Pull Request failed! (hub pull-request -m '$commitMessage' -b '$upstream' -h '$branch')" } } Write-Host 'Updating ...' -ForegroundColor DarkCyan if ($Push) { execute "hub pull origin $OriginBranch" execute "hub checkout $OriginBranch" } else { execute "hub pull upstream $OriginBranch" execute "hub push origin $OriginBranch" } . "$PSScriptRoot\checkver.ps1" -App $App -Dir $Dir -Update -SkipUpdated:$SkipUpdated -ThrowError:$ThrowError if ($SpecialSnowflakes) { Write-Host "Forcing update on our special snowflakes: $($SpecialSnowflakes -join ',')" -ForegroundColor DarkCyan $SpecialSnowflakes -split ',' | ForEach-Object { . "$PSScriptRoot\checkver.ps1" $_ -Dir $Dir -ForceUpdate -ThrowError:$ThrowError } } hub diff --name-only | ForEach-Object { $manifest = $_ if (!$manifest.EndsWith('.json')) { return } $app = ([System.IO.Path]::GetFileNameWithoutExtension($manifest)) $json = parse_json $manifest if (!$json.version) { error "Invalid manifest: $manifest ..." return } $version = $json.version $CommitMessage = $CommitMessageFormat -replace '',$app -replace '',$version if ($Push) { Write-Host "Creating update $app ($version) ..." -ForegroundColor DarkCyan execute "hub add $manifest" # detect if file was staged, because it's not when only LF or CRLF have changed $status = execute 'hub status --porcelain -uno' $status = $status | Where-Object { $_ -match "M\s{2}.*$app.json" } if ($status -and $status.StartsWith('M ') -and $status.EndsWith("$app.json")) { execute "hub commit -m '$commitMessage'" } else { Write-Host "Skipping $app because only LF/CRLF changes were detected ..." -ForegroundColor Yellow } } else { pull_requests $json $app $Upstream $manifest $CommitMessage } } if ($Push) { Write-Host 'Pushing updates ...' -ForegroundColor DarkCyan execute "hub push origin $OriginBranch" } else { Write-Host "Returning to $OriginBranch branch and removing unstaged files ..." -ForegroundColor DarkCyan execute "hub checkout -f $OriginBranch" } execute 'hub reset --hard' ================================================ FILE: bin/checkhashes.ps1 ================================================ <# .SYNOPSIS Check if ALL urls inside manifest have correct hashes. .PARAMETER App Manifest to be checked. Wildcard is supported. .PARAMETER Dir Where to search for manifest(s). .PARAMETER Update When there are mismatched hashes, manifest will be updated. .PARAMETER ForceUpdate Manifest will be updated all the time. Not only when there are mismatched hashes. .PARAMETER SkipCorrect Manifests without mismatch will not be shown. .PARAMETER UseCache Downloaded files will not be deleted after script finish. Should not be used, because check should be used for downloading actual version of file (as normal user, not finding in some document from vendors, which could be damaged / wrong (Example: Slack@3.3.1 ScoopInstaller/Extras#1192)), not some previously downloaded. .EXAMPLE PS BUCKETROOT> .\bin\checkhashes.ps1 Check all manifests for hash mismatch. .EXAMPLE PS BUCKETROOT> .\bin\checkhashes.ps1 MANIFEST -Update Check MANIFEST and Update if there are some wrong hashes. #> param( [String] $App = '*', [Parameter(Mandatory = $true)] [ValidateScript( { if (!(Test-Path $_ -Type Container)) { throw "$_ is not a directory!" } else { $true } })] [String] $Dir, [Switch] $Update, [Switch] $ForceUpdate, [Switch] $SkipCorrect, [Alias('k')] [Switch] $UseCache ) . "$PSScriptRoot\..\lib\core.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" . "$PSScriptRoot\..\lib\buckets.ps1" . "$PSScriptRoot\..\lib\autoupdate.ps1" . "$PSScriptRoot\..\lib\json.ps1" . "$PSScriptRoot\..\lib\versions.ps1" . "$PSScriptRoot\..\lib\download.ps1" $Dir = Convert-Path $Dir if ($ForceUpdate) { $Update = $true } # Cleanup if (!$UseCache) { Remove-Item "$cachedir\*HASH_CHECK*" -Force } function err ([String] $name, [String[]] $message) { Write-Host "$name`: " -ForegroundColor Red -NoNewline Write-Host ($message -join "`r`n") -ForegroundColor Red } $MANIFESTS = @() foreach ($single in Get-ChildItem $Dir -Filter "$App.json" -Recurse) { $name = $single.BaseName $file = $single.FullName $manifest = parse_json $file # Skip nighly manifests, since their hash validation is skipped if ($manifest.version -eq 'nightly') { continue } $urls = @() $hashes = @() if ($manifest.url) { $manifest.url | ForEach-Object { $urls += $_ } $manifest.hash | ForEach-Object { $hashes += $_ } } elseif ($manifest.architecture) { # First handle 64bit script:url $manifest '64bit' | ForEach-Object { $urls += $_ } hash $manifest '64bit' | ForEach-Object { $hashes += $_ } script:url $manifest '32bit' | ForEach-Object { $urls += $_ } hash $manifest '32bit' | ForEach-Object { $hashes += $_ } script:url $manifest 'arm64' | ForEach-Object { $urls += $_ } hash $manifest 'arm64' | ForEach-Object { $hashes += $_ } } else { err $name 'Manifest does not contain URL property.' continue } # Number of URLS and Hashes is different if ($urls.Length -ne $hashes.Length) { err $name 'URLS and hashes count mismatch.' continue } $MANIFESTS += @{ app = $name file = $file manifest = $manifest urls = $urls hashes = $hashes } } # clear any existing events Get-Event | ForEach-Object { Remove-Event $_.SourceIdentifier } foreach ($current in $MANIFESTS) { $count = 0 # Array of indexes mismatched hashes. $mismatched = @() # Array of computed hashes $actuals = @() $current.urls | ForEach-Object { $algorithm, $expected = get_hash $current.hashes[$count] if ($UseCache) { $version = $current.manifest.version } else { $version = 'HASH_CHECK' } Invoke-CachedDownload $current.app $version $_ $null $null -use_cache:$UseCache $to_check = cache_path $current.app $version $_ $actual_hash = (Get-FileHash -Path $to_check -Algorithm $algorithm).Hash.ToLower() # Append type of algorithm to both expected and actual if it's not sha256 if ($algorithm -ne 'sha256') { $actual_hash = "$algorithm`:$actual_hash" $expected = "$algorithm`:$expected" } $actuals += $actual_hash if ($actual_hash -ne $expected) { $mismatched += $count } $count++ } if ($mismatched.Length -eq 0 ) { if (!$SkipCorrect) { Write-Host "$($current.app): " -NoNewline Write-Host 'OK' -ForegroundColor Green } } else { Write-Host "$($current.app): " -NoNewline Write-Host 'Mismatch found ' -ForegroundColor Red $mismatched | ForEach-Object { $file = cache_path $current.app $version $current.urls[$_] Write-Host "`tURL:`t`t$($current.urls[$_])" if (Test-Path $file) { Write-Host "`tFirst bytes:`t$((get_magic_bytes_pretty $file ' ').ToUpper())" } Write-Host "`tExpected:`t$($current.hashes[$_])" -ForegroundColor Green Write-Host "`tActual:`t`t$($actuals[$_])" -ForegroundColor Red } } if ($Update) { if ($current.manifest.url -and $current.manifest.hash) { $current.manifest.hash = $actuals } else { $platforms = ($current.manifest.architecture | Get-Member -MemberType NoteProperty).Name # Defaults to zero, don't know, which architecture is available $64bit_count = 0 $32bit_count = 0 $arm64_count = 0 # 64bit is get, donwloaded and added first if ($platforms.Contains('64bit')) { $64bit_count = $current.manifest.architecture.'64bit'.hash.Count $current.manifest.architecture.'64bit'.hash = $actuals[0..($64bit_count - 1)] } if ($platforms.Contains('32bit')) { $32bit_count = $current.manifest.architecture.'32bit'.hash.Count $current.manifest.architecture.'32bit'.hash = $actuals[($64bit_count)..($64bit_count + $32bit_count - 1)] } if ($platforms.Contains('arm64')) { $arm64_count = $current.manifest.architecture.'arm64'.hash.Count $current.manifest.architecture.'arm64'.hash = $actuals[($64bit_count + $32bit_count)..($64bit_count + $32bit_count + $arm64_count - 1)] } } Write-Host "Writing updated $($current.app) manifest" -ForegroundColor DarkGreen $current.manifest = $current.manifest | ConvertToPrettyJson $path = Convert-Path $current.file [System.IO.File]::WriteAllLines($path, $current.manifest) } } ================================================ FILE: bin/checkurls.ps1 ================================================ <# .SYNOPSIS List manifests which do not have valid URLs. .PARAMETER App Manifest name to search. Placeholder is supported. .PARAMETER Dir Where to search for manifest(s). .PARAMETER Timeout How long (seconds) the request can be pending before it times out. .PARAMETER SkipValid Manifests will all valid URLs will not be shown. #> param( [String] $App = '*', [Parameter(Mandatory = $true)] [ValidateScript( { if (!(Test-Path $_ -Type Container)) { throw "$_ is not a directory!" } else { $true } })] [String] $Dir, [Int] $Timeout = 5, [Switch] $SkipValid ) . "$PSScriptRoot\..\lib\core.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" . "$PSScriptRoot\..\lib\download.ps1" $Dir = Convert-Path $Dir $Queue = @() Get-ChildItem $Dir -Filter "$App.json" -Recurse | ForEach-Object { $manifest = parse_json $_.FullName $Queue += , @($_.BaseName, $manifest) } Write-Host '[' -NoNewLine Write-Host 'U' -NoNewLine -ForegroundColor Cyan Write-Host ']RLs' Write-Host ' | [' -NoNewLine Write-Host 'O' -NoNewLine -ForegroundColor Green Write-Host ']kay' Write-Host ' | | [' -NoNewLine Write-Host 'F' -NoNewLine -ForegroundColor Red Write-Host ']ailed' Write-Host ' | | |' function test_dl([String] $url, $cookies) { # Trim renaming suffix, prevent getting 40x response $url = ($url -split '#/')[0] $wreq = [Net.WebRequest]::Create($url) $wreq.Timeout = $Timeout * 1000 if ($wreq -is [Net.HttpWebRequest]) { $wreq.UserAgent = Get-UserAgent $wreq.Referer = strip_filename $url if ($cookies) { $wreq.Headers.Add('Cookie', (cookie_header $cookies)) } } get_config PRIVATE_HOSTS | Where-Object { $_ -ne $null -and $url -match $_.match } | ForEach-Object { (ConvertFrom-StringData -StringData $_.Headers).GetEnumerator() | ForEach-Object { $wreq.Headers[$_.Key] = $_.Value } } $wres = $null try { $wres = $wreq.GetResponse() return $url, $wres.StatusCode, $null } catch { $e = $_.Exception if ($e.InnerException) { $e = $e.InnerException } return $url, 'Error', $e.Message } finally { if ($null -ne $wres -and $wres -isnot [Net.FtpWebResponse]) { $wres.Close() } } } foreach ($man in $Queue) { $name, $manifest = $man $urls = @() $ok = 0 $failed = 0 $errors = @() if ($manifest.url) { $manifest.url | ForEach-Object { $urls += $_ } } else { script:url $manifest '64bit' | ForEach-Object { $urls += $_ } script:url $manifest '32bit' | ForEach-Object { $urls += $_ } script:url $manifest 'arm64' | ForEach-Object { $urls += $_ } } $urls | ForEach-Object { $url, $status, $msg = test_dl $_ $manifest.cookie if ($msg) { $errors += "$msg ($url)" } if ($status -eq 'OK' -or $status -eq 'OpeningData') { $ok += 1 } else { $failed += 1 } } if (($ok -eq $urls.Length) -and $SkipValid) { continue } # URLS Write-Host '[' -NoNewLine Write-Host $urls.Length -NoNewLine -ForegroundColor Cyan Write-Host ']' -NoNewLine # Okay Write-Host '[' -NoNewLine if ($ok -eq $urls.Length) { Write-Host $ok -NoNewLine -ForegroundColor Green } elseif ($ok -eq 0) { Write-Host $ok -NoNewLine -ForegroundColor Red } else { Write-Host $ok -NoNewLine -ForegroundColor Yellow } Write-Host ']' -NoNewLine # Failed Write-Host '[' -NoNewLine if ($failed -eq 0) { Write-Host $failed -NoNewLine -ForegroundColor Green } else { Write-Host $failed -NoNewLine -ForegroundColor Red } Write-Host '] ' -NoNewLine Write-Host $name $errors | ForEach-Object { Write-Host " > $_" -ForegroundColor DarkRed } } ================================================ FILE: bin/checkver.ps1 ================================================ <# .SYNOPSIS Check manifest for a newer version. .DESCRIPTION Checks websites for newer versions using an (optional) regular expression defined in the manifest. .PARAMETER App Manifest name to search. Placeholders are supported. .PARAMETER Dir Where to search for manifest(s). .PARAMETER Update Update given manifest .PARAMETER ForceUpdate Update given manifest(s) even when there is no new version. Useful for hash updates. .PARAMETER SkipUpdated Updated manifests will not be shown. .PARAMETER Version Update manifest to specific version. .PARAMETER ThrowError Throw error as exception instead of just printing it. .EXAMPLE PS BUCKETROOT > .\bin\checkver.ps1 Check all manifest inside default directory. .EXAMPLE PS BUCKETROOT > .\bin\checkver.ps1 -SkipUpdated Check all manifest inside default directory (list only outdated manifests). .EXAMPLE PS BUCKETROOT > .\bin\checkver.ps1 -Update Check all manifests and update All outdated manifests. .EXAMPLE PS BUCKETROOT > .\bin\checkver.ps1 APP Check manifest APP.json inside default directory. .EXAMPLE PS BUCKETROOT > .\bin\checkver.ps1 APP -Update Check manifest APP.json and update, if there is newer version. .EXAMPLE PS BUCKETROOT > .\bin\checkver.ps1 APP -ForceUpdate Check manifest APP.json and update, even if there is no new version. .EXAMPLE PS BUCKETROOT > .\bin\checkver.ps1 APP -Update -Version VER Check manifest APP.json and update, using version VER .EXAMPLE PS BUCKETROOT > .\bin\checkver.ps1 APP DIR Check manifest APP.json inside ./DIR directory. .EXAMPLE PS BUCKETROOT > .\bin\checkver.ps1 -Dir DIR Check all manifests inside ./DIR directory. .EXAMPLE PS BUCKETROOT > .\bin\checkver.ps1 APP DIR -Update Check manifest APP.json inside ./DIR directory and update if there is newer version. #> param( [String] $App = '*', [ValidateScript( { if (!(Test-Path $_ -Type Container)) { throw "$_ is not a directory!" } else { $true } })] [String] $Dir, [Switch] $Update, [Switch] $ForceUpdate, [Switch] $SkipUpdated, [String] $Version = '', [Switch] $ThrowError ) . "$PSScriptRoot\..\lib\core.ps1" . "$PSScriptRoot\..\lib\autoupdate.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" . "$PSScriptRoot\..\lib\buckets.ps1" . "$PSScriptRoot\..\lib\json.ps1" . "$PSScriptRoot\..\lib\versions.ps1" . "$PSScriptRoot\..\lib\download.ps1" if ($App -ne '*' -and (Test-Path $App -PathType Leaf)) { $Dir = Split-Path $App $files = Get-ChildItem $Dir -Filter (Split-Path $App -Leaf) } elseif ($Dir) { $Dir = Convert-Path $Dir $files = Get-ChildItem $Dir -Filter "$App.json" -Recurse } else { throw "'-Dir' parameter required if '-App' is not a filepath!" } $GitHubToken = Get-GitHubToken # don't use $Version with $App = '*' if ($App -eq '*' -and $Version -ne '') { throw "Don't use '-Version' with '-App *'!" } # get apps to check $Queue = @() $json = '' $files | ForEach-Object { $file = $_.FullName $json = parse_json $file if ($json.checkver) { $Queue += , @($_.BaseName, $json, $file) } } # clear any existing events Get-Event | Remove-Event Get-EventSubscriber | Unregister-Event # start all downloads $Queue | ForEach-Object { $name, $json, $file = $_ $substitutions = Get-VersionSubstitution $json.version # 'autoupdate.ps1' $wc = New-Object Net.Webclient if ($json.checkver.useragent) { $wc.Headers.Add('User-Agent', (substitute $json.checkver.useragent $substitutions)) } else { $wc.Headers.Add('User-Agent', (Get-UserAgent)) } Register-ObjectEvent $wc downloadDataCompleted -ErrorAction Stop | Out-Null # Not Specified if ($json.checkver.url) { $url = $json.checkver.url } else { $url = $json.homepage } if ($json.checkver.re) { $regex = $json.checkver.re } elseif ($json.checkver.regex) { $regex = $json.checkver.regex } else { $regex = '' } $jsonpath = '' $xpath = '' $replace = '' $useGithubAPI = $false # GitHub if ($regex) { $githubRegex = $regex } else { $githubRegex = '/releases/tag/(?:v|V)?([\d.]+)' } if ($json.checkver -eq 'github') { if (!$json.homepage.StartsWith('https://github.com/')) { error "$name checkver expects the homepage to be a github repository" } $url = $json.homepage.TrimEnd('/') + '/releases/latest' $regex = $githubRegex $useGithubAPI = $true } if ($json.checkver.github) { $url = $json.checkver.github.TrimEnd('/') + '/releases/latest' $regex = $githubRegex if ($json.checkver.PSObject.Properties.Count -eq 1) { $useGithubAPI = $true } } # SourceForge if ($regex) { $sourceforgeRegex = $regex } else { $sourceforgeRegex = '(?!\.)([\d.]+)(?<=\d)' } if ($json.checkver -eq 'sourceforge') { if ($json.homepage -match '//(sourceforge|sf)\.net/projects/(?[^/]+)(/files/(?[^/]+))?|//(?[^.]+)\.(sourceforge\.(net|io)|sf\.net)') { $project = $Matches['project'] $path = $Matches['path'] } else { $project = strip_ext $name } $url = "https://sourceforge.net/projects/$project/rss" if ($path) { $url = $url + '?path=/' + $path.TrimStart('/') } $regex = "CDATA\[/$path/.*?$sourceforgeRegex.*?\]".Replace('//', '/') } if ($json.checkver.sourceforge) { if ($json.checkver.sourceforge -is [System.String] -and $json.checkver.sourceforge -match '(?[\w-]*)(/(?.*))?') { $project = $Matches['project'] $path = $Matches['path'] } else { $project = $json.checkver.sourceforge.project $path = $json.checkver.sourceforge.path } $url = "https://sourceforge.net/projects/$project/rss" if ($path) { $url = $url + '?path=/' + $path.TrimStart('/') } $regex = "CDATA\[/$path/.*?$sourceforgeRegex.*?\]".Replace('//', '/') } if ($json.checkver.jp) { $jsonpath = $json.checkver.jp } if ($json.checkver.jsonpath) { $jsonpath = $json.checkver.jsonpath } if ($json.checkver.xpath) { $xpath = $json.checkver.xpath } if ($json.checkver.replace -is [System.String]) { # If `checkver` is [System.String], it has a method called `Replace` $replace = $json.checkver.replace } if (!$jsonpath -and !$regex -and !$xpath) { $regex = $json.checkver } $reverse = $json.checkver.reverse -and $json.checkver.reverse -eq 'true' if ($url -like '*api.github.com/*') { $useGithubAPI = $true } if ($useGithubAPI -and ($null -ne $GitHubToken)) { $url = $url -replace '//(www\.)?github.com/', '//api.github.com/repos/' $wc.Headers.Add('Authorization', "token $GitHubToken") } $url = substitute $url $substitutions $state = New-Object psobject @{ app = $name file = $file url = $url regex = $regex json = $json jsonpath = $jsonpath xpath = $xpath reverse = $reverse replace = $replace } get_config PRIVATE_HOSTS | Where-Object { $_ -ne $null -and $url -match $_.match } | ForEach-Object { (ConvertFrom-StringData -StringData $_.Headers).GetEnumerator() | ForEach-Object { $wc.Headers[$_.Key] = $_.Value } } $wc.Headers.Add('Referer', (strip_filename $url)) $wc.DownloadDataAsync($url, $state) } function next($er) { Write-Host "$App`: " -NoNewline Write-Host $er -ForegroundColor DarkRed } # wait for all to complete $in_progress = $Queue.length while ($in_progress -gt 0) { $ev = Wait-Event Remove-Event $ev.SourceIdentifier $in_progress-- $state = $ev.SourceEventArgs.UserState $result = $ev.SourceEventArgs.Result $app = $state.app $file = $state.file $json = $state.json $url = $state.url $regexp = $state.regex $jsonpath = $state.jsonpath $xpath = $state.xpath $script = $json.checkver.script $reverse = $state.reverse $replace = $state.replace $expected_ver = $json.version $ver = $Version if (!$ver) { if (!$regexp -and $replace) { next "'replace' requires 're' or 'regex'" continue } $err = $ev.SourceEventArgs.Error if ($err) { next "$($err.message)`r`nURL $url is not valid" continue } if ($url) { $ms = New-Object System.IO.MemoryStream $ms.Write($result, 0, $result.Length) $ms.Seek(0, 0) | Out-Null if ($result[0] -eq 0x1F -and $result[1] -eq 0x8B) { $ms = New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Decompress) } $page = (New-Object System.IO.StreamReader($ms, (Get-Encoding $wc))).ReadToEnd() } $source = $url if ($script) { $page = Invoke-Command ([scriptblock]::Create($script -join "`r`n")) $source = 'the output of script' } if ($jsonpath) { # Return only a single value if regex is absent $noregex = [String]::IsNullOrEmpty($regexp) # If reverse is ON and regex is ON, # Then reverse would have no effect because regex handles reverse # on its own # So in this case we have to disable reverse $ver = json_path $page $jsonpath $null ($reverse -and $noregex) $noregex if (!$ver) { $ver = json_path_legacy $page $jsonpath } if (!$ver) { next "couldn't find '$jsonpath' in $source" continue } } if ($xpath) { $xml = [xml]$page # Find all `significant namespace declarations` from the XML file $nsList = $xml.SelectNodes("//namespace::*[not(. = ../../namespace::*)]") # Then add them into the NamespaceManager $nsmgr = New-Object System.Xml.XmlNamespaceManager($xml.NameTable) $nsList | ForEach-Object { if ($_.LocalName -eq 'xmlns') { $nsmgr.AddNamespace('ns', $_.Value) $xpath = $xpath -replace '/([^:/]+)((?=/)|(?=$))', '/ns:$1' } else { $nsmgr.AddNamespace($_.LocalName, $_.Value) } } # Getting version from XML, using XPath $ver = $xml.SelectSingleNode($xpath, $nsmgr).'#text' if (!$ver) { next "couldn't find '$($xpath -replace 'ns:', '')' in $source" continue } } if ($jsonpath -and $regexp) { $page = $ver $ver = '' } if ($xpath -and $regexp) { $page = $ver $ver = '' } if ($regexp) { $re = New-Object System.Text.RegularExpressions.Regex($regexp) if ($reverse) { $match = $re.Matches($page) | Select-Object -Last 1 } else { $match = $re.Matches($page) | Select-Object -First 1 } if ($match -and $match.Success) { $matchesHashtable = @{} $re.GetGroupNames() | ForEach-Object { $matchesHashtable.Add($_, $match.Groups[$_].Value) } $ver = $matchesHashtable['1'] if ($replace) { $ver = $re.Replace($match.Value, $replace) } if (!$ver) { $ver = $matchesHashtable['version'] } } else { next "couldn't match '$regexp' in $source" continue } } if (!$ver) { next "couldn't find new version in $source" continue } } # Skip actual only if versions are same and there is no -f if (($ver -eq $expected_ver) -and !$ForceUpdate -and $SkipUpdated) { continue } Write-Host "$app`: " -NoNewline # version hasn't changed (step over if forced update) if ($ver -eq $expected_ver -and !$ForceUpdate) { Write-Host $ver -ForegroundColor DarkGreen continue } Write-Host $ver -ForegroundColor DarkRed -NoNewline Write-Host " (scoop version is $expected_ver)" -NoNewline $update_available = (Compare-Version -ReferenceVersion $ver -DifferenceVersion $expected_ver) -ne 0 if ($json.autoupdate -and $update_available) { Write-Host ' autoupdate available' -ForegroundColor Cyan } else { Write-Host '' } # forcing an update implies updating, right? if ($ForceUpdate) { $Update = $true } if ($Update -and $json.autoupdate) { if ($ForceUpdate) { Write-Host 'Forcing autoupdate!' -ForegroundColor DarkMagenta } try { Invoke-AutoUpdate $app $file $json $ver $matchesHashtable # 'autoupdate.ps1' } catch { if ($ThrowError) { throw $_ } else { error $_.Exception.Message } } } } ================================================ FILE: bin/describe.ps1 ================================================ <# .SYNOPSIS Search for application description on homepage. .PARAMETER App Manifest name to search. Placeholders are supported. .PARAMETER Dir Where to search for manifest(s). #> param( [String] $App = '*', [Parameter(Mandatory = $true)] [ValidateScript( { if (!(Test-Path $_ -Type Container)) { throw "$_ is not a directory!" } else { $true } })] [String] $Dir ) . "$PSScriptRoot\..\lib\core.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" . "$PSScriptRoot\..\lib\description.ps1" . "$PSScriptRoot\..\lib\download.ps1" $Dir = Convert-Path $Dir $Queue = @() Get-ChildItem $Dir -Filter "$App.json" -Recurse | ForEach-Object { $manifest = parse_json $_.FullName $Queue += , @($_.BaseName, $manifest) } $Queue | ForEach-Object { $name, $manifest = $_ Write-Host "$name`: " -NoNewline if (!$manifest.homepage) { Write-Host "`nNo homepage set." -ForegroundColor Red return } # get description from homepage try { $wc = New-Object Net.Webclient $wc.Headers.Add('User-Agent', (Get-UserAgent)) $homepage = $wc.DownloadData($manifest.homepage) $home_html = (Get-Encoding($wc)).GetString($homepage) } catch { Write-Host "`n$($_.Exception.Message)" -ForegroundColor Red return } $description, $descr_method = find_description $manifest.homepage $home_html if (!$description) { Write-Host "`nDescription not found ($($manifest.homepage))" -ForegroundColor Red return } $description = clean_description $description Write-Host "(found by $descr_method)" Write-Host " ""$description""" -ForegroundColor Green } ================================================ FILE: bin/formatjson.ps1 ================================================ <# .SYNOPSIS Format manifest. .PARAMETER App Manifest to format. Wildcards are supported. .PARAMETER Dir Where to search for manifest(s). .EXAMPLE PS BUCKETROOT> .\bin\formatjson.ps1 Format all manifests inside bucket directory. .EXAMPLE PS BUCKETROOT> .\bin\formatjson.ps1 7zip Format manifest '7zip' inside bucket directory. #> param( [String] $App = '*', [Parameter(Mandatory = $true)] [ValidateScript( { if (!(Test-Path $_ -Type Container)) { throw "$_ is not a directory!" } else { $true } })] [String] $Dir ) . "$PSScriptRoot\..\lib\core.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" . "$PSScriptRoot\..\lib\json.ps1" $Dir = Convert-Path $Dir Get-ChildItem $Dir -Filter "$App.json" -Recurse | ForEach-Object { $file = $_.FullName # beautify $json = parse_json $file | ConvertToPrettyJson # convert to 4 spaces $json = $json -replace "`t", ' ' [System.IO.File]::WriteAllLines($file, $json) } ================================================ FILE: bin/install.ps1 ================================================ #Requires -Version 5 Invoke-RestMethod https://get.scoop.sh | Invoke-Expression ================================================ FILE: bin/missing-checkver.ps1 ================================================ <# .SYNOPSIS Check if manifest contains checkver and autoupdate property. .PARAMETER App Manifest name. Wirldcard is supported. .PARAMETER Dir Location of manifests. .PARAMETER SkipSupported Manifests with checkver and autoupdate will not be presented. #> param( [String] $App = '*', [Parameter(Mandatory = $true)] [ValidateScript( { if (!(Test-Path $_ -Type Container)) { throw "$_ is not a directory!" } else { $true } })] [String] $Dir, [Switch] $SkipSupported ) . "$PSScriptRoot\..\lib\core.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" $Dir = Convert-Path $Dir Write-Host '[' -NoNewLine Write-Host 'C' -NoNewLine -ForegroundColor Green Write-Host ']heckver' Write-Host ' | [' -NoNewLine Write-Host 'A' -NoNewLine -ForegroundColor Cyan Write-Host ']utoupdate' Write-Host ' | |' Get-ChildItem $Dir -Filter "$App.json" -Recurse | ForEach-Object { $json = parse_json $_.FullName if ($SkipSupported -and $json.checkver -and $json.autoupdate) { return } Write-Host '[' -NoNewLine Write-Host $(if ($json.checkver) { 'C' } else { ' ' }) -NoNewLine -ForegroundColor Green Write-Host ']' -NoNewLine Write-Host '[' -NoNewLine Write-Host $(if ($json.autoupdate) { 'A' } else { ' ' }) -NoNewLine -ForegroundColor Cyan Write-Host '] ' -NoNewLine Write-Host $_.BaseName } ================================================ FILE: bin/refresh.ps1 ================================================ # for development, update the installed scripts to match local source . "$PSScriptRoot\..\lib\core.ps1" $src = "$PSScriptRoot\.." $dest = ensure (versiondir 'scoop' 'current') # make sure not running from the installed directory if("$src" -eq "$dest") { abort "$(strip_ext $myinvocation.mycommand.name) is for development only" } 'copying files...' $output = robocopy $src $dest /mir /njh /njs /nfl /ndl /xd .git tmp /xf .DS_Store last_updated $output | Where-Object { $_ -ne "" } Write-Output 'creating shim...' shim "$dest\bin\scoop.ps1" $false success 'scoop was refreshed!' ================================================ FILE: bin/scoop.ps1 ================================================ #Requires -Version 5 Set-StrictMode -Off . "$PSScriptRoot\..\lib\core.ps1" . "$PSScriptRoot\..\lib\buckets.ps1" . "$PSScriptRoot\..\lib\commands.ps1" . "$PSScriptRoot\..\lib\help.ps1" $subCommand = $Args[0] # for aliases where there's a local function, re-alias so the function takes precedence $aliases = Get-Alias | Where-Object { $_.Options -notmatch 'ReadOnly|AllScope' } | ForEach-Object { $_.Name } Get-ChildItem Function: | Where-Object -Property Name -In -Value $aliases | ForEach-Object { Set-Alias -Name $_.Name -Value Local:$($_.Name) -Scope Script } switch ($subCommand) { ({ $subCommand -in @($null, '-h', '--help', '/?') }) { exec 'help' } ({ $subCommand -in @('-v', '--version') }) { Write-Host 'Current Scoop version:' if (Test-GitAvailable -and (Test-Path "$PSScriptRoot\..\.git") -and (get_config SCOOP_BRANCH 'master') -ne 'master') { Invoke-Git -Path "$PSScriptRoot\.." -ArgumentList @('log', 'HEAD', '-1', '--oneline') } else { $version = Select-String -Pattern '^## \[(v[\d.]+)\].*?([\d-]+)$' -Path "$PSScriptRoot\..\CHANGELOG.md" Write-Host $version.Matches.Groups[1].Value -ForegroundColor Cyan -NoNewline Write-Host " - Released at $($version.Matches.Groups[2].Value)" } Write-Host '' Get-LocalBucket | ForEach-Object { $bucketLoc = Find-BucketDirectory $_ -Root if (Test-GitAvailable -and (Test-Path "$bucketLoc\.git")) { Write-Host "'$_' bucket:" Invoke-Git -Path $bucketLoc -ArgumentList @('log', 'HEAD', '-1', '--oneline') Write-Host '' } } } ({ $subCommand -in (commands) }) { [string[]]$arguments = $Args | Select-Object -Skip 1 if ($null -ne $arguments -and $arguments[0] -in @('-h', '--help', '/?')) { exec 'help' @($subCommand) } else { exec $subCommand $arguments } } default { warn "scoop: '$subCommand' isn't a scoop command. See 'scoop help'." exit 1 } } ================================================ FILE: bin/test.ps1 ================================================ . "$PSScriptRoot\..\test\bin\test.ps1" ================================================ FILE: bin/uninstall.ps1 ================================================ <# .SYNOPSIS Uninstall ALL scoop applications and scoop itself. .PARAMETER global Global applications will be uninstalled. .PARAMETER purge Persisted data will be deleted. #> param( [bool] $global, [bool] $purge ) . "$PSScriptRoot\..\lib\core.ps1" . "$PSScriptRoot\..\lib\system.ps1" . "$PSScriptRoot\..\lib\install.ps1" . "$PSScriptRoot\..\lib\shortcuts.ps1" . "$PSScriptRoot\..\lib\versions.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" if ($global -and !(is_admin)) { error 'You need admin rights to uninstall globally.' exit 1 } if ($purge) { warn 'This will uninstall Scoop, all the programs that have been installed with Scoop and all persisted data!' } else { warn 'This will uninstall Scoop and all the programs that have been installed with Scoop!' } $yn = Read-Host 'Are you sure? (yN)' if ($yn -notlike 'y*') { exit } $errors = $false # Uninstall given app function do_uninstall($app, $global) { $version = Select-CurrentVersion -AppName $app -Global:$global $dir = versiondir $app $version $global $manifest = installed_manifest $app $version $global $install = install_info $app $version $global $architecture = $install.architecture Write-Output "Uninstalling '$app'" Invoke-Installer -Path $dir -Manifest $manifest -ProcessorArchitecture $architecture -Uninstall rm_shims $app $manifest $global $architecture # If a junction was used during install, that will have been used # as the reference directory. Othewise it will just be the version # directory. $refdir = unlink_current (appdir $app $global) env_rm_path $manifest $refdir $global $architecture env_rm $manifest $global $architecture $appdir = appdir $app $global try { Remove-Item $appdir -Recurse -Force -ErrorAction Stop } catch { $errors = $true warn "Couldn't remove $(friendly_path $appdir): $_.Exception" } } function rm_dir($dir) { try { Remove-Item $dir -Recurse -Force -ErrorAction Stop } catch { abort "Couldn't remove $(friendly_path $dir): $_" } } # Remove all folders (except persist) inside given scoop directory. function keep_onlypersist($directory) { Get-ChildItem $directory -Exclude 'persist' | ForEach-Object { rm_dir $_ } } # Run uninstallation for each app if necessary, continuing if there's # a problem deleting a directory (which is quite likely) if ($global) { installed_apps $true | ForEach-Object { # global apps do_uninstall $_ $true } } installed_apps $false | ForEach-Object { # local apps do_uninstall $_ $false } if ($errors) { abort 'Not all apps could be deleted. Try again or restart.' } if ($purge) { rm_dir $scoopdir if ($global) { rm_dir $globaldir } } else { keep_onlypersist $scoopdir if ($global) { keep_onlypersist $globaldir } } Remove-Path -Path (shimdir $global) -Global:$global if (get_config USE_ISOLATED_PATH) { Remove-Path -Path ('%' + $scoopPathEnvVar + '%') -Global:$global } success 'Scoop has been uninstalled.' ================================================ FILE: buckets.json ================================================ { "main": "https://github.com/ScoopInstaller/Main", "extras": "https://github.com/ScoopInstaller/Extras", "versions": "https://github.com/ScoopInstaller/Versions", "nirsoft": "https://github.com/ScoopInstaller/Nirsoft", "sysinternals": "https://github.com/niheaven/scoop-sysinternals", "php": "https://github.com/ScoopInstaller/PHP", "nerd-fonts": "https://github.com/matthewjberger/scoop-nerd-fonts", "nonportable": "https://github.com/ScoopInstaller/Nonportable", "java": "https://github.com/ScoopInstaller/Java", "games": "https://github.com/Calinou/scoop-games" } ================================================ FILE: lib/autoupdate.ps1 ================================================ # Must included with 'json.ps1' function format_hash([String] $hash) { $hash = $hash.toLower() if ($hash -like 'sha256:*') { $hash = $hash.Substring(7) # Remove prefix 'sha256:' } switch ($hash.Length) { 32 { $hash = "md5:$hash" } # md5 40 { $hash = "sha1:$hash" } # sha1 64 { $hash = $hash } # sha256 128 { $hash = "sha512:$hash" } # sha512 default { $hash = $null } } return $hash } function find_hash_in_rdf([String] $url, [String] $basename) { $xml = $null try { # Download and parse RDF XML file $wc = New-Object Net.Webclient $wc.Headers.Add('Referer', (strip_filename $url)) $wc.Headers.Add('User-Agent', (Get-UserAgent)) $data = $wc.DownloadData($url) [xml]$xml = (Get-Encoding($wc)).GetString($data) } catch [System.Net.WebException] { Write-Host $_ -ForegroundColor DarkRed Write-Host "URL $url is not valid" -ForegroundColor DarkRed return $null } # Find file content $digest = $xml.RDF.Content | Where-Object { [String]$_.about -eq $basename } return format_hash $digest.sha256 } function find_hash_in_textfile([String] $url, [Hashtable] $substitutions, [String] $regex) { $hashfile = $null $templates = @{ '$md5' = '([a-fA-F0-9]{32})' '$sha1' = '([a-fA-F0-9]{40})' '$sha256' = '([a-fA-F0-9]{64})' '$sha512' = '([a-fA-F0-9]{128})' '$checksum' = '([a-fA-F0-9]{32,128})' '$base64' = '([a-zA-Z0-9+\/=]{24,88})' } try { $wc = New-Object Net.Webclient $wc.Headers.Add('Referer', (strip_filename $url)) $wc.Headers.Add('User-Agent', (Get-UserAgent)) $data = $wc.DownloadData($url) $ms = New-Object System.IO.MemoryStream $ms.Write($data, 0, $data.Length) $ms.Seek(0, 0) | Out-Null if ($data[0] -eq 0x1F -and $data[1] -eq 0x8B) { $ms = New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Decompress) } $hashfile = (New-Object System.IO.StreamReader($ms, (Get-Encoding $wc))).ReadToEnd() } catch [system.net.webexception] { Write-Host $_ -ForegroundColor DarkRed Write-Host "URL $url is not valid" -ForegroundColor DarkRed return } if ($regex.Length -eq 0) { $regex = '^\s*([a-fA-F0-9]+)\s*$' } $regex = substitute $regex $templates $false $regex = substitute $regex $substitutions $true if ($hashfile -match $regex) { debug $regex $hash = $matches[1] -replace '\s', '' } # convert base64 encoded hash values if ($hash -match '^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{4})$') { $base64 = $matches[0] if (!($hash -match '^[a-fA-F0-9]+$') -and $hash.Length -notin @(32, 40, 64, 128)) { try { $hash = ([System.Convert]::FromBase64String($base64) | ForEach-Object { $_.ToString('x2') }) -join '' } catch { $hash = $hash } } } # find hash with filename in $hashfile if ($hash.Length -eq 0) { $filenameRegex = "([a-fA-F0-9]{32,128})[\x20\t]+.*`$basename(?:\s|$)|`$basename[\x20\t]+.*?([a-fA-F0-9]{32,128})" $filenameRegex = substitute $filenameRegex $substitutions $true if ($hashfile -match $filenameRegex) { debug $filenameRegex $hash = $matches[1] } $metalinkRegex = ']+>([a-fA-F0-9]{64})' if ($hashfile -match $metalinkRegex) { debug $metalinkRegex $hash = $matches[1] } } return format_hash $hash } function find_hash_in_json([String] $url, [Hashtable] $substitutions, [String] $jsonpath) { $json = $null try { $wc = New-Object Net.Webclient $wc.Headers.Add('Referer', (strip_filename $url)) $wc.Headers.Add('User-Agent', (Get-UserAgent)) $data = $wc.DownloadData($url) $ms = New-Object System.IO.MemoryStream $ms.Write($data, 0, $data.Length) $ms.Seek(0, 0) | Out-Null if ($data[0] -eq 0x1F -and $data[1] -eq 0x8B) { $ms = New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Decompress) } $json = (New-Object System.IO.StreamReader($ms, (Get-Encoding $wc))).ReadToEnd() } catch [System.Net.WebException] { Write-Host $_ -ForegroundColor DarkRed Write-Host "URL $url is not valid" -ForegroundColor DarkRed return } debug $jsonpath $hash = json_path $json $jsonpath $substitutions if (!$hash) { $hash = json_path_legacy $json $jsonpath $substitutions } return format_hash $hash } function find_hash_in_xml([String] $url, [Hashtable] $substitutions, [String] $xpath) { $xml = $null try { $wc = New-Object Net.Webclient $wc.Headers.Add('Referer', (strip_filename $url)) $wc.Headers.Add('User-Agent', (Get-UserAgent)) $data = $wc.DownloadData($url) $ms = New-Object System.IO.MemoryStream $ms.Write($data, 0, $data.Length) $ms.Seek(0, 0) | Out-Null if ($data[0] -eq 0x1F -and $data[1] -eq 0x8B) { $ms = New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Decompress) } $xml = [xml]((New-Object System.IO.StreamReader($ms, (Get-Encoding $wc))).ReadToEnd()) } catch [system.net.webexception] { Write-Host $_ -ForegroundColor DarkRed Write-Host "URL $url is not valid" -ForegroundColor DarkRed return } # Replace placeholders if ($substitutions) { $xpath = substitute $xpath $substitutions } # Find all `significant namespace declarations` from the XML file $nsList = $xml.SelectNodes('//namespace::*[not(. = ../../namespace::*)]') # Then add them into the NamespaceManager $nsmgr = New-Object System.Xml.XmlNamespaceManager($xml.NameTable) $nsList | ForEach-Object { $nsmgr.AddNamespace($_.LocalName, $_.Value) } debug $xpath debug $nsmgr # Getting hash from XML, using XPath $hash = $xml.SelectSingleNode($xpath, $nsmgr).'#text' return format_hash $hash } function find_hash_in_headers([String] $url) { $hash = $null try { $req = [System.Net.WebRequest]::Create($url) $req.Referer = (strip_filename $url) $req.AllowAutoRedirect = $false $req.UserAgent = (Get-UserAgent) $req.Timeout = 2000 $req.Method = 'HEAD' $res = $req.GetResponse() if (([int]$res.StatusCode -ge 300) -and ([int]$res.StatusCode -lt 400)) { if ($res.Headers['Digest'] -match 'SHA-256=([^,]+)' -or $res.Headers['Digest'] -match 'SHA=([^,]+)' -or $res.Headers['Digest'] -match 'MD5=([^,]+)') { $hash = ([System.Convert]::FromBase64String($matches[1]) | ForEach-Object { $_.ToString('x2') }) -join '' debug $hash } } $res.Close() } catch [System.Net.WebException] { Write-Host $_ -ForegroundColor DarkRed Write-Host "URL $url is not valid" -ForegroundColor DarkRed return } return format_hash $hash } function get_hash_for_app([String] $app, $config, [String] $version, [String] $url, [Hashtable] $substitutions) { $hash = $null $hashmode = $config.mode $basename = [System.Web.HttpUtility]::UrlDecode((url_remote_filename($url))) $substitutions = $substitutions.Clone() $substitutions.Add('$url', (strip_fragment $url)) $substitutions.Add('$baseurl', (strip_filename (strip_fragment $url)).TrimEnd('/')) $substitutions.Add('$basename', $basename) $substitutions.Add('$urlNoExt', (strip_ext (strip_fragment $url))) $substitutions.Add('$basenameNoExt', (strip_ext $basename)) debug $substitutions $hashfile_url = substitute $config.url $substitutions debug $hashfile_url if ($hashfile_url) { Write-Host 'Searching hash for ' -ForegroundColor DarkYellow -NoNewline Write-Host $basename -ForegroundColor Green -NoNewline Write-Host ' in ' -ForegroundColor DarkYellow -NoNewline Write-Host $hashfile_url -ForegroundColor Green } if ($hashmode.Length -eq 0 -and $config.url.Length -ne 0) { $hashmode = 'extract' } $jsonpath = '' if ($config.jp) { $jsonpath = $config.jp $hashmode = 'json' } if ($config.jsonpath) { $jsonpath = $config.jsonpath $hashmode = 'json' } $regex = '' if ($config.find) { $regex = $config.find } if ($config.regex) { $regex = $config.regex } $xpath = '' if ($config.xpath) { $xpath = $config.xpath $hashmode = 'xpath' } if (!$hashfile_url -and $url -match '^(?:.*fosshub.com\/).*(?:\/|\?dwl=)(?.*)$') { $hashmode = 'fosshub' } if (!$hashfile_url -and $url -match '(?:downloads\.)?sourceforge.net\/projects?\/(?[^\/]+)\/(?:files\/)?(?.*)') { $hashmode = 'sourceforge' } if (!$hashfile_url -and $url -match 'https:\/\/github\.com\/(?[^\/]+)\/(?[^\/]+)\/releases\/download\/[^\/]+\/[^\/]+') { $hashmode = 'github' } switch ($hashmode) { 'extract' { $hash = find_hash_in_textfile $hashfile_url $substitutions $regex } 'json' { $hash = find_hash_in_json $hashfile_url $substitutions $jsonpath } 'xpath' { $hash = find_hash_in_xml $hashfile_url $substitutions $xpath } 'rdf' { $hash = find_hash_in_rdf $hashfile_url $basename } 'metalink' { $hash = find_hash_in_headers $url if (!$hash) { $hash = find_hash_in_textfile "$url.meta4" $substitutions } } 'fosshub' { $hash = find_hash_in_textfile $url $substitutions ($matches.filename + '.*?"sha256":"([a-fA-F0-9]{64})"') } 'sourceforge' { # change the URL because downloads.sourceforge.net doesn't have checksums $hashfile_url = (strip_filename (strip_fragment "https://sourceforge.net/projects/$($matches['project'])/files/$($matches['file'])")).TrimEnd('/') $hash = find_hash_in_textfile $hashfile_url $substitutions '"$basename":.*?"sha1":\s*"([a-fA-F0-9]{40})"' } 'github' { $hashfile_url = "https://api.github.com/repos/$($matches['owner'])/$($matches['repo'])/releases" $hash = find_hash_in_json $hashfile_url $substitutions ("$..assets[?(@.browser_download_url == '" + $url + "')].digest") } } if ($hash) { # got one! Write-Host 'Found: ' -ForegroundColor DarkYellow -NoNewline Write-Host $hash -ForegroundColor Green -NoNewline Write-Host ' using ' -ForegroundColor DarkYellow -NoNewline Write-Host "$((Get-Culture).TextInfo.ToTitleCase($hashmode)) Mode" -ForegroundColor Green return $hash } elseif ($hashfile_url) { Write-Host -f DarkYellow "Could not find hash in $hashfile_url" } Write-Host 'Downloading ' -ForegroundColor DarkYellow -NoNewline Write-Host $basename -ForegroundColor Green -NoNewline Write-Host ' to compute hashes!' -ForegroundColor DarkYellow try { Invoke-CachedDownload $app $version $url $null $null $true } catch [system.net.webexception] { Write-Host $_ -ForegroundColor DarkRed Write-Host "URL $url is not valid" -ForegroundColor DarkRed return $null } $file = cache_path $app $version $url $hash = (Get-FileHash -Path $file -Algorithm SHA256).Hash.ToLower() Write-Host 'Computed hash: ' -ForegroundColor DarkYellow -NoNewline Write-Host $hash -ForegroundColor Green return $hash } function Update-ManifestProperty { <# .SYNOPSIS Update propert(y|ies) in manifest .DESCRIPTION Update selected propert(y|ies) to given version in manifest. .PARAMETER Manifest Manifest to be updated .PARAMETER Property Selected propert(y|ies) to be updated .PARAMETER AppName Software name .PARAMETER Version Given software version .PARAMETER Substitutions Hashtable of internal substitutable variables .OUTPUTS System.Boolean Flag that indicate if there are any changed properties #> [CmdletBinding(SupportsShouldProcess = $true)] [OutputType([Boolean])] param ( [Parameter(Mandatory = $true, Position = 1)] [PSCustomObject] $Manifest, [Parameter(ValueFromPipeline = $true, Position = 2)] [String[]] $Property, [String] $AppName, [String] $Version, [Alias('Matches')] [HashTable] $Substitutions ) begin { $hasManifestChanged = $false } process { foreach ($currentProperty in $Property) { if ($currentProperty -eq 'hash') { # Update hash if ($Manifest.hash) { # Global $newURL = substitute $Manifest.autoupdate.url $Substitutions $newHash = HashHelper -AppName $AppName -Version $Version -HashExtraction $Manifest.autoupdate.hash -URL $newURL -Substitutions $Substitutions $Manifest.hash, $hasPropertyChanged = PropertyHelper -Property $Manifest.hash -Value $newHash $hasManifestChanged = $hasManifestChanged -or $hasPropertyChanged } else { # Arch-spec $Manifest.architecture | Get-Member -MemberType NoteProperty | ForEach-Object { $arch = $_.Name $newURL = substitute (arch_specific 'url' $Manifest.autoupdate $arch) $Substitutions $newHash = HashHelper -AppName $AppName -Version $Version -HashExtraction (arch_specific 'hash' $Manifest.autoupdate $arch) -URL $newURL -Substitutions $Substitutions $Manifest.architecture.$arch.hash, $hasPropertyChanged = PropertyHelper -Property $Manifest.architecture.$arch.hash -Value $newHash $hasManifestChanged = $hasManifestChanged -or $hasPropertyChanged } } } elseif ($Manifest.$currentProperty -and $Manifest.autoupdate.$currentProperty) { # Update other property (global) $autoupdateProperty = $Manifest.autoupdate.$currentProperty $newValue = substitute $autoupdateProperty $Substitutions if (($autoupdateProperty.GetType().Name -eq 'Object[]') -and ($autoupdateProperty.Length -eq 1)) { # Make sure it's an array $newValue = , $newValue } $Manifest.$currentProperty, $hasPropertyChanged = PropertyHelper -Property $Manifest.$currentProperty -Value $newValue $hasManifestChanged = $hasManifestChanged -or $hasPropertyChanged } elseif ($Manifest.architecture) { # Update other property (arch-spec) $Manifest.architecture | Get-Member -MemberType NoteProperty | ForEach-Object { $arch = $_.Name if ($Manifest.architecture.$arch.$currentProperty -and ($Manifest.autoupdate.architecture.$arch.$currentProperty -or $Manifest.autoupdate.$currentProperty)) { $autoupdateProperty = @(arch_specific $currentProperty $Manifest.autoupdate $arch) $newValue = substitute $autoupdateProperty $Substitutions if (($autoupdateProperty.GetType().Name -eq 'Object[]') -and ($autoupdateProperty.Length -eq 1)) { # Make sure it's an array $newValue = , $newValue } $Manifest.architecture.$arch.$currentProperty, $hasPropertyChanged = PropertyHelper -Property $Manifest.architecture.$arch.$currentProperty -Value $newValue $hasManifestChanged = $hasManifestChanged -or $hasPropertyChanged } } } } } end { if ($Version -ne '' -and $Manifest.version -ne $Version) { $Manifest.version = $Version $hasManifestChanged = $true } return $hasManifestChanged } } function Get-VersionSubstitution { param ( [String] $Version, [Hashtable] $CustomMatches ) $firstPart = $Version.Split('-') | Select-Object -First 1 $lastPart = $Version.Split('-') | Select-Object -Last 1 $versionVariables = @{ '$version' = $Version '$dotVersion' = ($Version -replace '[._-]', '.') '$underscoreVersion' = ($Version -replace '[._-]', '_') '$dashVersion' = ($Version -replace '[._-]', '-') '$cleanVersion' = ($Version -replace '[._-]', '') '$majorVersion' = $firstPart.Split('.') | Select-Object -First 1 '$minorVersion' = $firstPart.Split('.') | Select-Object -Skip 1 -First 1 '$patchVersion' = $firstPart.Split('.') | Select-Object -Skip 2 -First 1 '$buildVersion' = $firstPart.Split('.') | Select-Object -Skip 3 -First 1 '$preReleaseVersion' = $lastPart } if ($Version -match '(?\d+\.\d+(?:\.\d+)?)(?.*)') { $versionVariables.Add('$matchHead', $Matches['head']) $versionVariables.Add('$matchTail', $Matches['tail']) } if ($CustomMatches) { $CustomMatches.GetEnumerator() | ForEach-Object { if ($_.Name -ne '0') { $versionVariables.Add('$match' + (Get-Culture).TextInfo.ToTitleCase($_.Name), $_.Value) } } } return $versionVariables } function Invoke-AutoUpdate { param ( [String] $AppName, [String] $Path, [PSObject] $Manifest, [String] $Version, [Hashtable] $CustomMatches ) Write-Host "Autoupdating $AppName" -ForegroundColor DarkCyan $substitutions = Get-VersionSubstitution $Version $CustomMatches # update properties $updatedProperties = @(@($Manifest.autoupdate.PSObject.Properties.Name) -ne 'architecture') if ($Manifest.autoupdate.architecture) { $updatedProperties += $Manifest.autoupdate.architecture.PSObject.Properties | ForEach-Object { $_.Value.PSObject.Properties.Name } } if ($updatedProperties -contains 'url') { $updatedProperties += 'hash' } $updatedProperties = $updatedProperties | Select-Object -Unique debug [$updatedProperties] $hasChanged = Update-ManifestProperty -Manifest $Manifest -Property $updatedProperties -AppName $AppName -Version $Version -Substitutions $substitutions if ($hasChanged) { # write file Write-Host "Writing updated $AppName manifest" -ForegroundColor DarkGreen # Accept unusual Unicode characters # 'Set-Content -Encoding ASCII' don't works in PowerShell 5 # Wait for 'UTF8NoBOM' Encoding in PowerShell 7 # $Manifest | ConvertToPrettyJson | Set-Content -Path (Join-Path $Path "$AppName.json") -Encoding UTF8NoBOM [System.IO.File]::WriteAllLines($Path, (ConvertToPrettyJson $Manifest)) # notes $note = "`nUpdating note:" if ($Manifest.autoupdate.note) { $note += "`nno-arch: $($Manifest.autoupdate.note)" $hasNote = $true } if ($Manifest.autoupdate.architecture) { '64bit', '32bit', 'arm64' | ForEach-Object { if ($Manifest.autoupdate.architecture.$_.note) { $note += "`n$_-arch: $($Manifest.autoupdate.architecture.$_.note)" $hasNote = $true } } } if ($hasNote) { Write-Host $note -ForegroundColor DarkYellow } } else { # This if-else branch may not be in use. Write-Host "No updates for $AppName" -ForegroundColor DarkGray } } ## Helper Functions function PropertyHelper { <# .SYNOPSIS Helper of updating property .DESCRIPTION Update manifest property (String, Array or PSCustomObject). .PARAMETER Property Property to be updated .PARAMETER Value New property values Update line by line .OUTPUTS System.Object[] The first element is new property, the second element is change flag #> param ( [Object]$Property, [Object]$Value ) $hasChanged = $false if (@($Property).Length -lt @($Value).Length) { $Property = $Value $hasChanged = $true } else { switch ($Property.GetType().Name) { 'String' { $Value = $Value -as [String] if ($null -ne $Value) { $Property = $Value $hasChanged = $true } } 'Object[]' { $Value = @($Value) for ($i = 0; $i -lt $Value.Length; $i++) { $Property[$i], $hasItemChanged = PropertyHelper -Property $Property[$i] -Value $Value[$i] $hasChanged = $hasChanged -or $hasItemChanged } } 'PSCustomObject' { if ($Value -is [PSObject]) { foreach ($name in $Property.PSObject.Properties.Name) { if ($Value.$name) { $Property.$name, $hasItemChanged = PropertyHelper -Property $Property.$name -Value $Value.$name $hasChanged = $hasChanged -or $hasItemChanged } } } } } } return $Property, $hasChanged } function HashHelper { <# .SYNOPSIS Helper of getting file hash(es) .DESCRIPTION Extract or calculate file hash(es). If hash extraction templates are less then URLs, the last template will be reused for the rest URLs. .PARAMETER AppName Software name .PARAMETER Version Given software version .PARAMETER HashExtraction Hash extraction template(s) .PARAMETER URL New download URL(s), used to calculate hash locally (fallback) .PARAMETER Substitutions Hashtable of internal substitutable variables .OUTPUTS System.String Hash value (single URL) System.String[] Hash values (multi URLs) #> param ( [String] $AppName, [String] $Version, [PSObject[]] $HashExtraction, [String[]] $URL, [HashTable] $Substitutions ) $hash = @() for ($i = 0; $i -lt $URL.Length; $i++) { if ($null -eq $HashExtraction) { $currentHashExtraction = $null } else { $currentHashExtraction = $HashExtraction[$i], $HashExtraction[-1] | Select-Object -First 1 } $hash += get_hash_for_app $AppName $currentHashExtraction $Version $URL[$i] $Substitutions if ($null -eq $hash[$i]) { throw "Could not update $AppName, hash for $(url_remote_filename $URL[$i]) failed!" } } return $hash } ================================================ FILE: lib/buckets.ps1 ================================================ $bucketsdir = "$scoopdir\buckets" function Find-BucketDirectory { <# .DESCRIPTION Return full path for bucket with given name. Main bucket will be returned as default. .PARAMETER Name Name of bucket. .PARAMETER Root Root folder of bucket repository will be returned instead of 'bucket' subdirectory (if exists). #> param( [string] $Name = 'main', [switch] $Root ) # Handle info passing empty string as bucket ($install.bucket) if (($null -eq $Name) -or ($Name -eq '')) { $Name = 'main' } $bucket = "$bucketsdir\$Name" if ((Test-Path "$bucket\bucket") -and !$Root) { $bucket = "$bucket\bucket" } return $bucket } function bucketdir($name) { Show-DeprecatedWarning $MyInvocation 'Find-BucketDirectory' return Find-BucketDirectory $name } function known_bucket_repos { $json = "$PSScriptRoot\..\buckets.json" return Get-Content $json -Raw | ConvertFrom-Json -ErrorAction stop } function known_bucket_repo($name) { $buckets = known_bucket_repos $buckets.$name } function known_buckets { known_bucket_repos | ForEach-Object { $_.PSObject.Properties | Select-Object -Expand 'name' } } function apps_in_bucket($dir) { return (Get-ChildItem $dir -Filter '*.json' -Recurse).BaseName } function Get-LocalBucket { <# .SYNOPSIS List all local buckets. #> $bucketNames = [System.Collections.Generic.List[String]](Get-ChildItem -Path $bucketsdir -Directory).Name if ($null -eq $bucketNames) { return @() # Return a zero-length list instead of $null. } else { $knownBuckets = known_buckets for ($i = $knownBuckets.Count - 1; $i -ge 0 ; $i--) { $name = $knownBuckets[$i] if ($bucketNames.Contains($name)) { [void]$bucketNames.Remove($name) $bucketNames.Insert(0, $name) } } return $bucketNames } } function buckets { Show-DeprecatedWarning $MyInvocation 'Get-LocalBucket' return Get-LocalBucket } function Convert-RepositoryUri { [CmdletBinding()] param ( [Parameter(Mandatory, Position = 0, ValueFromPipeline = $true)] [AllowEmptyString()] [String] $Uri ) process { # https://git-scm.com/docs/git-clone#_git_urls # https://regex101.com/r/xGmwRr/1 if ($Uri -match '(?:@|/{1,3})(?:www\.|.*@)?(?[^/]+?)(?::\d+)?[:/](?.+)/(?.+?)(?:\.git)?/?$') { $Matches.provider, $Matches.user, $Matches.repo -join '/' } else { error "$Uri is not a valid Git URL!" error "Please see https://git-scm.com/docs/git-clone#_git_urls for valid ones." return $null } } } function list_buckets { $buckets = @() Get-LocalBucket | ForEach-Object { $bucket = [Ordered]@{ Name = $_ } $path = Find-BucketDirectory $_ -Root if ((Test-Path (Join-Path $path '.git')) -and (Get-Command git -ErrorAction SilentlyContinue)) { $bucket.Source = Invoke-Git -Path $path -ArgumentList @('config', 'remote.origin.url') $bucket.Updated = Invoke-Git -Path $path -ArgumentList @('log', '--format=%aD', '-n', '1') | Get-Date } else { $bucket.Source = friendly_path $path $bucket.Updated = (Get-Item "$path\bucket" -ErrorAction SilentlyContinue).LastWriteTime } $bucket.Manifests = Get-ChildItem "$path\bucket" -Force -Recurse -ErrorAction SilentlyContinue | Measure-Object | Select-Object -ExpandProperty Count $buckets += [PSCustomObject]$bucket } ,$buckets } function add_bucket($name, $repo) { if (!(Test-GitAvailable)) { error "Git is required for buckets. Run 'scoop install git' and try again." return 1 } $dir = Find-BucketDirectory $name -Root if (Test-Path $dir) { warn "The '$name' bucket already exists. To add this bucket again, first remove it by running 'scoop bucket rm $name'." return 2 } $uni_repo = Convert-RepositoryUri -Uri $repo if ($null -eq $uni_repo) { return 1 } foreach ($bucket in Get-LocalBucket) { if (Test-Path -Path "$bucketsdir\$bucket\.git") { $remote = Invoke-Git -Path "$bucketsdir\$bucket" -ArgumentList @('config', '--get', 'remote.origin.url') if ((Convert-RepositoryUri -Uri $remote) -eq $uni_repo) { warn "Bucket $bucket already exists for $repo" return 2 } } } Write-Host 'Checking repo... ' -NoNewline $out = Invoke-Git -ArgumentList @('ls-remote', $repo) 2>&1 if ($LASTEXITCODE -ne 0) { error "'$repo' doesn't look like a valid git repository`n`nError given:`n$out" return 1 } ensure $bucketsdir | Out-Null $dir = ensure $dir $out = Invoke-Git -ArgumentList @('clone', $repo, $dir, '-q') if ($LASTEXITCODE -ne 0) { error "Failed to clone '$repo' to '$dir'.`n`nError given:`n$out`n`nPlease check the repository URL or network connection and try again." Remove-Item $dir -Recurse -Force -ErrorAction SilentlyContinue return 1 } Write-Host 'OK' if (get_config USE_SQLITE_CACHE) { info 'Updating cache...' Set-ScoopDB -Path (Get-ChildItem (Find-BucketDirectory $name) -Filter '*.json' -Recurse).FullName } success "The $name bucket was added successfully." return 0 } function rm_bucket($name) { $dir = Find-BucketDirectory $name -Root if (!(Test-Path $dir)) { error "'$name' bucket not found." return 1 } Remove-Item $dir -Recurse -Force -ErrorAction Stop if (get_config USE_SQLITE_CACHE) { info 'Updating cache...' Remove-ScoopDBItem -Bucket $name } success "The $name bucket was removed successfully." return 0 } function new_issue_msg($app, $bucket, $title, $body) { $app, $manifest, $bucket, $url = Get-Manifest "$bucket/$app" $url = known_bucket_repo $bucket $bucket_path = "$bucketsdir\$bucket" if (Test-Path $bucket_path) { $remote = Invoke-Git -Path $bucket_path -ArgumentList @('config', '--get', 'remote.origin.url') # Support ssh and http syntax # git@PROVIDER:USER/REPO.git # https://PROVIDER/USER/REPO.git $remote -match '(@|:\/\/)(?.+)[:/](?.*)\/(?.*)(\.git)?$' | Out-Null $url = "https://$($Matches.Provider)/$($Matches.User)/$($Matches.Repo)" } if (!$url) { return 'Please contact the bucket maintainer!' } # Print only github repositories if ($url -like '*github*') { $title = [System.Web.HttpUtility]::UrlEncode("$app@$($manifest.version): $title") $body = [System.Web.HttpUtility]::UrlEncode($body) $url = $url -replace '\.git$', '' $url = "$url/issues/new?title=$title" if ($body) { $url += "&body=$body" } } $msg = "`nPlease try again or create a new issue by using the following link and paste your console output:" return "$msg`n$url" } ================================================ FILE: lib/commands.ps1 ================================================ # Description: Functions for managing commands and aliases. ## Functions for commands function command_files { (Get-ChildItem "$PSScriptRoot\..\libexec") + (Get-ChildItem "$scoopdir\shims") | Where-Object 'scoop-.*?\.ps1$' -Property Name -Match } function commands { command_files | ForEach-Object { command_name $_ } } function command_name($filename) { $filename.name | Select-String 'scoop-(.*?)\.ps1$' | ForEach-Object { $_.matches[0].groups[1].value } } function command_path($cmd) { $cmd_path = "$PSScriptRoot\..\libexec\scoop-$cmd.ps1" # built in commands if (!(Test-Path $cmd_path)) { # get path from shim $shim_path = "$scoopdir\shims\scoop-$cmd.ps1" $line = ((Get-Content $shim_path) | Where-Object { $_.startswith('$path') }) if ($line) { Invoke-Command ([scriptblock]::Create($line)) -NoNewScope $cmd_path = $path } else { $cmd_path = $shim_path } } $cmd_path } function exec($cmd, $arguments) { $cmd_path = command_path $cmd & $cmd_path @arguments } ## Functions for aliases function add_alias { param( [ValidateNotNullOrEmpty()] [string]$name, [ValidateNotNullOrEmpty()] [string]$command, [string]$description ) $aliases = get_config ALIAS ([PSCustomObject]@{}) if ($aliases.$name) { abort "Alias '$name' already exists." } $alias_script_name = "scoop-$name" $shimdir = shimdir $false if (Test-Path "$shimdir\$alias_script_name.ps1") { abort "File '$alias_script_name.ps1' already exists in shims directory." } $script = @( "# Summary: $description", "$command" ) -join "`n" try { $script | Out-UTF8File "$shimdir\$alias_script_name.ps1" } catch { abort $_.Exception } # Add the new alias to the config. $aliases | Add-Member -MemberType NoteProperty -Name $name -Value $alias_script_name set_config ALIAS $aliases | Out-Null } function rm_alias { param( [ValidateNotNullOrEmpty()] [string]$name ) $aliases = get_config ALIAS ([PSCustomObject]@{}) if (!$aliases.$name) { abort "Alias '$name' doesn't exist." } info "Removing alias '$name'..." if (Test-Path "$(shimdir $false)\scoop-$name.ps1") { Remove-Item "$(shimdir $false)\scoop-$name.ps1" } $aliases.PSObject.Properties.Remove($name) set_config ALIAS $aliases | Out-Null } function list_aliases { param( [bool]$verbose ) $aliases = get_config ALIAS ([PSCustomObject]@{}) $alias_info = $aliases.PSObject.Properties.Name | Where-Object { $_ } | ForEach-Object { # Mark the alias as , if the alias script file does NOT exist. if (!(Test-Path "$(shimdir $false)\scoop-$_.ps1")) { [PSCustomObject]@{ Name = $_ Command = '' } return } $content = Get-Content (command_path $_) [PSCustomObject]@{ Name = $_ Command = ($content | Select-Object -Skip 1).Trim() Summary = (summary $content).Trim() } } if (!$alias_info) { info 'No alias found.' return } $alias_info = $alias_info | Sort-Object Name $properties = @('Name', 'Command') if ($verbose) { $properties += 'Summary' } $alias_info | Select-Object $properties } ================================================ FILE: lib/core.ps1 ================================================ function Get-PESubsystem($filePath) { try { $fileStream = [System.IO.FileStream]::new($filePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read) $binaryReader = [System.IO.BinaryReader]::new($fileStream) $fileStream.Seek(0x3C, [System.IO.SeekOrigin]::Begin) | Out-Null $peOffset = $binaryReader.ReadInt32() $fileStream.Seek($peOffset, [System.IO.SeekOrigin]::Begin) | Out-Null $fileHeaderOffset = $fileStream.Position $fileStream.Seek(18, [System.IO.SeekOrigin]::Current) | Out-Null $fileStream.Seek($fileHeaderOffset + 0x5C, [System.IO.SeekOrigin]::Begin) | Out-Null return $binaryReader.ReadInt16() } catch { return -1 } finally { $binaryReader.Close() $fileStream.Close() } } function Set-PESubsystem($filePath, $targetSubsystem) { try { $fileStream = [System.IO.FileStream]::new($filePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite) $binaryReader = [System.IO.BinaryReader]::new($fileStream) $binaryWriter = [System.IO.BinaryWriter]::new($fileStream) $fileStream.Seek(0x3C, [System.IO.SeekOrigin]::Begin) | Out-Null $peOffset = $binaryReader.ReadInt32() $fileStream.Seek($peOffset, [System.IO.SeekOrigin]::Begin) | Out-Null $fileHeaderOffset = $fileStream.Position $fileStream.Seek(18, [System.IO.SeekOrigin]::Current) | Out-Null $fileStream.Seek($fileHeaderOffset + 0x5C, [System.IO.SeekOrigin]::Begin) | Out-Null $binaryWriter.Write([System.Int16] $targetSubsystem) } catch { return $false } finally { $binaryReader.Close() $fileStream.Close() } return $true } function Optimize-SecurityProtocol { # .NET Framework 4.7+ has a default security protocol called 'SystemDefault', # which allows the operating system to choose the best protocol to use. # If SecurityProtocolType contains 'SystemDefault' (means .NET4.7+ detected) # and the value of SecurityProtocol is 'SystemDefault', just do nothing on SecurityProtocol, # 'SystemDefault' will use TLS 1.2 if the webrequest requires. $isNewerNetFramework = ([System.Enum]::GetNames([System.Net.SecurityProtocolType]) -contains 'SystemDefault') $isSystemDefault = ([System.Net.ServicePointManager]::SecurityProtocol.Equals([System.Net.SecurityProtocolType]::SystemDefault)) # If not, change it to support TLS 1.2 if (!($isNewerNetFramework -and $isSystemDefault)) { # Set to TLS 1.2 (3072). Ssl3, TLS 1.0, and 1.1 have been deprecated, # https://datatracker.ietf.org/doc/html/rfc8996 [System.Net.ServicePointManager]::SecurityProtocol = 3072 } } function Show-DeprecatedWarning { <# .SYNOPSIS Print deprecated warning for functions, which will be deleted in near future. .PARAMETER Invocation Invocation to identify location of line. Just pass $MyInvocation. .PARAMETER New New command name. #> param($Invocation, [String] $New) warn ('"{0}" will be deprecated. Please change your code/manifest to use "{1}"' -f $Invocation.MyCommand.Name, $New) Write-Host " -> $($Invocation.PSCommandPath):$($Invocation.ScriptLineNumber):$($Invocation.OffsetInLine)" -ForegroundColor DarkGray } function load_cfg($file) { if(!(Test-Path $file)) { return $null } try { # ReadAllLines will detect the encoding of the file automatically # Ref: https://docs.microsoft.com/en-us/dotnet/api/system.io.file.readalllines?view=netframework-4.5 $content = [System.IO.File]::ReadAllLines($file) return ($content | ConvertFrom-Json -ErrorAction Stop) } catch { Write-Host "ERROR loading $file`: $($_.exception.message)" } } function get_config($name, $default) { $name = $name.ToLowerInvariant() if($null -eq $scoopConfig.$name -and $null -ne $default) { return $default } return $scoopConfig.$name } function set_config { Param ( [ValidateNotNullOrEmpty()] $name, $value ) $name = $name.ToLowerInvariant() if ($null -eq $scoopConfig -or $scoopConfig.Count -eq 0) { ensure (Split-Path -Path $configFile) | Out-Null $scoopConfig = New-Object -TypeName PSObject } if ($value -eq [bool]::TrueString -or $value -eq [bool]::FalseString) { $value = [System.Convert]::ToBoolean($value) } # Initialize config's change Complete-ConfigChange -Name $name -Value $value if ($null -eq $scoopConfig.$name) { $scoopConfig | Add-Member -MemberType NoteProperty -Name $name -Value $value } else { $scoopConfig.$name = $value } if ($null -eq $value) { $scoopConfig.PSObject.Properties.Remove($name) } # Save config with UTF8NoBOM encoding ConvertTo-Json $scoopConfig | Out-UTF8File -FilePath $configFile return $scoopConfig } function Complete-ConfigChange { [CmdletBinding()] param ( [Parameter(Mandatory, Position = 0)] [string] $Name, [Parameter(Mandatory, Position = 1)] [AllowEmptyString()] [string] $Value ) if ($Name -eq 'use_isolated_path') { $oldValue = get_config USE_ISOLATED_PATH if ($Value -eq $oldValue) { return } else { $currPathEnvVar = $scoopPathEnvVar } . "$PSScriptRoot\..\lib\system.ps1" if ($Value -eq $false -or $Value -eq '') { info 'Turn off Scoop isolated path... This may take a while, please wait.' $movedPath = Get-EnvVar -Name $currPathEnvVar if ($movedPath) { Add-Path -Path $movedPath -Quiet Remove-Path -Path ('%' + $currPathEnvVar + '%') -Quiet Set-EnvVar -Name $currPathEnvVar -Quiet } if (is_admin) { $movedPath = Get-EnvVar -Name $currPathEnvVar -Global if ($movedPath) { Add-Path -Path $movedPath -Global -Quiet Remove-Path -Path ('%' + $currPathEnvVar + '%') -Global -Quiet Set-EnvVar -Name $currPathEnvVar -Global -Quiet } } } else { $newPathEnvVar = if ($Value -eq $true) { 'SCOOP_PATH' } else { $Value.ToUpperInvariant() } info "Turn on Scoop isolated path ('$newPathEnvVar')... This may take a while, please wait." $movedPath = Remove-Path -Path "$scoopdir\apps\*" -TargetEnvVar $currPathEnvVar -Quiet -PassThru if ($movedPath) { Add-Path -Path $movedPath -TargetEnvVar $newPathEnvVar -Quiet Add-Path -Path ('%' + $newPathEnvVar + '%') -Quiet if ($currPathEnvVar -ne 'PATH') { Remove-Path -Path ('%' + $currPathEnvVar + '%') -Quiet Set-EnvVar -Name $currPathEnvVar -Quiet } } if (is_admin) { $movedPath = Remove-Path -Path "$globaldir\apps\*" -TargetEnvVar $currPathEnvVar -Global -Quiet -PassThru if ($movedPath) { Add-Path -Path $movedPath -TargetEnvVar $newPathEnvVar -Global -Quiet Add-Path -Path ('%' + $newPathEnvVar + '%') -Global -Quiet if ($currPathEnvVar -ne 'PATH') { Remove-Path -Path ('%' + $currPathEnvVar + '%') -Global -Quiet Set-EnvVar -Name $currPathEnvVar -Global -Quiet } } } } } if ($Name -eq 'use_sqlite_cache' -and $Value -eq $true) { if ((Get-DefaultArchitecture) -eq 'arm64') { abort 'SQLite cache is not supported on ARM64 platform.' } . "$PSScriptRoot\..\lib\database.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" info 'Initializing SQLite cache in progress... This may take a while, please wait.' Set-ScoopDB } } function Invoke-Git { [CmdletBinding()] [OutputType([String])] param( [Parameter(Mandatory = $false, Position = 0)] [Alias('PSPath', 'Path')] [ValidateNotNullOrEmpty()] [String] $WorkingDirectory, [Parameter(Mandatory = $true, Position = 1)] [Alias('Args')] [String[]] $ArgumentList ) $proxy = get_config PROXY $git = Get-HelperPath -Helper Git if ($WorkingDirectory) { $ArgumentList = @('-C', $WorkingDirectory) + $ArgumentList } if([String]::IsNullOrEmpty($proxy) -or $proxy -eq 'none') { return & $git @ArgumentList } if($ArgumentList -Match '\b(clone|checkout|pull|fetch|ls-remote)\b') { $j = Start-Job -ScriptBlock { # convert proxy setting for git $proxy = $using:proxy if ($proxy -and $proxy.StartsWith('currentuser@')) { $proxy = $proxy.Replace('currentuser@', ':@') } $env:HTTPS_PROXY = $proxy $env:HTTP_PROXY = $proxy & $using:git @using:ArgumentList } $o = $j | Receive-Job -Wait -AutoRemoveJob return $o } return & $git @ArgumentList } function Invoke-GitLog { [CmdletBinding()] Param ( [Parameter(Mandatory, ValueFromPipeline)] [String]$Path, [Parameter(Mandatory, ValueFromPipeline)] [String]$CommitHash, [String]$Name = '' ) Process { if ($Name) { if ($Name.Length -gt 12) { $Name = "$($Name.Substring(0, 10)).." } $Name = "%Cgreen$($Name.PadRight(12, ' ').Substring(0, 12))%Creset " } Invoke-Git -Path $Path -ArgumentList @('--no-pager', 'log', '--color', '--no-decorate', "--grep='^(chore)'", '--invert-grep', '--abbrev=12', "--format=tformat: * %C(yellow)%h%Creset %<|(72,trunc)%s $Name%C(cyan)%cr%Creset", "$CommitHash..HEAD") } } # helper functions function coalesce($a, $b) { if($a) { return $a } $b } function is_admin { $admin = [security.principal.windowsbuiltinrole]::administrator $id = [security.principal.windowsidentity]::getcurrent() ([security.principal.windowsprincipal]($id)).isinrole($admin) } # messages function abort($msg, [int] $exit_code=1) { write-host $msg -f red; exit $exit_code } function error($msg) { write-host "ERROR $msg" -f darkred } function warn($msg) { write-host "WARN $msg" -f darkyellow } function info($msg) { write-host "INFO $msg" -f darkgray } function debug($obj) { if ((get_config DEBUG $false) -ine 'true' -and $env:SCOOP_DEBUG -ine 'true') { return } $prefix = "DEBUG[$(Get-Date -UFormat %s)]" $param = $MyInvocation.Line.Replace($MyInvocation.InvocationName, '').Trim() $msg = $obj | Out-String -Stream if($null -eq $obj -or $null -eq $msg) { Write-Host "$prefix $param = " -f DarkCyan -NoNewline Write-Host '$null' -f DarkYellow -NoNewline Write-Host " -> $($MyInvocation.PSCommandPath):$($MyInvocation.ScriptLineNumber):$($MyInvocation.OffsetInLine)" -f DarkGray return } if($msg.GetType() -eq [System.Object[]]) { Write-Host "$prefix $param ($($obj.GetType()))" -f DarkCyan -NoNewline Write-Host " -> $($MyInvocation.PSCommandPath):$($MyInvocation.ScriptLineNumber):$($MyInvocation.OffsetInLine)" -f DarkGray $msg | Where-Object { ![String]::IsNullOrWhiteSpace($_) } | Select-Object -Skip 2 | # Skip headers ForEach-Object { Write-Host "$prefix $param.$($_)" -f DarkCyan } } else { Write-Host "$prefix $param = $($msg.Trim())" -f DarkCyan -NoNewline Write-Host " -> $($MyInvocation.PSCommandPath):$($MyInvocation.ScriptLineNumber):$($MyInvocation.OffsetInLine)" -f DarkGray } } function success($msg) { write-host $msg -f darkgreen } function filesize($length) { $gb = [math]::pow(2, 30) $mb = [math]::pow(2, 20) $kb = [math]::pow(2, 10) if($length -gt $gb) { "{0:n1} GB" -f ($length / $gb) } elseif($length -gt $mb) { "{0:n1} MB" -f ($length / $mb) } elseif($length -gt $kb) { "{0:n1} KB" -f ($length / $kb) } else { if ($null -eq $length) { $length = 0 } "$($length) B" } } # dirs function basedir($global) { if($global) { return $globaldir } $scoopdir } function appsdir($global) { "$(basedir $global)\apps" } function shimdir($global) { "$(basedir $global)\shims" } function modulesdir($global) { "$(basedir $global)\modules" } function appdir($app, $global) { "$(appsdir $global)\$app" } function versiondir($app, $version, $global) { "$(appdir $app $global)\$version" } function currentdir($app, $global) { if (get_config NO_JUNCTION) { $version = Select-CurrentVersion -App $app -Global:$global } else { $version = 'current' } "$(appdir $app $global)\$version" } function persistdir($app, $global) { "$(basedir $global)\persist\$app" } function usermanifestsdir { "$(basedir)\workspace" } function usermanifest($app) { "$(usermanifestsdir)\$app.json" } function cache_path($app, $version, $url) { $underscoredUrl = $url -replace '[^\w\.\-]+', '_' $filePath = Join-Path $cachedir "$app#$version#$underscoredUrl" # NOTE: Scoop cache files migration. Remove this 6 months after the feature ships. if (Test-Path $filePath) { return $filePath } $urlStream = [System.IO.MemoryStream]::new([System.Text.Encoding]::UTF8.GetBytes($url)) $sha = (Get-FileHash -Algorithm SHA256 -InputStream $urlStream).Hash.ToLower().Substring(0, 7) $extension = [System.IO.Path]::GetExtension($url) $filePath = $filePath -replace "$underscoredUrl", "$sha$extension" return $filePath } # apps function sanitary_path($path) { return [regex]::replace($path, "[/\\?:*<>|]", "") } function installed($app, [Nullable[bool]]$global) { if ($null -eq $global) { return (installed $app $false) -or (installed $app $true) } # Dependencies of the format "bucket/dependency" install in a directory of form # "dependency". So we need to extract the bucket from the name and only give the app # name to is_directory $app = ($app -split '/|\\')[-1] return $null -ne (Select-CurrentVersion -AppName $app -Global:$global) } function installed_apps($global) { $dir = appsdir $global if (Test-Path $dir) { Get-ChildItem $dir | Where-Object { $_.psiscontainer -and $_.name -ne 'scoop' } | ForEach-Object { $_.name } } } # check whether the app failed to install function failed($app, $global) { $app = ($app -split '/|\\')[-1] $appPath = appdir $app $global $hasCurrent = (get_config NO_JUNCTION) -or (Test-Path "$appPath\current") return (Test-Path $appPath) -and !($hasCurrent -and (installed $app $global)) } function file_path($app, $file) { Show-DeprecatedWarning $MyInvocation 'Get-AppFilePath' Get-AppFilePath -App $app -File $file } function Get-AppFilePath { [CmdletBinding()] [OutputType([String])] param( [Parameter(Mandatory = $true, Position = 0)] [String] $App, [Parameter(Mandatory = $true, Position = 1)] [String] $File ) # normal path to file $Path = "$(currentdir $App $false)\$File" if (Test-Path $Path) { return $Path } # global path to file $Path = "$(currentdir $App $true)\$File" if (Test-Path $Path) { return $Path } # not found return $null } Function Test-CommandAvailable { param ( [String]$Name ) Return [Boolean](Get-Command $Name -ErrorAction Ignore) } Function Test-GitAvailable { return [Boolean](Get-HelperPath -Helper Git) } function Get-HelperPath { [CmdletBinding()] [OutputType([String])] param( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [ValidateSet('Git', '7zip', 'Lessmsi', 'Innounp', 'Dark', 'Aria2')] [String] $Helper ) begin { $HelperPath = $null } process { switch ($Helper) { 'Git' { $internalgit = (Get-AppFilePath 'git' 'mingw64\bin\git.exe'), (Get-AppFilePath 'git' 'mingw32\bin\git.exe') | Where-Object { $_ -ne $null } if ($internalgit) { $HelperPath = $internalgit } else { $HelperPath = (Get-Command git -CommandType Application -TotalCount 1 -ErrorAction Ignore).Source } } '7zip' { $HelperPath = Get-AppFilePath '7zip' '7z.exe' } 'Lessmsi' { $HelperPath = Get-AppFilePath 'lessmsi' 'lessmsi.exe' } 'Innounp' { $HelperPath = Get-AppFilePath 'innounp-unicode' 'innounp.exe' if ([String]::IsNullOrEmpty($HelperPath)) { $HelperPath = Get-AppFilePath 'innounp' 'innounp.exe' } } 'Dark' { $HelperPath = Get-AppFilePath 'wixtoolset' 'wix.exe' if ([String]::IsNullOrEmpty($HelperPath)) { $HelperPath = Get-AppFilePath 'dark' 'dark.exe' } } 'Aria2' { $HelperPath = Get-AppFilePath 'aria2' 'aria2c.exe' } } return $HelperPath } } function Get-CommandPath { [CmdletBinding()] [OutputType([String])] param( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [String] $Command ) begin { $userShims = shimdir $false $globalShims = shimdir $true } process { try { $comm = Get-Command $Command -ErrorAction Stop } catch { return $null } $commandPath = if ($comm.Path -like "$userShims\scoop-*.ps1") { # Scoop aliases $comm.Source } elseif ($comm.Path -like "$userShims*" -or $comm.Path -like "$globalShims*") { Get-ShimTarget ($comm.Path -replace '\.exe$', '.shim') } elseif ($comm.CommandType -eq 'Application') { $comm.Source } elseif ($comm.CommandType -eq 'Alias') { Get-CommandPath $comm.ResolvedCommandName } else { $null } return $commandPath } } function Test-HelperInstalled { [CmdletBinding()] param( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [ValidateSet('7zip', 'Lessmsi', 'Innounp', 'Dark', 'Aria2')] [String] $Helper ) return ![String]::IsNullOrWhiteSpace((Get-HelperPath -Helper $Helper)) } function app_status($app, $global) { $status = @{} $status.installed = installed $app $global $status.version = Select-CurrentVersion -AppName $app -Global:$global $status.latest_version = $status.version $install_info = install_info $app $status.version $global $status.failed = failed $app $global $status.hold = ($install_info.hold -eq $true) $deprecated_dir = (Find-BucketDirectory -Name $install_info.bucket -Root) + "\deprecated" $status.deprecated = (Get-ChildItem $deprecated_dir -Filter "$(sanitary_path $app).json" -Recurse).FullName $manifest = manifest $app $install_info.bucket $install_info.url $status.removed = (!$manifest) if ($manifest.version) { $status.latest_version = $manifest.version } $status.outdated = $false if ($status.version -and $status.latest_version) { if (get_config FORCE_UPDATE $false) { $status.outdated = ((Compare-Version -ReferenceVersion $status.version -DifferenceVersion $status.latest_version) -ne 0) } else { $status.outdated = ((Compare-Version -ReferenceVersion $status.version -DifferenceVersion $status.latest_version) -gt 0) } } $status.missing_deps = @() $deps = @($manifest.depends) | Where-Object { if ($null -eq $_) { return $null } else { $app, $bucket, $null = parse_app $_ return !(installed $app) } } if ($deps) { $status.missing_deps += , $deps } return $status } function appname_from_url($url) { (split-path $url -leaf) -replace '.json$', '' } # paths function fname($path) { split-path $path -leaf } function strip_ext($fname) { $fname -replace '\.[^\.]*$', '' } function strip_filename($path) { $path -replace [regex]::escape((fname $path)) } function strip_fragment($url) { $url -replace (new-object uri $url).fragment } function ensure($dir) { if (!(Test-Path -Path $dir)) { New-Item -Path $dir -ItemType Directory | Out-Null } Convert-Path -Path $dir } function Get-AbsolutePath { <# .SYNOPSIS Get absolute path .DESCRIPTION Get absolute path, even if not existed .PARAMETER Path Path to manipulate .OUTPUTS System.String Absolute path, may or maynot existed #> [CmdletBinding()] [OutputType([string])] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string] $Path ) process { return $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path) } } function fullpath($path) { Show-DeprecatedWarning $MyInvocation 'Get-AbsolutePath' return Get-AbsolutePath -Path $path } function friendly_path($path) { $h = (Get-PSProvider 'FileSystem').Home if (!$h.EndsWith('\')) { $h += '\' } if ($h -eq '\') { return $path } else { return $path -replace ([Regex]::Escape($h)), '~\' } } function is_local($path) { ($path -notmatch '^https?://') -and (Test-Path $path) } # operations function run($exe, $arg, $msg, $continue_exit_codes) { Show-DeprecatedWarning $MyInvocation 'Invoke-ExternalCommand' Invoke-ExternalCommand -FilePath $exe -ArgumentList $arg -Activity $msg -ContinueExitCodes $continue_exit_codes } function Invoke-ExternalCommand { [CmdletBinding(DefaultParameterSetName = "Default")] [OutputType([Boolean])] param ( [Parameter(Mandatory = $true, Position = 0)] [Alias("Path")] [ValidateNotNullOrEmpty()] [String] $FilePath, [Parameter(Position = 1)] [Alias("Args")] [String[]] $ArgumentList, [Parameter(ParameterSetName = "UseShellExecute")] [Switch] $RunAs, [Parameter(ParameterSetName = "UseShellExecute")] [Switch] $Quiet, [Alias("Msg")] [String] $Activity, [Alias("cec")] [Hashtable] $ContinueExitCodes, [Parameter(ParameterSetName = "Default")] [Alias("Log")] [String] $LogPath ) if ($Activity) { Write-Host "$Activity " -NoNewline } $Process = New-Object System.Diagnostics.Process $Process.StartInfo.FileName = $FilePath $Process.StartInfo.UseShellExecute = $false if ($LogPath) { if ($FilePath -match '^msiexec(.exe)?$') { $ArgumentList += "/lwe `"$LogPath`"" } else { $redirectToLogFile = $true $Process.StartInfo.RedirectStandardOutput = $true $Process.StartInfo.RedirectStandardError = $true } } if ($RunAs) { $Process.StartInfo.UseShellExecute = $true $Process.StartInfo.Verb = 'RunAs' } if ($Quiet) { $Process.StartInfo.UseShellExecute = $true $Process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden } if ($ArgumentList.Length -gt 0) { # Remove existing double quotes and split arguments # '(?<=(? '$filename')$(if ($shim_app) { ' installed from ' + $shim_app })" } function shim($path, $global, $name, $arg) { if (!(Test-Path $path)) { abort "Can't shim '$(fname $path)': couldn't find '$path'." } $abs_shimdir = ensure (shimdir $global) Add-Path -Path $abs_shimdir -Global:$global if (!$name) { $name = strip_ext (fname $path) } $shim = "$abs_shimdir\$($name.tolower())" # convert to relative path $resolved_path = Convert-Path $path Push-Location $abs_shimdir $relative_path = Resolve-Path -Relative $resolved_path Pop-Location if ($path -match '\.(exe|com)$') { # for programs with no awareness of any shell warn_on_overwrite "$shim.shim" $path Copy-Item (get_shim_path) "$shim.exe" -Force Write-Output "path = `"$resolved_path`"" | Out-UTF8File "$shim.shim" if ($arg) { Write-Output "args = $arg" | Out-UTF8File "$shim.shim" -Append } $target_subsystem = Get-PESubsystem $resolved_path if ($target_subsystem -eq 2) { # we only want to make shims GUI Write-Output "Making $shim.exe a GUI binary." Set-PESubsystem "$shim.exe" $target_subsystem | Out-Null } } elseif ($path -match '\.(bat|cmd)$') { # shim .bat, .cmd so they can be used by programs with no awareness of PSH warn_on_overwrite "$shim.cmd" $path @( "@rem $resolved_path", "@`"$resolved_path`" $arg %*" ) -join "`r`n" | Out-UTF8File "$shim.cmd" warn_on_overwrite $shim $path @( "#!/bin/sh", "# $resolved_path", "MSYS2_ARG_CONV_EXCL=/C cmd.exe /C `"$resolved_path`" $arg `"$@`"" ) -join "`n" | Out-UTF8File $shim -NoNewLine } elseif ($path -match '\.ps1$') { # if $path points to another drive resolve-path prepends .\ which could break shims warn_on_overwrite "$shim.ps1" $path $ps1text = if ($relative_path -match '^(\.\\)?\w:.*$') { @( "# $resolved_path", "`$path = `"$path`"", "if (`$MyInvocation.ExpectingInput) { `$input | & `$path $arg @args } else { & `$path $arg @args }", "exit `$LASTEXITCODE" ) } else { @( "# $resolved_path", "`$path = Join-Path `$PSScriptRoot `"$relative_path`"", "if (`$MyInvocation.ExpectingInput) { `$input | & `$path $arg @args } else { & `$path $arg @args }", "exit `$LASTEXITCODE" ) } $ps1text -join "`r`n" | Out-UTF8File "$shim.ps1" # make ps1 accessible from cmd.exe warn_on_overwrite "$shim.cmd" $path @( "@rem $resolved_path", "@echo off", "where /q pwsh.exe", "if %errorlevel% equ 0 (", " pwsh -noprofile -ex unrestricted -file `"$resolved_path`" $arg %*", ") else (", " powershell -noprofile -ex unrestricted -file `"$resolved_path`" $arg %*", ")" ) -join "`r`n" | Out-UTF8File "$shim.cmd" warn_on_overwrite $shim $path @( "#!/bin/sh", "# $resolved_path", "if command -v pwsh.exe > /dev/null 2>&1; then", " pwsh.exe -noprofile -ex unrestricted -file `"$resolved_path`" $arg `"$@`"", "else", " powershell.exe -noprofile -ex unrestricted -file `"$resolved_path`" $arg `"$@`"", "fi" ) -join "`n" | Out-UTF8File $shim -NoNewLine } elseif ($path -match '\.jar$') { warn_on_overwrite "$shim.cmd" $path @( "@rem $resolved_path", "@pushd $(Split-Path $resolved_path -Parent)", "@java -jar `"$resolved_path`" $arg %*", "@popd" ) -join "`r`n" | Out-UTF8File "$shim.cmd" warn_on_overwrite $shim $path @( "#!/bin/sh", "# $resolved_path", "if [ `$WSL_INTEROP ]", 'then', " cd `$(wslpath -u '$(Split-Path $resolved_path -Parent)')", 'else', " cd `$(cygpath -u '$(Split-Path $resolved_path -Parent)')", 'fi', "java.exe -jar `"$resolved_path`" $arg `"$@`"" ) -join "`n" | Out-UTF8File $shim -NoNewLine } elseif ($path -match '\.py$') { warn_on_overwrite "$shim.cmd" $path @( "@rem $resolved_path", "@python `"$resolved_path`" $arg %*" ) -join "`r`n" | Out-UTF8File "$shim.cmd" warn_on_overwrite $shim $path @( '#!/bin/sh', "# $resolved_path", "python.exe `"$resolved_path`" $arg `"$@`"" ) -join "`n" | Out-UTF8File $shim -NoNewLine } else { warn_on_overwrite "$shim.cmd" $path $quoted_arg = if ($arg.Count -gt 0) { $arg | ForEach-Object { "`"$_`"" } } @( "@rem $resolved_path", '@echo off', 'bash -c "command -v wslpath >/dev/null"', 'if %errorlevel% equ 0 (', " bash `"`$(wslpath -u '$resolved_path')`" $quoted_arg %*", ') else (', " set args=$quoted_arg %*", ' setlocal enabledelayedexpansion', ' if not "!args!"=="" set args=!args:"=""!', " bash -c `"`$(cygpath -u '$resolved_path') !args!`"", ')' ) -join "`r`n" | Out-UTF8File "$shim.cmd" warn_on_overwrite $shim $path @( '#!/bin/sh', "# $resolved_path", "if [ `$WSL_INTEROP ]", 'then', " `"`$(wslpath -u '$resolved_path')`" $arg `"$@`"", 'else', " `"`$(cygpath -u '$resolved_path')`" $arg `"$@`"", 'fi' ) -join "`n" | Out-UTF8File $shim -NoNewLine } } function get_shim_path() { $shim_version = get_config SHIM 'kiennq' $shim_path = switch ($shim_version) { 'scoopcs' { "$(versiondir 'scoop' 'current')\supporting\shims\scoopcs\shim.exe" } '71' { "$(versiondir 'scoop' 'current')\supporting\shims\71\shim.exe" } 'kiennq' { "$(versiondir 'scoop' 'current')\supporting\shims\kiennq\shim.exe" } 'default' { "$(versiondir 'scoop' 'current')\supporting\shims\scoopcs\shim.exe" } default { warn "Unknown shim version: '$shim_version'" } } return $shim_path } function Get-DefaultArchitecture { $arch = get_config DEFAULT_ARCHITECTURE $system = if (${env:ProgramFiles(Arm)}) { 'arm64' } elseif ([System.Environment]::Is64BitOperatingSystem) { '64bit' } else { '32bit' } if ($null -eq $arch) { $arch = $system } else { try { $arch = Format-ArchitectureString $arch } catch { warn 'Invalid default architecture configured. Determining default system architecture' $arch = $system } } return $arch } function Format-ArchitectureString($Architecture) { if (!$Architecture) { return Get-DefaultArchitecture } $Architecture = $Architecture.ToString().ToLower() switch ($Architecture) { { @('64bit', '64', 'x64', 'amd64', 'x86_64', 'x86-64') -contains $_ } { return '64bit' } { @('32bit', '32', 'x86', 'i386', '386', 'i686') -contains $_ } { return '32bit' } { @('arm64', 'arm', 'aarch64') -contains $_ } { return 'arm64' } default { throw [System.ArgumentException] "Invalid architecture: '$Architecture'" } } } function Confirm-InstallationStatus { [CmdletBinding()] [OutputType([Object[]])] param( [Parameter(Mandatory = $true)] [String[]] $Apps, [Switch] $Global ) $Installed = @() $Apps | Select-Object -Unique | Where-Object { $_ -ne 'scoop' } | ForEach-Object { $App, $null, $null = parse_app $_ if ($Global) { if (Test-Path (appdir $App $true)) { $Installed += , @($App, $true) } elseif (Test-Path (appdir $App $false)) { error "'$App' isn't installed globally, but it may be installed locally." warn "Try again without the --global (or -g) flag instead." } else { error "'$App' isn't installed." } } else { if (Test-Path (appdir $App $false)) { $Installed += , @($App, $false) } elseif (Test-Path (appdir $App $true)) { error "'$App' isn't installed locally, but it may be installed globally." warn "Try again with the --global (or -g) flag instead." } else { error "'$App' isn't installed." } } if (failed $App $Global) { error "'$App' isn't installed correctly." } } return , $Installed } function wraptext($text, $width) { if(!$width) { $width = $host.ui.rawui.buffersize.width }; $width -= 1 # be conservative: doesn't seem to print the last char $text -split '\r?\n' | ForEach-Object { $line = '' $_ -split ' ' | ForEach-Object { if($line.length -eq 0) { $line = $_ } elseif($line.length + $_.length + 1 -le $width) { $line += " $_" } else { $lines += ,$line; $line = $_ } } $lines += ,$line } $lines -join "`n" } function pluralize($count, $singular, $plural) { if($count -eq 1) { $singular } else { $plural } } # convert list of apps to list of ($app, $global) tuples function applist($apps, $global) { if(!$apps) { return @() } return ,@($apps | ForEach-Object { ,@($_, $global) }) } function parse_app([string]$app) { if ($app -match '^(?:(?[a-zA-Z0-9-_.]+)/)?(?.*\.json|[a-zA-Z0-9-_.]+)(?:@(?.*))?$') { return $Matches['app'], $Matches['bucket'], $Matches['version'] } else { return $app, $null, $null } } function show_app($app, $bucket, $version) { if($bucket) { $app = "$bucket/$app" } if($version) { $app = "$app@$version" } return $app } function is_scoop_outdated() { $now = [System.DateTime]::Now try { $expireHour = (New-TimeSpan (get_config LAST_UPDATE) $now).TotalHours return ($expireHour -ge 3) } catch { # If not System.DateTime set_config LAST_UPDATE ($now.ToString('o')) | Out-Null return $true } } function Test-ScoopCoreOnHold() { $hold_update_until = get_config HOLD_UPDATE_UNTIL if ($null -eq $hold_update_until) { return $false } $parsed_date = New-Object -TypeName DateTime if ([System.DateTime]::TryParse($hold_update_until, $null, [System.Globalization.DateTimeStyles]::AssumeLocal, [ref]$parsed_date)) { if ((New-TimeSpan $parsed_date).TotalSeconds -lt 0) { warn "Skipping self-update of Scoop Core until $($parsed_date.ToLocalTime())..." warn "If you want to update Scoop Core immediately, use 'scoop unhold scoop; scoop update'." return $true } else { warn 'Self-update of Scoop Core is enabled again!' } } else { error "'hold_update_until' has been set in the wrong format and was removed." error 'If you want to disable self-update of Scoop Core for a moment,' error "use 'scoop hold scoop' or 'scoop config hold_update_until /'." } set_config HOLD_UPDATE_UNTIL $null | Out-Null return $false } function substitute($entity, [Hashtable] $params, [Bool]$regexEscape = $false) { if ($null -ne $entity) { $newentity = $entity.PSObject.Copy() switch ($entity.GetType().Name) { 'String' { $params.GetEnumerator() | ForEach-Object { if ($regexEscape -eq $false -or $null -eq $_.Value) { $newentity = $newentity.Replace($_.Name, $_.Value) } else { $newentity = $newentity.Replace($_.Name, [Regex]::Escape($_.Value)) } } } 'Object[]' { $newentity = $entity | ForEach-Object { , (substitute $_ $params $regexEscape) } } 'PSCustomObject' { $newentity.PSObject.Properties | ForEach-Object { $_.Value = substitute $_.Value $params $regexEscape } } } } return $newentity } function Out-UTF8File { param( [Parameter(Mandatory = $True, Position = 0)] [Alias("Path")] [String] $FilePath, [Switch] $Append, [Switch] $NoNewLine, [Parameter(ValueFromPipeline = $True)] [PSObject] $InputObject ) process { if ($Append) { [System.IO.File]::AppendAllText($FilePath, $InputObject) } else { if (!$NoNewLine) { # Ref: https://stackoverflow.com/questions/5596982 # Performance Note: `WriteAllLines` throttles memory usage while # `WriteAllText` needs to keep the complete string in memory. [System.IO.File]::WriteAllLines($FilePath, $InputObject) } else { # However `WriteAllText` does not add ending newline. [System.IO.File]::WriteAllText($FilePath, $InputObject) } } } } ################## # Core Bootstrap # ################## # Note: Github disabled TLS 1.0 support on 2018-02-23. Need to enable TLS 1.2 # for all communication with api.github.com Optimize-SecurityProtocol # Load Scoop config $configHome = $env:XDG_CONFIG_HOME, "$env:USERPROFILE\.config" | Select-Object -First 1 $configFile = "$configHome\scoop\config.json" # Check if it's the expected install path for scoop: /apps/scoop/current $coreRoot = Split-Path $PSScriptRoot $pathExpected = ($coreRoot -replace '\\','/') -like '*apps/scoop/current*' if ($pathExpected) { # Portable config is located in root directory: # .\current\scoop\apps\\config.json <- a reversed path # Imagine `/apps/scoop/current/` in a reversed format, # and the directory tree: # # ``` # : # ├─apps # ├─buckets # ├─cache # ├─persist # ├─shims # ├─config.json # ``` $configPortablePath = Get-AbsolutePath "$coreRoot\..\..\..\config.json" if (Test-Path $configPortablePath) { $configFile = $configPortablePath } } $scoopConfig = load_cfg $configFile # Scoop root directory $scoopdir = $env:SCOOP, (get_config ROOT_PATH), "$PSScriptRoot\..\..\..\..", "$([System.Environment]::GetFolderPath('UserProfile'))\scoop" | Where-Object { $_ } | Select-Object -First 1 | Get-AbsolutePath # Scoop global apps directory $globaldir = $env:SCOOP_GLOBAL, (get_config GLOBAL_PATH), "$([System.Environment]::GetFolderPath('CommonApplicationData'))\scoop" | Where-Object { $_ } | Select-Object -First 1 | Get-AbsolutePath # Scoop cache directory # Note: Setting the SCOOP_CACHE environment variable to use a shared directory # is experimental and untested. There may be concurrency issues when # multiple users write and access cached files at the same time. # Use at your own risk. $cachedir = $env:SCOOP_CACHE, (get_config CACHE_PATH), "$scoopdir\cache" | Where-Object { $_ } | Select-Object -First 1 | Get-AbsolutePath # Scoop apps' PATH Environment Variable $scoopPathEnvVar = switch (get_config USE_ISOLATED_PATH) { { $_ -is [string] } { $_.ToUpperInvariant() } $true { 'SCOOP_PATH' } default { 'PATH' } } # OS information $WindowsBuild = [System.Environment]::OSVersion.Version.Build ================================================ FILE: lib/database.ps1 ================================================ # Description: Functions for interacting with the Scoop database cache <# .SYNOPSIS Get SQLite .NET driver .DESCRIPTION Download and extract the SQLite .NET driver from NuGet. .PARAMETER Version System.String The version of the SQLite .NET driver to download. .INPUTS None .OUTPUTS System.Boolean True if the SQLite .NET driver was successfully downloaded and extracted, otherwise false. #> function Get-SQLite { param ( [string]$Version = '1.0.118' ) # Install SQLite try { Write-Host "Downloading SQLite $Version..." -ForegroundColor DarkYellow $sqlitePkgPath = "$env:TEMP\sqlite.zip" $sqliteTempPath = "$env:TEMP\sqlite" $sqlitePath = "$PSScriptRoot\..\supporting\sqlite" Invoke-WebRequest -Uri "https://api.nuget.org/v3-flatcontainer/stub.system.data.sqlite.core.netframework/$version/stub.system.data.sqlite.core.netframework.$version.nupkg" -OutFile $sqlitePkgPath Write-Host "Extracting SQLite $Version..." -ForegroundColor DarkYellow -NoNewline Expand-Archive -Path $sqlitePkgPath -DestinationPath $sqliteTempPath -Force New-Item -Path $sqlitePath -ItemType Directory -Force | Out-Null Move-Item -Path "$sqliteTempPath\build\net451\*", "$sqliteTempPath\lib\net451\System.Data.SQLite.dll" -Destination $sqlitePath -Force Remove-Item -Path $sqlitePkgPath, $sqliteTempPath -Recurse -Force Write-Host ' Done' -ForegroundColor DarkYellow return $true } catch { return $false } } <# .SYNOPSIS Open Scoop SQLite database. .DESCRIPTION Open Scoop SQLite database connection and create the necessary tables if not exists. .INPUTS None .OUTPUTS System.Data.SQLite.SQLiteConnection The SQLite database connection if **PassThru** is used. #> function Open-ScoopDB { # Load System.Data.SQLite if (!('System.Data.SQLite.SQLiteConnection' -as [Type])) { try { if (!(Test-Path -Path "$PSScriptRoot\..\supporting\sqlite\System.Data.SQLite.dll")) { Get-SQLite | Out-Null } Add-Type -Path "$PSScriptRoot\..\supporting\sqlite\System.Data.SQLite.dll" } catch { throw "Scoop's Database cache requires the ADO.NET driver:`n`thttp://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki" } } $dbPath = Join-Path $scoopdir 'scoop.db' $db = New-Object -TypeName System.Data.SQLite.SQLiteConnection $db.ConnectionString = "Data Source=$dbPath" $db.ParseViaFramework = $true # Allow UNC path $db.Open() $tableCommand = $db.CreateCommand() $tableCommand.CommandText = "CREATE TABLE IF NOT EXISTS 'app' ( name TEXT NOT NULL COLLATE NOCASE, description TEXT NOT NULL, version TEXT NOT NULL, bucket VARCHAR NOT NULL, manifest JSON NOT NULL, binary TEXT, shortcut TEXT, dependency TEXT, suggest TEXT, PRIMARY KEY (name, version, bucket) )" $tableCommand.CommandType = [System.Data.CommandType]::Text $tableCommand.ExecuteNonQuery() | Out-Null $tableCommand.Dispose() return $db } <# .SYNOPSIS Set Scoop database item(s). .DESCRIPTION Insert or replace item(s) into the Scoop SQLite database. .PARAMETER InputObject System.Object[] The database item(s) to insert or replace. .INPUTS System.Object[] .OUTPUTS None #> function Set-ScoopDBItem { [CmdletBinding()] param ( [Parameter(Mandatory, Position = 0, ValueFromPipeline)] [psobject[]] $InputObject ) begin { $db = Open-ScoopDB $dbTrans = $db.BeginTransaction() # TODO Support [hashtable]$InputObject $colName = @($InputObject | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name) $dbQuery = "INSERT OR REPLACE INTO app ($($colName -join ', ')) VALUES ($('@' + ($colName -join ', @')))" $dbCommand = $db.CreateCommand() $dbCommand.CommandText = $dbQuery $dbCommand.CommandType = [System.Data.CommandType]::Text } process { foreach ($item in $InputObject) { $item.PSObject.Properties | ForEach-Object { $dbCommand.Parameters.AddWithValue("@$($_.Name)", $_.Value) | Out-Null } $dbCommand.ExecuteNonQuery() | Out-Null } } end { try { $dbTrans.Commit() } catch { $dbTrans.Rollback() throw $_ } finally { $dbCommand.Dispose() $dbTrans.Dispose() $db.Dispose() } } } <# .SYNOPSIS Set Scoop app database item(s). .DESCRIPTION Insert or replace Scoop app(s) into the database. .PARAMETER Path System.String The path to the bucket. .PARAMETER CommitHash System.String The commit hash to compare with the HEAD. .INPUTS None .OUTPUTS None #> function Set-ScoopDB { [CmdletBinding()] param ( [Parameter(Position = 0, ValueFromPipeline)] [string[]] $Path ) begin { $list = [System.Collections.Generic.List[psobject]]::new() $arch = Get-DefaultArchitecture } process { if ($Path.Count -eq 0) { $bucketPath = Get-LocalBucket | ForEach-Object { Find-BucketDirectory $_ } $Path = (Get-ChildItem $bucketPath -Filter '*.json' -Recurse).FullName } $Path | ForEach-Object { $manifestRaw = [System.IO.File]::ReadAllText($_) $manifest = ConvertFrom-Json $manifestRaw -ErrorAction SilentlyContinue if ($null -ne $manifest.version) { $list.Add([pscustomobject]@{ name = $($_ -replace '.*[\\/]([^\\/]+)\.json$', '$1') description = if ($manifest.description) { $manifest.description } else { '' } version = $manifest.version bucket = $($_ -replace '.*buckets[\\/]([^\\/]+)(?:[\\/].*)', '$1') manifest = $manifestRaw binary = $( $result = @() @(arch_specific 'bin' $manifest $arch) | ForEach-Object { if ($_ -is [System.Array]) { $result += "$($_[1]).$($_[0].Split('.')[-1])" } else { $result += $_ } } $result -replace '.*?([^\\/]+)?(\.(exe|bat|cmd|ps1|jar|py))$', '$1' -join ' | ' ) shortcut = $( $result = @() @(arch_specific 'shortcuts' $manifest $arch) | ForEach-Object { $result += $_[1] } $result -replace '.*?([^\\/]+$)', '$1' -join ' | ' ) dependency = $manifest.depends -join ' | ' suggest = $( $suggest_output = @() $manifest.suggest.PSObject.Properties | ForEach-Object { $suggest_output += $_.Value -join ' | ' } $suggest_output -join ' | ' ) }) } } } end { if ($list.Count -ne 0) { Set-ScoopDBItem $list } } } <# .SYNOPSIS Select Scoop database item(s). .DESCRIPTION Select item(s) from the Scoop SQLite database. The pattern is matched against the name, binaries, and shortcuts columns for apps. .PARAMETER Pattern System.String The pattern to search for. If is an empty string, all items will be returned. .PARAMETER From System.String[] The fields to search from. .INPUTS System.String .OUTPUTS System.Data.DataTable The selected database item(s). #> function Select-ScoopDBItem { [CmdletBinding()] param ( [Parameter(Mandatory, Position = 0, ValueFromPipeline)] [AllowEmptyString()] [string] $Pattern, [Parameter(Mandatory, Position = 1)] [ValidateNotNullOrEmpty()] [string[]] $From ) begin { $db = Open-ScoopDB $dbAdapter = New-Object -TypeName System.Data.SQLite.SQLiteDataAdapter $result = New-Object System.Data.DataTable $dbQuery = "SELECT * FROM app WHERE $(($From -join ' LIKE @Pattern OR ') + ' LIKE @Pattern')" $dbQuery = "SELECT * FROM ($($dbQuery + ' ORDER BY version DESC')) GROUP BY name, bucket" $dbCommand = $db.CreateCommand() $dbCommand.CommandText = $dbQuery $dbCommand.CommandType = [System.Data.CommandType]::Text $dbAdapter.SelectCommand = $dbCommand } process { $dbCommand.Parameters.AddWithValue('@Pattern', $(if ($Pattern -eq '') { '%' } else { '%' + $Pattern + '%' })) | Out-Null [void]$dbAdapter.Fill($result) } end { $dbAdapter.Dispose() $db.Dispose() return $result } } <# .SYNOPSIS Get Scoop database item. .DESCRIPTION Get item from the Scoop SQLite database. .PARAMETER Name System.String The name of the item to get. .PARAMETER Bucket System.String The bucket of the item to get. .PARAMETER Version System.String The version of the item to get. If not provided, the latest version will be returned. .INPUTS System.String .OUTPUTS System.Data.DataTable The selected database item. #> function Get-ScoopDBItem { [CmdletBinding()] param ( [Parameter(Mandatory, Position = 0, ValueFromPipeline)] [string] $Name, [Parameter(Mandatory, Position = 1)] [string] $Bucket, [Parameter(Position = 2)] [string] $Version ) begin { $db = Open-ScoopDB $dbAdapter = New-Object -TypeName System.Data.SQLite.SQLiteDataAdapter $result = New-Object System.Data.DataTable $dbQuery = 'SELECT * FROM app WHERE name = @Name AND bucket = @Bucket' if ($Version) { $dbQuery += ' AND version = @Version' } else { $dbQuery += ' ORDER BY version DESC LIMIT 1' } $dbCommand = $db.CreateCommand() $dbCommand.CommandText = $dbQuery $dbCommand.CommandType = [System.Data.CommandType]::Text $dbAdapter.SelectCommand = $dbCommand } process { $dbCommand.Parameters.AddWithValue('@Name', $Name) | Out-Null $dbCommand.Parameters.AddWithValue('@Bucket', $Bucket) | Out-Null $dbCommand.Parameters.AddWithValue('@Version', $Version) | Out-Null [void]$dbAdapter.Fill($result) } end { $dbAdapter.Dispose() $db.Dispose() return $result } } <# .SYNOPSIS Remove Scoop database item(s). .DESCRIPTION Remove item(s) from the Scoop SQLite database. .PARAMETER Name System.String The name of the item to remove. .PARAMETER Bucket System.String The bucket of the item to remove. .INPUTS System.String .OUTPUTS None #> function Remove-ScoopDBItem { [CmdletBinding()] param ( [Parameter(Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] [string] $Name, [Parameter(Mandatory, Position = 1, ValueFromPipelineByPropertyName)] [string] $Bucket ) begin { $db = Open-ScoopDB $dbTrans = $db.BeginTransaction() $dbQuery = 'DELETE FROM app WHERE bucket = @Bucket' $dbCommand = $db.CreateCommand() $dbCommand.CommandText = $dbQuery $dbCommand.CommandType = [System.Data.CommandType]::Text } process { $dbCommand.Parameters.AddWithValue('@Bucket', $Bucket) | Out-Null if ($Name) { $dbCommand.CommandText = $dbQuery + ' AND name = @Name' $dbCommand.Parameters.AddWithValue('@Name', $Name) | Out-Null } $dbCommand.ExecuteNonQuery() | Out-Null } end { try { $dbTrans.Commit() } catch { $dbTrans.Rollback() throw $_ } finally { $dbCommand.Dispose() $dbTrans.Dispose() $db.Dispose() } } } ================================================ FILE: lib/decompress.ps1 ================================================ # Description: Functions for decompressing archives or installers function Invoke-Extraction { param ( [string] $Path, [string[]] $Name, [psobject] $Manifest, [Alias('Arch', 'Architecture')] [string] $ProcessorArchitecture ) $uri = @(url $Manifest $ProcessorArchitecture) # 'extract_dir' and 'extract_to' are paired $extractDir = @(extract_dir $Manifest $ProcessorArchitecture) $extractTo = @(extract_to $Manifest $ProcessorArchitecture) $extracted = 0 for ($i = 0; $i -lt $Name.Length; $i++) { # work out extraction method, if applicable $extractFn = $null switch -regex ($Name[$i]) { '\.zip$' { if ((Test-HelperInstalled -Helper 7zip) -or ((get_config USE_EXTERNAL_7ZIP) -and (Test-CommandAvailable 7z))) { $extractFn = 'Expand-7zipArchive' } else { $extractFn = 'Expand-ZipArchive' } continue } '\.msi$' { $extractFn = 'Expand-MsiArchive' continue } '\.exe$' { if ($Manifest.innosetup) { $extractFn = 'Expand-InnoArchive' } continue } { Test-7zipRequirement -Uri $_ } { $extractFn = 'Expand-7zipArchive' continue } } if ($extractFn) { $fnArgs = @{ Path = Join-Path $Path $Name[$i] DestinationPath = Join-Path $Path $extractTo[$extracted] ExtractDir = $extractDir[$extracted] } Write-Host 'Extracting ' -NoNewline Write-Host $(url_remote_filename $uri[$i]) -ForegroundColor Cyan -NoNewline Write-Host ' ... ' -NoNewline & $extractFn @fnArgs -Removal Write-Host 'done.' -ForegroundColor Green $extracted++ } } } function Expand-7zipArchive { [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [String] $Path, [Parameter(Position = 1)] [String] $DestinationPath = (Split-Path $Path), [String] $ExtractDir, [Parameter(ValueFromRemainingArguments = $true)] [String] $Switches, [ValidateSet('All', 'Skip', 'Rename')] [String] $Overwrite, [Switch] $Removal ) if ((get_config USE_EXTERNAL_7ZIP)) { try { $7zPath = (Get-Command '7z' -CommandType Application -ErrorAction Stop | Select-Object -First 1).Source } catch [System.Management.Automation.CommandNotFoundException] { abort "`nCannot find external 7-Zip (7z.exe) while 'use_external_7zip' is 'true'!`nRun 'scoop config use_external_7zip false' or install 7-Zip manually and try again." } } else { $7zPath = Get-HelperPath -Helper 7zip } $LogPath = "$(Split-Path $Path)\7zip.log" $DestinationPath = $DestinationPath.TrimEnd('\') $ArgList = @('x', $Path, "-o$DestinationPath", '-xr!*.nsis', '-y') $IsTar = ((strip_ext $Path) -match '\.tar$') -or ($Path -match '\.t[abgpx]z2?$') if (!$IsTar -and $ExtractDir) { $ArgList += "-ir!$ExtractDir\*" } if ($Switches) { $ArgList += (-split $Switches) } switch ($Overwrite) { 'All' { $ArgList += '-aoa' } 'Skip' { $ArgList += '-aos' } 'Rename' { $ArgList += '-aou' } } $Status = Invoke-ExternalCommand $7zPath $ArgList -LogPath $LogPath if (!$Status) { abort "Failed to extract files from $Path.`nLog file:`n $(friendly_path $LogPath)`n$(new_issue_msg $app $bucket 'decompress error')" } if ($IsTar) { # Check for tar $Status = Invoke-ExternalCommand $7zPath @('l', $Path) -LogPath $LogPath if ($Status) { # get inner tar file name $TarFile = (Select-String -Path $LogPath -Pattern '[^ ]*tar$').Matches.Value Expand-7zipArchive -Path "$DestinationPath\$TarFile" -DestinationPath $DestinationPath -ExtractDir $ExtractDir -Removal } else { abort "Failed to list files in $Path.`nNot a 7-Zip supported archive file." } } if (!$IsTar -and $ExtractDir) { movedir "$DestinationPath\$ExtractDir" $DestinationPath | Out-Null # Remove temporary directory if it is empty $ExtractDirTopPath = [string] "$DestinationPath\$($ExtractDir -replace '[\\/].*')" if ((Get-ChildItem -Path $ExtractDirTopPath -Force -ErrorAction Ignore).Count -eq 0) { Remove-Item -Path $ExtractDirTopPath -Recurse -Force -ErrorAction Ignore } } if (Test-Path $LogPath) { Remove-Item $LogPath -Force } if ($Removal) { if (($Path -replace '.*\.([^\.]*)$', '$1') -eq '001') { # Remove splitted 7-zip archive parts Get-ChildItem "$($Path -replace '\.[^\.]*$', '').???" | Remove-Item -Force } elseif (($Path -replace '.*\.part(\d+)\.rar$', '$1')[-1] -eq '1') { # Remove splitted RAR archive parts Get-ChildItem "$($Path -replace '\.part(\d+)\.rar$', '').part*.rar" | Remove-Item -Force } else { # Remove original archive file Remove-Item $Path -Force } } } function Expand-ZstdArchive { [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [String] $Path, [Parameter(Position = 1)] [String] $DestinationPath = (Split-Path $Path), [String] $ExtractDir, [Parameter(ValueFromRemainingArguments = $true)] [String] $Switches, [Switch] $Removal ) # TODO: Remove this function after 2024/12/31 Show-DeprecatedWarning $MyInvocation 'Expand-7zipArchive' Expand-7zipArchive -Path $Path -DestinationPath $DestinationPath -ExtractDir $ExtractDir -Switches $Switches -Removal:$Removal } function Expand-MsiArchive { [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [String] $Path, [Parameter(Position = 1)] [String] $DestinationPath = (Split-Path $Path), [String] $ExtractDir, [Parameter(ValueFromRemainingArguments = $true)] [String] $Switches, [Switch] $Removal ) $DestinationPath = $DestinationPath.TrimEnd('\') if ($ExtractDir) { $OriDestinationPath = $DestinationPath $DestinationPath = "$DestinationPath\_tmp" } if ((get_config USE_LESSMSI)) { $MsiPath = Get-HelperPath -Helper Lessmsi $ArgList = @('x', $Path, "$DestinationPath\") } else { $MsiPath = 'msiexec.exe' $ArgList = @('/a', $Path, '/qn', "TARGETDIR=$DestinationPath\SourceDir") } $LogPath = "$(Split-Path $Path)\msi.log" if ($Switches) { $ArgList += (-split $Switches) } $Status = Invoke-ExternalCommand $MsiPath $ArgList -LogPath $LogPath if (!$Status) { abort "Failed to extract files from $Path.`nLog file:`n $(friendly_path $LogPath)`n$(new_issue_msg $app $bucket 'decompress error')" } if ($ExtractDir -and (Test-Path "$DestinationPath\SourceDir")) { movedir "$DestinationPath\SourceDir\$ExtractDir" $OriDestinationPath | Out-Null Remove-Item $DestinationPath -Recurse -Force } elseif ($ExtractDir) { movedir "$DestinationPath\$ExtractDir" $OriDestinationPath | Out-Null Remove-Item $DestinationPath -Recurse -Force } elseif (Test-Path "$DestinationPath\SourceDir") { movedir "$DestinationPath\SourceDir" $DestinationPath | Out-Null } if (($DestinationPath -ne (Split-Path $Path)) -and (Test-Path "$DestinationPath\$(fname $Path)")) { Remove-Item "$DestinationPath\$(fname $Path)" -Force } if (Test-Path $LogPath) { Remove-Item $LogPath -Force } if ($Removal) { # Remove original archive file Remove-Item $Path -Force } } function Expand-InnoArchive { [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [String] $Path, [Parameter(Position = 1)] [String] $DestinationPath = (Split-Path $Path), [String] $ExtractDir, [Parameter(ValueFromRemainingArguments = $true)] [String] $Switches, [Switch] $Removal ) $LogPath = "$(Split-Path $Path)\innounp.log" $ArgList = @('-x', "-d$DestinationPath", $Path, '-y') switch -Regex ($ExtractDir) { '^[^{].*' { $ArgList += "-c{app}\$ExtractDir" } '^{.*' { $ArgList += "-c$ExtractDir" } Default { $ArgList += '-c{app}' } } if ($Switches) { $ArgList += (-split $Switches) } $Status = Invoke-ExternalCommand (Get-HelperPath -Helper Innounp) $ArgList -LogPath $LogPath if (!$Status) { abort "Failed to extract files from $Path.`nLog file:`n $(friendly_path $LogPath)`n$(new_issue_msg $app $bucket 'decompress error')" } if (Test-Path $LogPath) { Remove-Item $LogPath -Force } if ($Removal) { # Remove original archive file Remove-Item $Path -Force } } function Expand-ZipArchive { [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [String] $Path, [Parameter(Position = 1)] [String] $DestinationPath = (Split-Path $Path), [String] $ExtractDir, [Switch] $Removal ) if ($ExtractDir) { $OriDestinationPath = $DestinationPath $DestinationPath = "$DestinationPath\_tmp" } # Disable progress bar to gain performance $oldProgressPreference = $ProgressPreference $global:ProgressPreference = 'SilentlyContinue' # Compatible with Pscx v3 (https://github.com/Pscx/Pscx) ('Microsoft.PowerShell.Archive' is not needed for Pscx v4) Microsoft.PowerShell.Archive\Expand-Archive -Path $Path -DestinationPath $DestinationPath -Force $global:ProgressPreference = $oldProgressPreference if ($ExtractDir) { movedir "$DestinationPath\$ExtractDir" $OriDestinationPath | Out-Null Remove-Item $DestinationPath -Recurse -Force } if ($Removal) { # Remove original archive file Remove-Item $Path -Force } } function Expand-DarkArchive { [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [String] $Path, [Parameter(Position = 1)] [String] $DestinationPath = (Split-Path $Path), [Parameter(ValueFromRemainingArguments = $true)] [String] $Switches, [Switch] $Removal ) $LogPath = "$(Split-Path $Path)\dark.log" $DarkPath = Get-HelperPath -Helper Dark if ((Split-Path $DarkPath -Leaf) -eq 'wix.exe') { $ArgList = @('burn', 'extract', $Path, '-out', $DestinationPath, '-outba', "$DestinationPath\UX") } else { $ArgList = @('-nologo', '-x', $DestinationPath, $Path) } if ($Switches) { $ArgList += (-split $Switches) } $Status = Invoke-ExternalCommand $DarkPath $ArgList -LogPath $LogPath if (!$Status) { abort "Failed to extract files from $Path.`nLog file:`n $(friendly_path $LogPath)`n$(new_issue_msg $app $bucket 'decompress error')" } if (Test-Path "$DestinationPath\WixAttachedContainer") { Rename-Item "$DestinationPath\WixAttachedContainer" 'AttachedContainer' -ErrorAction Ignore } else { if (Test-Path "$DestinationPath\AttachedContainer\a0") { $Xml = [xml](Get-Content -Raw "$DestinationPath\UX\manifest.xml" -Encoding utf8) $Xml.BurnManifest.UX.Payload | ForEach-Object { Rename-Item "$DestinationPath\UX\$($_.SourcePath)" $_.FilePath -ErrorAction Ignore } $Xml.BurnManifest.Payload | ForEach-Object { Rename-Item "$DestinationPath\AttachedContainer\$($_.SourcePath)" $_.FilePath -ErrorAction Ignore } } } if (Test-Path $LogPath) { Remove-Item $LogPath -Force } if ($Removal) { # Remove original archive file Remove-Item $Path -Force } } ================================================ FILE: lib/depends.ps1 ================================================ function Get-Dependency { <# .SYNOPSIS Get app's dependencies (with apps attached at the end). .PARAMETER AppName App's name .PARAMETER Architecture App's architecture .PARAMETER Resolved List of resolved dependencies (internal use) .PARAMETER Unresolved List of unresolved dependencies (internal use) .OUTPUTS [Object[]] List of app's dependencies .NOTES When pipeline input is used, the output will have duplicate items, and should be filtered by 'Select-Object -Unique'. ALgorithm: http://www.electricmonk.nl/docs/dependency_resolving_algorithm/dependency_resolving_algorithm.html #> [CmdletBinding()] [OutputType([Object[]])] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [PSObject] $AppName, [Parameter(Mandatory = $true, Position = 1)] [String] $Architecture, [String[]] $Resolved = @(), [String[]] $Unresolved = @() ) process { $AppName, $manifest, $bucket, $url = Get-Manifest $AppName $Unresolved += $AppName if (!$manifest) { if (((Get-LocalBucket) -notcontains $bucket) -and $bucket) { warn "Bucket '$bucket' not added. Add it with $(if($bucket -in (known_buckets)) { "'scoop bucket add $bucket' or " })'scoop bucket add $bucket '." } abort "Couldn't find manifest for '$AppName'$(if($bucket) { " from '$bucket' bucket" } elseif($url) { " at '$url'" })." } $deps = @(Get-InstallationHelper $manifest $Architecture) + @($manifest.depends) | Select-Object -Unique foreach ($dep in $deps) { if ($Resolved -notcontains $dep) { if ($Unresolved -contains $dep) { abort "Circular dependency detected: '$AppName' -> '$dep'." } $Resolved, $Unresolved = Get-Dependency $dep $Architecture -Resolved $Resolved -Unresolved $Unresolved } } $Unresolved = $Unresolved -ne $AppName if ($bucket) { $Resolved += "$bucket/$AppName" } else { if ($url) { $Resolved += $url } else { $Resolved += $AppName } } if ($Unresolved.Length -eq 0) { return $Resolved } else { return $Resolved, $Unresolved } } } function Get-InstallationHelper { <# .SYNOPSIS Get helpers that used in installation .PARAMETER Manifest App's manifest .PARAMETER Architecture Architecture of the app .PARAMETER All If true, return all helpers, otherwise return only helpers that are not already installed .OUTPUTS [Object[]] List of helpers #> [CmdletBinding()] [OutputType([Object[]])] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [PSObject] $Manifest, [Parameter(Mandatory = $true, Position = 1)] [String] $Architecture, [Switch] $All ) begin { $helper = @() } process { $url = arch_specific 'url' $Manifest $Architecture $pre_install = arch_specific 'pre_install' $Manifest $Architecture $installer = arch_specific 'installer' $Manifest $Architecture $post_install = arch_specific 'post_install' $Manifest $Architecture $script = $pre_install + $installer.script + $post_install if (((Test-7zipRequirement -Uri $url) -or ($script -like '*Expand-7zipArchive *')) -and !(get_config USE_EXTERNAL_7ZIP)) { $helper += '7zip' } if (((Test-LessmsiRequirement -Uri $url) -or ($script -like '*Expand-MsiArchive *')) -and (get_config USE_LESSMSI)) { $helper += 'lessmsi' } if ($Manifest.innosetup -or ($script -like '*Expand-InnoArchive *')) { $helper += 'innounp' } if ($script -like '*Expand-DarkArchive *') { $helper += 'dark' } if (!$All) { '7zip', 'lessmsi', 'innounp', 'dark' | ForEach-Object { if (Test-HelperInstalled -Helper $_) { $helper = $helper -ne $_ } } } } end { return $helper } } function Test-7zipRequirement { [CmdletBinding()] [OutputType([Boolean])] param ( [Parameter(Mandatory = $true)] [AllowNull()] [String[]] $Uri ) return ($Uri | Where-Object { $_ -match '\.(001|7z|bz(ip)?2?|gz|img|iso|lzma|lzh|nupkg|rar|tar|t[abgpx]z2?|t?zst|xz)(\.[^\d.]+)?$' }).Count -gt 0 } function Test-LessmsiRequirement { [CmdletBinding()] [OutputType([Boolean])] param ( [Parameter(Mandatory = $true)] [AllowNull()] [String[]] $Uri ) return ($Uri | Where-Object { $_ -match '\.msi$' }).Count -gt 0 } ================================================ FILE: lib/description.ps1 ================================================ function find_description($url, $html, $redir = $false) { $meta = meta_tags $html # check $og_description = meta_content $meta 'property' 'og:description' if($og_description) { return $og_description, '' } # check $description = meta_content $meta 'name' 'description' if($description) { return $description, '' } # check redirect $refresh = meta_refresh $meta $url if($refresh -and !$redir) { $wc = New-Object Net.Webclient $wc.Headers.Add('User-Agent', (Get-UserAgent)) $data = $wc.DownloadData($refresh) $html = (Get-Encoding($wc)).GetString($data) return find_description $refresh $html $true } # check text for 'x is ...' $text = html_text $html $meta $text_desc = find_is $text if($text_desc) { return $text_desc, 'text' } # first paragraph $first_para = first_para $html if($first_para) { return $first_para, 'first

' } return $null, $null } function clean_description($description) { if(!$description) { return $description } $description = $description -replace '\n', ' ' $description = $description -replace '\s{2,}', ' ' return $description.trim() } # Collects meta tags from $html into hashtables. function meta_tags($html) { $tags = @() $meta = ([regex]']+>').matches($html) $meta | ForEach-Object { $attrs = ([regex]'([\w-]+)="([^"]+)"').matches($_.value) $hash = @{} $attrs | ForEach-Object { $hash[$_.groups[1].value] = $_.groups[2].value } $tags += $hash } $tags } function meta_content($tags, $attribute, $search) { if(!$tags) { return } return $tags | Where-Object { $_[$attribute] -eq $search } | ForEach-Object { $_['content'] } } # Looks for a redirect URL in a refresh tag. function meta_refresh($tags, $url) { $refresh = meta_content $tags 'http-equiv' 'refresh' if($refresh) { if($refresh -match '\d+;\s*url\s*=\s*(.*)') { $refresh_url = $matches[1].trim("'", '"') if($refresh_url -notmatch '^https?://') { $refresh_url = "$url$refresh_url" } return $refresh_url } } } function html_body($html) { if($html -match '(?s)]*>(.*?)') { $body = $matches[1] $body = $body -replace '(?s)]*>.*?', ' ' $body = $body -replace '(?s)', ' ' return $body } } function html_text($body, $meta_tags) { $body = html_body $html if($body) { return strip_html $body } } function strip_html($html) { $html = $html -replace '(?s)<[^>]*>', ' ' $html = $html -replace '\t', ' ' $html = $html -replace ' ?', ' ' $html = $html -replace '>?', '>' $html = $html -replace '<?', '<' $html = $html -replace '"?', '"' $encoding_meta = meta_content $meta_tags 'http-equiv' 'Content-Type' if($encoding_meta) { if($encoding_meta -match 'charset\s*=\s*(.*)') { $charset = $matches[1] try { $encoding = [text.encoding]::getencoding($charset) } catch { Write-Warning "Unknown charset" } if($encoding) { $html = ([regex]'&#(\d+);?').replace($html, { param($m) try { return $encoding.getstring($m.Groups[1].Value) } catch { return $m.value } }) } } } $html = $html -replace '\n +', "`r`n" $html = $html -replace '\n{2,}', "`r`n" $html = $html -replace ' {2,}', ' ' $html = $html -replace ' (\.|,)', '$1' return $html.trim() } function find_is($text) { if($text -match '(?s)[\n\.]((?:[^\n\.])+? is .+?[\.!])') { return $matches[1].trim() } } function first_para($html) { $body = html_body $html if($body -match '(?s)]*>(.*?)

') { return strip_html $matches[1] } } ================================================ FILE: lib/diagnostic.ps1 ================================================ <# Diagnostic tests. Return $true if the test passed, otherwise $false. Use 'warn' to highlight the issue, and follow up with the recommended actions to rectify. #> function check_windows_defender($global) { $defender = Get-Service -Name WinDefend -ErrorAction SilentlyContinue if (Test-CommandAvailable Get-MpPreference) { if ((Get-MpPreference).DisableRealtimeMonitoring) { return $true } if ($defender -and $defender.Status) { if ($defender.Status -eq [System.ServiceProcess.ServiceControllerStatus]::Running) { $installPath = $scoopdir; if ($global) { $installPath = $globaldir; } $exclusionPath = (Get-MpPreference).ExclusionPath if (!($exclusionPath -contains $installPath)) { info "Windows Defender may slow down or disrupt installs with realtime scanning." Write-Host " Consider running:" Write-Host " sudo Add-MpPreference -ExclusionPath '$installPath'" Write-Host " (Requires 'sudo' command. Run 'scoop install sudo' if you don't have it.)" return $false } } } } return $true } function check_main_bucket { if ((Get-LocalBucket) -notcontains 'main') { warn 'Main bucket is not added.' Write-Host " run 'scoop bucket add main'" return $false } return $true } function check_long_paths { if ([System.Environment]::OSVersion.Version.Major -lt 10 -or [System.Environment]::OSVersion.Version.Build -lt 1607) { warn 'This version of Windows does not support configuration of LongPaths.' return $false } $key = Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -ErrorAction SilentlyContinue -Name 'LongPathsEnabled' if (!$key -or ($key.LongPathsEnabled -eq 0)) { warn 'LongPaths support is not enabled.' Write-Host " You can enable it by running:" Write-Host " sudo Set-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1" Write-Host " (Requires 'sudo' command. Run 'scoop install sudo' if you don't have it.)" return $false } return $true } function Get-WindowsDeveloperModeStatus { $DevModRegistryPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" if (!(Test-Path -Path $DevModRegistryPath) -or (Get-ItemProperty -Path ` $DevModRegistryPath -Name AllowDevelopmentWithoutDevLicense -ErrorAction ` SilentlyContinue).AllowDevelopmentWithoutDevLicense -ne 1) { warn "Windows Developer Mode is not enabled. Operations relevant to symlinks may fail without proper rights." Write-Host " You may read more about the symlinks support here:" Write-Host " https://blogs.windows.com/windowsdeveloper/2016/12/02/symlinks-windows-10/" return $false } return $true } ================================================ FILE: lib/download.ps1 ================================================ # Description: Functions for downloading files ## Meta downloader function Invoke-ScoopDownload ($app, $version, $manifest, $bucket, $architecture, $dir, $use_cache = $true, $check_hash = $true) { # we only want to show this warning once if (!$use_cache) { warn 'Cache is being ignored.' } # can be multiple urls: if there are, then installer should go first to make 'installer.args' section work $urls = @(script:url $manifest $architecture) # can be multiple cookies: they will be used for all HTTP requests. $cookies = $manifest.cookie # download first if (Test-Aria2Enabled) { Invoke-CachedAria2Download $app $version $manifest $architecture $dir $cookies $use_cache $check_hash } else { foreach ($url in $urls) { $fname = url_filename $url try { Invoke-CachedDownload $app $version $url "$dir\$fname" $cookies $use_cache } catch { Write-Host -ForegroundColor DarkRed $_ abort "URL $url is not valid" } if ($check_hash) { $manifest_hash = hash_for_url $manifest $url $architecture $ok, $err = check_hash "$dir\$fname" $manifest_hash $(show_app $app $bucket) if (!$ok) { error $err $cached = cache_path $app $version $url if (Test-Path $cached) { # rm cached file Remove-Item -Force $cached } if ($url.Contains('sourceforge.net')) { Write-Host -ForegroundColor Yellow 'SourceForge.net is known for causing hash validation fails. Please try again before opening a ticket.' } abort $(new_issue_msg $app $bucket 'hash check failed') } } } } return $urls.ForEach({ url_filename $_ }) } ## [System.Net] downloader function Invoke-CachedDownload ($app, $version, $url, $to, $cookies = $null, $use_cache = $true) { $cached = cache_path $app $version $url if (!(Test-Path $cached) -or !$use_cache) { ensure $cachedir | Out-Null Start-Download $url "$cached.download" $cookies Move-Item "$cached.download" $cached -Force } else { Write-Host "Loading $(url_remote_filename $url) from cache" } if (!($null -eq $to)) { if ($use_cache) { Copy-Item $cached $to } else { Move-Item $cached $to -Force } } } function Start-Download ($url, $to, $cookies) { $progress = [console]::isoutputredirected -eq $false -and $host.name -ne 'Windows PowerShell ISE Host' try { $url = handle_special_urls $url Invoke-Download $url $to $cookies $progress } catch { $e = $_.exception if ($e.Response.StatusCode -eq 'Unauthorized') { warn 'Token might be misconfigured.' } if ($e.innerexception) { $e = $e.innerexception } throw $e } } function Invoke-Download ($url, $to, $cookies, $progress) { # download with filesize and progress indicator $reqUrl = ($url -split '#')[0] $wreq = [Net.WebRequest]::Create($reqUrl) if ($wreq -is [Net.HttpWebRequest]) { $wreq.UserAgent = Get-UserAgent if (-not ($url -match 'sourceforge\.net' -or $url -match 'portableapps\.com')) { $wreq.Referer = strip_filename $url } if ($url -match 'api\.github\.com/repos') { $wreq.Accept = 'application/octet-stream' $wreq.Headers['Authorization'] = "Bearer $(Get-GitHubToken)" $wreq.Headers['X-GitHub-Api-Version'] = '2022-11-28' } if ($cookies) { $wreq.Headers.Add('Cookie', (cookie_header $cookies)) } get_config PRIVATE_HOSTS | Where-Object { $_ -ne $null -and $url -match $_.match } | ForEach-Object { (ConvertFrom-StringData -StringData $_.Headers).GetEnumerator() | ForEach-Object { $wreq.Headers[$_.Key] = $_.Value } } } try { $wres = $wreq.GetResponse() } catch [System.Net.WebException] { $exc = $_.Exception $handledCodes = @( [System.Net.HttpStatusCode]::MovedPermanently, # HTTP 301 [System.Net.HttpStatusCode]::Found, # HTTP 302 [System.Net.HttpStatusCode]::SeeOther, # HTTP 303 [System.Net.HttpStatusCode]::TemporaryRedirect # HTTP 307 ) # Only handle redirection codes $redirectRes = $exc.Response if ($handledCodes -notcontains $redirectRes.StatusCode) { throw $exc } # Get the new location of the file if ((-not $redirectRes.Headers) -or ($redirectRes.Headers -notcontains 'Location')) { throw $exc } $newUrl = $redirectRes.Headers['Location'] info "Following redirect to $newUrl..." # Handle manual file rename if ($url -like '*#/*') { $null, $postfix = $url -split '#/' $newUrl = "$newUrl`#/$postfix" } Invoke-Download $newUrl $to $cookies $progress return } $total = $wres.ContentLength if ($total -eq -1 -and $wreq -is [net.ftpwebrequest]) { $total = ftp_file_size($url) } if ($progress -and ($total -gt 0)) { [console]::CursorVisible = $false function Trace-DownloadProgress ($read) { Write-DownloadProgress $read $total $url } } else { Write-Host "Downloading $url ($(filesize $total))..." function Trace-DownloadProgress { #no op } } try { $s = $wres.getresponsestream() $fs = [io.file]::openwrite($to) $buffer = New-Object byte[] 2048 $totalRead = 0 $sw = [diagnostics.stopwatch]::StartNew() Trace-DownloadProgress $totalRead while (($read = $s.read($buffer, 0, $buffer.length)) -gt 0) { $fs.write($buffer, 0, $read) $totalRead += $read if ($sw.elapsedmilliseconds -gt 100) { $sw.restart() Trace-DownloadProgress $totalRead } } $sw.stop() Trace-DownloadProgress $totalRead } finally { if ($progress) { [console]::CursorVisible = $true Write-Host } if ($fs) { $fs.close() } if ($s) { $s.close() } $wres.close() } } function Format-DownloadProgress ($url, $read, $total, $console) { $filename = url_remote_filename $url # calculate current percentage done $p = [math]::Round($read / $total * 100, 0) # pre-generate LHS and RHS of progress string # so we know how much space we have $left = "$filename ($(filesize $total))" $right = [string]::Format('{0,3}%', $p) # calculate remaining width for progress bar $midwidth = $console.BufferSize.Width - ($left.Length + $right.Length + 8) # calculate how many characters are completed $completed = [math]::Abs([math]::Round(($p / 100) * $midwidth, 0) - 1) # generate dashes to symbolise completed if ($completed -gt 1) { $dashes = [string]::Join('', ((1..$completed) | ForEach-Object { '=' })) } # this is why we calculate $completed - 1 above $dashes += switch ($p) { 100 { '=' } default { '>' } } # the remaining characters are filled with spaces $spaces = switch ($dashes.Length) { $midwidth { [string]::Empty } default { [string]::Join('', ((1..($midwidth - $dashes.Length)) | ForEach-Object { ' ' })) } } "$left [$dashes$spaces] $right" } function Write-DownloadProgress ($read, $total, $url) { $console = $Host.UI.RawUI $left = $console.CursorPosition.X $top = $console.CursorPosition.Y $width = $console.BufferSize.Width if ($read -eq 0) { $maxOutputLength = $(Format-DownloadProgress $url 100 $total $console).Length if (($left + $maxOutputLength) -gt $width) { # not enough room to print progress on this line # print on new line Write-Host $left = 0 $top = $top + 1 if ($top -gt $console.CursorPosition.Y) { $top = $console.CursorPosition.Y } } } Write-Host $(Format-DownloadProgress $url $read $total $console) -NoNewline [console]::SetCursorPosition($left, $top) } ## Aria2 downloader function Test-Aria2Enabled { return (Test-HelperInstalled -Helper Aria2) -and (get_config 'aria2-enabled' $true) } function aria_exit_code($exitcode) { $codes = @{ 0 = 'All downloads were successful' 1 = 'An unknown error occurred' 2 = 'Timeout' 3 = 'Resource was not found' 4 = 'Aria2 saw the specified number of "resource not found" error. See --max-file-not-found option' 5 = 'Download aborted because download speed was too slow. See --lowest-speed-limit option' 6 = 'Network problem occurred.' 7 = 'There were unfinished downloads. This error is only reported if all finished downloads were successful and there were unfinished downloads in a queue when aria2 exited by pressing Ctrl-C by an user or sending TERM or INT signal' 8 = 'Remote server did not support resume when resume was required to complete download' 9 = 'There was not enough disk space available' 10 = 'Piece length was different from one in .aria2 control file. See --allow-piece-length-change option' 11 = 'Aria2 was downloading same file at that moment' 12 = 'Aria2 was downloading same info hash torrent at that moment' 13 = 'File already existed. See --allow-overwrite option' 14 = 'Renaming file failed. See --auto-file-renaming option' 15 = 'Aria2 could not open existing file' 16 = 'Aria2 could not create new file or truncate existing file' 17 = 'File I/O error occurred' 18 = 'Aria2 could not create directory' 19 = 'Name resolution failed' 20 = 'Aria2 could not parse Metalink document' 21 = 'FTP command failed' 22 = 'HTTP response header was bad or unexpected' 23 = 'Too many redirects occurred' 24 = 'HTTP authorization failed' 25 = 'Aria2 could not parse bencoded file (usually ".torrent" file)' 26 = '".torrent" file was corrupted or missing information that aria2 needed' 27 = 'Magnet URI was bad' 28 = 'Bad/unrecognized option was given or unexpected option argument was given' 29 = 'The remote server was unable to handle the request due to a temporary overloading or maintenance' 30 = 'Aria2 could not parse JSON-RPC request' 31 = 'Reserved. Not used' 32 = 'Checksum validation failed' } if ($null -eq $codes[$exitcode]) { return 'An unknown error occurred' } return $codes[$exitcode] } function get_filename_from_metalink($file) { $bytes = get_magic_bytes_pretty $file '' # check if file starts with ' p\@ssword' $proxy = get_config PROXY if (!$proxy) { return } try { $credentials, $address = $proxy -split '(?'." } $ret } ### URL handling function handle_special_urls($url) { # FossHub.com if ($url -match '^(?:.*fosshub.com\/)(?.*)(?:\/|\?dwl=)(?.*)$') { $Body = @{ projectUri = $Matches.name fileName = $Matches.filename source = 'CF' isLatestVersion = $true } if ((Invoke-RestMethod -Uri $url) -match '"p":"(?[a-f0-9]{24}).*?"r":"(?[a-f0-9]{24})') { $Body.Add('projectId', $Matches.pid) $Body.Add('releaseId', $Matches.rid) } $url = Invoke-RestMethod -Method Post -Uri 'https://api.fosshub.com/download/' -ContentType 'application/json' -Body (ConvertTo-Json $Body -Compress) if ($null -eq $url.error) { $url = $url.data.url } } # Sourceforge.net if ($url -match '(?:downloads\.)?sourceforge.net\/projects?\/(?[^\/]+)\/(?:files\/)?(?.*?)(?:$|\/download|\?)') { # Reshapes the URL to avoid redirections $url = "https://downloads.sourceforge.net/project/$($matches['project'])/$($matches['file'])" } # Github.com if ($url -match 'github.com/(?[^/]+)/(?[^/]+)/releases/download/(?[^/]+)/(?[^/#]+)(?.*)' -and ($token = Get-GitHubToken)) { $headers = @{ 'Authorization' = "token $token" } $privateUrl = "https://api.github.com/repos/$($Matches.owner)/$($Matches.repo)" $assetUrl = "https://api.github.com/repos/$($Matches.owner)/$($Matches.repo)/releases/tags/$($Matches.tag)" if ((Invoke-RestMethod -Uri $privateUrl -Headers $headers).Private) { $url = ((Invoke-RestMethod -Uri $assetUrl -Headers $headers).Assets | Where-Object -Property Name -EQ -Value $Matches.file).Url, $Matches.filename -join '' } } return $url } ### Remote file information function download_json($url) { $githubtoken = Get-GitHubToken $authheader = @{} if ($githubtoken) { $authheader = @{'Authorization' = "token $githubtoken" } } $ProgressPreference = 'SilentlyContinue' $result = Invoke-WebRequest $url -UseBasicParsing -Headers $authheader | Select-Object -ExpandProperty content | ConvertFrom-Json $ProgressPreference = 'Continue' $result } function get_magic_bytes($file) { if (!(Test-Path $file)) { return '' } if ((Get-Command Get-Content).parameters.ContainsKey('AsByteStream')) { # PowerShell Core (6.0+) '-Encoding byte' is replaced by '-AsByteStream' return Get-Content $file -AsByteStream -TotalCount 8 } else { return Get-Content $file -Encoding byte -TotalCount 8 } } function get_magic_bytes_pretty($file, $glue = ' ') { if (!(Test-Path $file)) { return '' } return (get_magic_bytes $file | ForEach-Object { $_.ToString('x2') }) -join $glue } Function Get-RemoteFileSize ($Uri) { $response = Invoke-WebRequest -Uri $Uri -Method HEAD -UseBasicParsing if (!$response.Headers.StatusCode) { $response.Headers.'Content-Length' | ForEach-Object { [int]$_ } } } function ftp_file_size($url) { $request = [net.ftpwebrequest]::create($url) $request.method = [net.webrequestmethods+ftp]::getfilesize $request.getresponse().contentlength } function url_filename($url) { (Split-Path $url -Leaf).split('?') | Select-Object -First 1 } function url_remote_filename($url) { # Unlike url_filename which can be tricked by appending a # URL fragment (e.g. #/dl.7z, useful for coercing a local filename), # this function extracts the original filename from the URL. $uri = (New-Object URI $url) $basename = Split-Path $uri.PathAndQuery -Leaf If ($basename -match '.*[?=]+([\w._-]+)') { $basename = $matches[1] } If (($basename -notlike '*.*') -or ($basename -match '^[v.\d]+$')) { $basename = Split-Path $uri.AbsolutePath -Leaf } If (($basename -notlike '*.*') -and ($uri.Fragment -ne '')) { $basename = $uri.Fragment.Trim('/', '#') } return $basename } ### Hash-related functions function hash_for_url($manifest, $url, $arch) { $hashes = @(hash $manifest $arch) | Where-Object { $_ -ne $null } if ($hashes.length -eq 0) { return $null } $urls = @(script:url $manifest $arch) $index = [array]::IndexOf($urls, $url) if ($index -eq -1) { abort "Couldn't find hash in manifest for '$url'." } @($hashes)[$index] } function check_hash($file, $hash, $app_name) { # returns (ok, err) if (!$hash) { warn "Warning: No hash in manifest. SHA256 for '$(fname $file)' is:`n $((Get-FileHash -Path $file -Algorithm SHA256).Hash.ToLower())" return $true, $null } Write-Host 'Checking hash of ' -NoNewline Write-Host $(url_remote_filename $url) -ForegroundColor Cyan -NoNewline Write-Host ' ... ' -NoNewline $algorithm, $expected = get_hash $hash if ($null -eq $algorithm) { return $false, "Hash type '$algorithm' isn't supported." } $actual = (Get-FileHash -Path $file -Algorithm $algorithm).Hash.ToLower() $expected = $expected.ToLower() if ($actual -ne $expected) { $msg = "Hash check failed!`n" $msg += "App: $app_name`n" $msg += "URL: $url`n" if (Test-Path $file) { $msg += "First bytes: $((get_magic_bytes_pretty $file ' ').ToUpper())`n" } if ($expected -or $actual) { $msg += "Expected: $expected`n" $msg += "Actual: $actual" } return $false, $msg } Write-Host 'ok.' -f Green return $true, $null } function get_hash([String] $multihash) { $type, $hash = $multihash -split ':' if (!$hash) { # no type specified, assume sha256 $type, $hash = 'sha256', $multihash } if (@('md5', 'sha1', 'sha256', 'sha512') -notcontains $type) { return $null, "Hash type '$type' isn't supported." } return $type, $hash.ToLower() } # Setup proxy globally setup_proxy ================================================ FILE: lib/getopt.ps1 ================================================ # adapted from http://hg.python.org/cpython/file/2.7/Lib/getopt.py # argv: # array of arguments # shortopts: # string of single-letter options. options that take a parameter # should be follow by ':' # longopts: # array of strings that are long-form options. options that take # a parameter should end with '=' # returns @(opts hash, remaining_args array, error string) # NOTES: # The first "--" in $argv, if any, will terminate all options; any # following arguments are treated as non-option arguments, even if # they begin with a hyphen. The "--" itself will not be included in # the returned $opts. (POSIX-compatible) function getopt([String[]]$argv, [String]$shortopts, [String[]]$longopts) { $opts = @{}; $rem = @() function err($msg) { $opts, $rem, $msg } function regex_escape($str) { return [Regex]::Escape($str) } for ($i = 0; $i -lt $argv.Length; $i++) { $arg = $argv[$i] if ($null -eq $arg) { continue } # don't try to parse array arguments if ($arg -is [Array]) { $rem += , $arg; continue } if ($arg -is [Int]) { $rem += $arg; continue } if ($arg -is [Decimal]) { $rem += $arg; continue } if ($arg -eq '--') { if ($i -lt $argv.Length - 1) { $rem += $argv[($i + 1)..($argv.Length - 1)] } break } elseif ($arg.StartsWith('--')) { $name = $arg.Substring(2) $longopt = $longopts | Where-Object { $_ -match "^$name=?$" } if ($longopt) { if ($longopt.EndsWith('=')) { # requires arg if ($i -eq $argv.Length - 1) { return err "Option --$name requires an argument." } $opts.$name = $argv[++$i] } else { $opts.$name = $true } } else { return err "Option --$name not recognized." } } elseif ($arg.StartsWith('-') -and $arg -ne '-') { for ($j = 1; $j -lt $arg.Length; $j++) { $letter = $arg[$j].ToString() if ($shortopts -match "$(regex_escape $letter)`:?") { $shortopt = $Matches[0] if ($shortopt[1] -eq ':') { if ($j -ne $arg.Length - 1 -or $i -eq $argv.Length - 1) { return err "Option -$letter requires an argument." } $opts.$letter = $argv[++$i] } else { $opts.$letter = $true } } else { return err "Option -$letter not recognized." } } } else { $rem += $arg } } $opts, $rem } ================================================ FILE: lib/help.ps1 ================================================ function usage($text) { $text | Select-String '(?m)^# Usage: ([^\n]*)$' | ForEach-Object { "Usage: " + $_.matches[0].groups[1].value } } function summary($text) { $text | Select-String '(?m)^# Summary: ([^\n]*)$' | ForEach-Object { $_.matches[0].groups[1].value } } function scoop_help($text) { $help_lines = $text | Select-String '(?ms)^# Help:(.(?!^[^#]))*' | ForEach-Object { $_.matches[0].value; } $help_lines -replace '(?ms)^#\s?(Help: )?', '' } function my_usage { # gets usage for the calling script usage (Get-Content $myInvocation.PSCommandPath -raw) } ================================================ FILE: lib/install.ps1 ================================================ function nightly_version($quiet = $false) { if (!$quiet) { warn "This is a nightly version. Downloaded files won't be verified." } return "nightly-$(Get-Date -Format 'yyyyMMdd')" } function install_app($app, $architecture, $global, $suggested, $use_cache = $true, $check_hash = $true) { $app, $manifest, $bucket, $url = Get-Manifest $app if (!$manifest) { abort "Couldn't find manifest for '$app'$(if ($bucket) { " from '$bucket' bucket" } elseif ($url) { " at '$url'" })." } $version = $manifest.version if (!$version) { abort "Manifest doesn't specify a version." } if ($version -match '[^\w\.\-\+_]') { abort "Manifest version has unsupported character '$($matches[0])'." } $is_nightly = $version -eq 'nightly' if ($is_nightly) { $version = nightly_version $check_hash = $false } $architecture = Get-SupportedArchitecture $manifest $architecture if ($null -eq $architecture) { error "'$app' doesn't support current architecture!" return } if ((get_config SHOW_MANIFEST $false) -and ($MyInvocation.ScriptName -notlike '*scoop-update*')) { Write-Host "Manifest: $app.json" $style = get_config CAT_STYLE if ($style) { $manifest | ConvertToPrettyJson | bat --no-paging --style $style --language json } else { $manifest | ConvertToPrettyJson } $answer = Read-Host -Prompt 'Continue installation? [Y/n]' if (($answer -eq 'n') -or ($answer -eq 'N')) { return } } Write-Output "Installing '$app' ($version) [$architecture]$(if ($bucket) { " from '$bucket' bucket" } else { " from '$url'" })" $dir = ensure (versiondir $app $version $global) $original_dir = $dir # keep reference to real (not linked) directory $persist_dir = persistdir $app $global $fname = Invoke-ScoopDownload $app $version $manifest $bucket $architecture $dir $use_cache $check_hash Invoke-Extraction -Path $dir -Name $fname -Manifest $manifest -ProcessorArchitecture $architecture Invoke-HookScript -HookType 'pre_install' -Manifest $manifest -ProcessorArchitecture $architecture Invoke-Installer -Path $dir -Name $fname -Manifest $manifest -ProcessorArchitecture $architecture -AppName $app -Global:$global ensure_install_dir_not_in_path $dir $global $dir = link_current $dir create_shims $manifest $dir $global $architecture create_startmenu_shortcuts $manifest $dir $global $architecture install_psmodule $manifest $dir $global env_add_path $manifest $dir $global $architecture env_set $manifest $global $architecture # persist data persist_data $manifest $original_dir $persist_dir persist_permission $manifest $global Invoke-HookScript -HookType 'post_install' -Manifest $manifest -ProcessorArchitecture $architecture # save info for uninstall save_installed_manifest $app $bucket $dir $url save_install_info @{ 'architecture' = $architecture; 'url' = $url; 'bucket' = $bucket } $dir if ($manifest.suggest) { $suggested[$app] = $manifest.suggest } success "'$app' ($version) was installed successfully!" show_notes $manifest $dir $original_dir $persist_dir } function is_in_dir($dir, $check) { $check -match "^$([regex]::Escape("$dir"))([/\\]|$)" } function Invoke-Installer { [CmdletBinding()] param ( [string] $Path, [string[]] $Name, [psobject] $Manifest, [Alias('Arch', 'Architecture')] [ValidateSet('32bit', '64bit', 'arm64')] [string] $ProcessorArchitecture, [string] $AppName, [switch] $Global, [switch] $Uninstall ) $type = if ($Uninstall) { 'uninstaller' } else { 'installer' } $installer = arch_specific $type $Manifest $ProcessorArchitecture if ($installer.file -or $installer.args) { # Installer filename is either explicit defined ('installer.file') or file name in the first URL if (!$Name) { $Name = url_filename @(url $manifest $architecture) } $progName = "$Path\$(coalesce $installer.file $Name[0])" if (!(is_in_dir $Path $progName)) { abort "Error in manifest: $((Get-Culture).TextInfo.ToTitleCase($type)) $progName is outside the app directory." } elseif (!(Test-Path $progName)) { abort "$((Get-Culture).TextInfo.ToTitleCase($type)) $progName is missing." } $substitutions = @{ '$dir' = $Path '$global' = $Global '$version' = $Manifest.version } $fnArgs = substitute $installer.args $substitutions if ($progName.EndsWith('.ps1')) { & $progName @fnArgs } else { $status = Invoke-ExternalCommand $progName -ArgumentList $fnArgs -Activity "Running $type ..." if (!$status) { if ($Uninstall) { abort 'Uninstallation aborted.' } else { abort "Installation aborted. You might need to run 'scoop uninstall $AppName' before trying again." } } # Don't remove installer if "keep" flag is set to true if (!$installer.keep) { Remove-Item $progName } } } Invoke-HookScript -HookType $type -Manifest $Manifest -ProcessorArchitecture $ProcessorArchitecture } function Invoke-HookScript { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [ValidateSet('installer', 'pre_install', 'post_install', 'uninstaller', 'pre_uninstall', 'post_uninstall')] [String] $HookType, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [PSCustomObject] $Manifest, [Parameter(Mandatory = $true)] [Alias('Arch', 'Architecture')] [ValidateSet('32bit', '64bit', 'arm64')] [string] $ProcessorArchitecture ) $script = arch_specific $HookType $Manifest $ProcessorArchitecture if ($HookType -in @('installer', 'uninstaller')) { $script = $script.script } if ($script) { Write-Host "Running $HookType script..." -NoNewline Invoke-Command ([scriptblock]::Create($script -join "`r`n")) Write-Host 'done.' -ForegroundColor Green } } # get target, name, arguments for shim function shim_def($item) { if ($item -is [array]) { return $item } return $item, (strip_ext (fname $item)), $null } function create_shims($manifest, $dir, $global, $arch) { $shims = @(arch_specific 'bin' $manifest $arch) $shims | Where-Object { $_ -ne $null } | ForEach-Object { $target, $name, $arg = shim_def $_ Write-Output "Creating shim for '$name'." if (Test-Path "$dir\$target" -PathType leaf) { $bin = "$dir\$target" } elseif (Test-Path $target -PathType leaf) { $bin = $target } else { $bin = (Get-Command $target).Source } if (!$bin) { abort "Can't shim '$target': File doesn't exist." } shim $bin $global $name (substitute $arg @{ '$dir' = $dir; '$original_dir' = $original_dir; '$persist_dir' = $persist_dir }) } } function rm_shim($name, $shimdir, $app) { '', '.shim', '.cmd', '.ps1' | ForEach-Object { $shimPath = "$shimdir\$name$_" $altShimPath = "$shimPath.$app" if ($app -and (Test-Path -Path $altShimPath -PathType Leaf)) { Write-Output "Removing shim '$name$_.$app'." Remove-Item $altShimPath } elseif (Test-Path -Path $shimPath -PathType Leaf) { Write-Output "Removing shim '$name$_'." Remove-Item $shimPath $oldShims = Get-Item -Path "$shimPath.*" -Exclude '*.shim', '*.cmd', '*.ps1' if ($null -eq $oldShims) { if ($_ -eq '.shim') { Write-Output "Removing shim '$name.exe'." Remove-Item -Path "$shimdir\$name.exe" } } else { (@($oldShims) | Sort-Object -Property LastWriteTimeUtc)[-1] | Rename-Item -NewName { $_.Name -replace '\.[^.]*$', '' } } } } } function rm_shims($app, $manifest, $global, $arch) { $shims = @(arch_specific 'bin' $manifest $arch) $shims | Where-Object { $_ -ne $null } | ForEach-Object { $target, $name, $null = shim_def $_ $shimdir = shimdir $global rm_shim $name $shimdir $app } } # Creates or updates the directory junction for [app]/current, # pointing to the specified version directory for the app. # # Returns the 'current' junction directory if in use, otherwise # the version directory. function link_current($versiondir) { if (get_config NO_JUNCTION) { return $versiondir.ToString() } $currentdir = "$(Split-Path $versiondir)\current" Write-Host "Linking $(friendly_path $currentdir) => $(friendly_path $versiondir)" if ($currentdir -eq $versiondir) { abort "Error: Version 'current' is not allowed!" } if (Test-Path $currentdir) { # remove the junction attrib -R /L $currentdir Remove-Item $currentdir -Recurse -Force -ErrorAction Stop } New-DirectoryJunction $currentdir $versiondir | Out-Null attrib $currentdir +R /L return $currentdir } # Removes the directory junction for [app]/current which # points to the current version directory for the app. # # Returns the 'current' junction directory (if it exists), # otherwise the normal version directory. function unlink_current($versiondir) { if (get_config NO_JUNCTION) { return $versiondir.ToString() } $currentdir = "$(Split-Path $versiondir)\current" if (Test-Path $currentdir) { Write-Host "Unlinking $(friendly_path $currentdir)" # remove read-only attribute on link attrib $currentdir -R /L # remove the junction Remove-Item $currentdir -Recurse -Force -ErrorAction Stop return $currentdir } return $versiondir } # to undo after installers add to path so that scoop manifest can keep track of this instead function ensure_install_dir_not_in_path($dir, $global) { $path = (Get-EnvVar -Name 'PATH' -Global:$global) $fixed, $removed = find_dir_or_subdir $path "$dir" if ($removed) { $removed | ForEach-Object { "Installer added '$(friendly_path $_)' to path. Removing." } Set-EnvVar -Name 'PATH' -Value $fixed -Global:$global } if (!$global) { $fixed, $removed = find_dir_or_subdir (Get-EnvVar -Name 'PATH' -Global) "$dir" if ($removed) { $removed | ForEach-Object { warn "Installer added '$_' to system path. You might want to remove this manually (requires admin permission)." } } } } function find_dir_or_subdir($path, $dir) { $dir = $dir.trimend('\') $fixed = @() $removed = @() $path.split(';') | ForEach-Object { if ($_) { if (($_ -eq $dir) -or ($_ -like "$dir\*")) { $removed += $_ } else { $fixed += $_ } } } return [string]::join(';', $fixed), $removed } function env_add_path($manifest, $dir, $global, $arch) { $env_add_path = arch_specific 'env_add_path' $manifest $arch $dir = $dir.TrimEnd('\') if ($env_add_path) { if (get_config USE_ISOLATED_PATH) { Add-Path -Path ('%' + $scoopPathEnvVar + '%') -Global:$global } $path = $env_add_path.Where({ $_ }).ForEach({ Join-Path $dir $_ | Get-AbsolutePath }).Where({ is_in_dir $dir $_ }) Add-Path -Path $path -TargetEnvVar $scoopPathEnvVar -Global:$global -Force } } function env_rm_path($manifest, $dir, $global, $arch) { $env_add_path = arch_specific 'env_add_path' $manifest $arch $dir = $dir.TrimEnd('\') if ($env_add_path) { $path = $env_add_path.Where({ $_ }).ForEach({ Join-Path $dir $_ | Get-AbsolutePath }).Where({ is_in_dir $dir $_ }) Remove-Path -Path $path -Global:$global # TODO: Remove after forced isolating Scoop path Remove-Path -Path $path -TargetEnvVar $scoopPathEnvVar -Global:$global } } function env_set($manifest, $global, $arch) { $env_set = arch_specific 'env_set' $manifest $arch if ($env_set) { $env_set | Get-Member -MemberType NoteProperty | ForEach-Object { $name = $_.Name $val = $ExecutionContext.InvokeCommand.ExpandString($env_set.$($name)) Set-EnvVar -Name $name -Value $val -Global:$global Set-Content env:\$name $val } } } function env_rm($manifest, $global, $arch) { $env_set = arch_specific 'env_set' $manifest $arch if ($env_set) { $env_set | Get-Member -MemberType NoteProperty | ForEach-Object { $name = $_.Name Set-EnvVar -Name $name -Value $null -Global:$global if (Test-Path env:\$name) { Remove-Item env:\$name } } } } function show_notes($manifest, $dir, $original_dir, $persist_dir) { if ($manifest.notes) { Write-Output 'Notes' Write-Output '-----' Write-Output (wraptext (substitute $manifest.notes @{ '$dir' = $dir; '$original_dir' = $original_dir; '$persist_dir' = $persist_dir })) } } function all_installed($apps, $global) { $apps | Where-Object { $app, $null, $null = parse_app $_ installed $app $global } } # returns (uninstalled, installed) function prune_installed($apps, $global) { $installed = @(all_installed $apps $global) $uninstalled = $apps | Where-Object { $installed -notcontains $_ } return @($uninstalled), @($installed) } function ensure_none_failed($apps) { foreach ($app in $apps) { $app = ($app -split '/|\\')[-1] -replace '\.json$', '' foreach ($global in $true, $false) { if ($global) { $instArgs = @('--global') } else { $instArgs = @() } if (failed $app $global) { if (installed $app $global) { info "Repair previous failed installation of $app." & "$PSScriptRoot\..\libexec\scoop-reset.ps1" $app @instArgs } else { warn "Purging previous failed installation of $app." & "$PSScriptRoot\..\libexec\scoop-uninstall.ps1" $app @instArgs } } } } } function show_suggestions($suggested) { $installed_apps = (installed_apps $true) + (installed_apps $false) foreach ($app in $suggested.keys) { $features = $suggested[$app] | Get-Member -type noteproperty | ForEach-Object { $_.name } foreach ($feature in $features) { $feature_suggestions = $suggested[$app].$feature $fulfilled = $false foreach ($suggestion in $feature_suggestions) { $suggested_app, $bucket, $null = parse_app $suggestion if ($installed_apps -contains $suggested_app) { $fulfilled = $true break } } if (!$fulfilled) { Write-Host "'$app' suggests installing '$([string]::join("' or '", $feature_suggestions))'." } } } } # Persistent data function persist_def($persist) { if ($persist -is [Array]) { $source = $persist[0] $target = $persist[1] } else { $source = $persist $target = $null } if (!$target) { $target = $source } return $source, $target } function persist_data($manifest, $original_dir, $persist_dir) { $persist = $manifest.persist if ($persist) { $persist_dir = ensure $persist_dir if ($persist -is [String]) { $persist = @($persist) } $persist | ForEach-Object { $source, $target = persist_def $_ Write-Host "Persisting $source" $source = $source.TrimEnd('/').TrimEnd('\\') $source = "$dir\$source" $target = "$persist_dir\$target" # if we have had persist data in the store, just create link and go if (Test-Path $target) { # if there is also a source data, rename it (to keep a original backup) if (Test-Path $source) { Move-Item -Force $source "$source.original" } # we don't have persist data in the store, move the source to target, then create link } elseif (Test-Path $source) { # ensure target parent folder exist ensure (Split-Path -Path $target) | Out-Null Move-Item $source $target # we don't have neither source nor target data! we need to create an empty target, # but we can't make a judgement that the data should be a file or directory... # so we create a directory by default. to avoid this, use pre_install # to create the source file before persisting (DON'T use post_install) } else { $target = New-Object System.IO.DirectoryInfo($target) ensure $target | Out-Null } # create link if (is_directory $target) { # target is a directory, create junction New-DirectoryJunction $source $target | Out-Null attrib $source +R /L } else { # target is a file, create hard link New-Item -Path $source -ItemType HardLink -Value $target | Out-Null } } } } function unlink_persist_data($manifest, $dir) { $persist = $manifest.persist # unlink all junction / hard link in the directory if ($persist) { @($persist) | ForEach-Object { $source, $null = persist_def $_ $source = Get-Item "$dir\$source" -ErrorAction SilentlyContinue if ($source.LinkType) { $source_path = $source.FullName # directory (junction) if ($source -is [System.IO.DirectoryInfo]) { # remove read-only attribute on the link attrib -R /L $source_path # remove the junction Remove-Item -Path $source_path -Recurse -Force -ErrorAction SilentlyContinue } else { # remove the hard link Remove-Item -Path $source_path -Force -ErrorAction SilentlyContinue } } } } } # check whether write permission for Users usergroup is set to global persist dir, if not then set function persist_permission($manifest, $global) { if ($global -and $manifest.persist -and (is_admin)) { $path = persistdir $null $global $user = New-Object System.Security.Principal.SecurityIdentifier 'S-1-5-32-545' $target_rule = New-Object System.Security.AccessControl.FileSystemAccessRule($user, 'Write', 'ObjectInherit', 'none', 'Allow') $acl = Get-Acl -Path $path $acl.SetAccessRule($target_rule) $acl | Set-Acl -Path $path } } # test if there are running processes function test_running_process($app, $global) { $processdir = appdir $app $global | Convert-Path $running_processes = Get-Process | Where-Object { $_.Path -like "$processdir\*" } | Out-String if ($running_processes) { if (get_config IGNORE_RUNNING_PROCESSES) { warn "The following instances of `"$app`" are still running. Scoop is configured to ignore this condition." Write-Host $running_processes return $false } else { error "The following instances of `"$app`" are still running. Close them and try again." Write-Host $running_processes return $true } } else { return $false } } # wrapper function to create junction links # Required to handle docker/for-win#12240 function New-DirectoryJunction($source, $target) { # test if this script is being executed inside a docker container if (Get-Service -Name cexecsvc -ErrorAction SilentlyContinue) { cmd.exe /d /c "mklink /j `"$source`" `"$target`"" } else { New-Item -Path $source -ItemType Junction -Value $target } } ================================================ FILE: lib/json.ps1 ================================================ # Convert objects to pretty json # Only needed until PowerShell ConvertTo-Json will be improved https://github.com/PowerShell/PowerShell/issues/2736 # https://github.com/PowerShell/PowerShell/issues/2736 was fixed in pwsh # Still needed in normal powershell function ConvertToPrettyJson { [CmdletBinding()] Param ( [Parameter(Mandatory, ValueFromPipeline)] $data ) Process { $data = normalize_values $data # convert to string [String]$json = $data | ConvertTo-Json -Depth 8 -Compress [String]$output = '' # state [String]$buffer = '' [Int]$depth = 0 [Bool]$inString = $false # configuration [String]$indent = ' ' * 4 [Bool]$unescapeString = $true [String]$eol = "`r`n" for ($i = 0; $i -lt $json.Length; $i++) { # read current char $buffer = $json.Substring($i, 1) $objectStart = !$inString -and $buffer.Equals('{') $objectEnd = !$inString -and $buffer.Equals('}') $arrayStart = !$inString -and $buffer.Equals('[') $arrayEnd = !$inString -and $buffer.Equals(']') $colon = !$inString -and $buffer.Equals(':') $comma = !$inString -and $buffer.Equals(',') $quote = $buffer.Equals('"') $escape = $buffer.Equals('\') if ($quote) { $inString = !$inString } # skip escape sequences if ($escape) { $buffer = $json.Substring($i, 2) ++$i # Unescape unicode if ($inString -and $unescapeString) { if ($buffer.Equals('\n')) { $buffer = "`n" } elseif ($buffer.Equals('\r')) { $buffer = "`r" } elseif ($buffer.Equals('\t')) { $buffer = "`t" } elseif ($buffer.Equals('\u')) { $buffer = [regex]::Unescape($json.Substring($i - 1, 6)) $i += 4 } } $output += $buffer continue } # indent / outdent if ($objectStart -or $arrayStart) { ++$depth } elseif ($objectEnd -or $arrayEnd) { --$depth $output += $eol + ($indent * $depth) } # add content $output += $buffer # add whitespace and newlines after the content if ($colon) { $output += ' ' } elseif ($comma -or $arrayStart -or $objectStart) { $output += $eol $output += $indent * $depth } } return $output } } function json_path([String] $json, [String] $jsonpath, [Hashtable] $substitutions, [Boolean] $reverse, [Boolean] $single) { Add-Type -Path "$PSScriptRoot\..\supporting\validator\bin\Newtonsoft.Json.dll" if ($null -ne $substitutions) { $jsonpath = substitute $jsonpath $substitutions ($jsonpath -like "*=~*") } try { $settings = New-Object -Type Newtonsoft.Json.JsonSerializerSettings $settings.DateParseHandling = [Newtonsoft.Json.DateParseHandling]::None $obj = [Newtonsoft.Json.JsonConvert]::DeserializeObject($json, $settings) } catch [Newtonsoft.Json.JsonReaderException] { return $null } try { $result = $obj.SelectTokens($jsonpath, $true) if ($reverse) { # Return versions in reverse order $result = [System.Linq.Enumerable]::Reverse($result) } if ([System.Linq.Enumerable]::Count($result) -eq 1 -or $single) { # Extract First value $result = [System.Linq.Enumerable]::First($result) # Convert first value to string $result = $result.ToString() } else { $result = [Newtonsoft.Json.JsonConvert]::SerializeObject($result) } return $result } catch [Exception] { Write-Host $_ -ForegroundColor DarkRed } return $null } function json_path_legacy([String] $json, [String] $jsonpath, [Hashtable] $substitutions) { $result = $json | ConvertFrom-Json -ea stop $isJsonPath = $jsonpath.StartsWith('$') $jsonpath.split('.') | ForEach-Object { $el = $_ # substitute the basename and version varibales into the jsonpath if ($null -ne $substitutions) { $el = substitute $el $substitutions } # skip $ if it's jsonpath format if ($el -eq '$' -and $isJsonPath) { return } # array detection if ($el -match '^(?\w+)?\[(?\d+)\]$') { $property = $matches['property'] if ($property) { $result = $result.$property[$matches['index']] } else { $result = $result[$matches['index']] } return } $result = $result.$el } return $result } function normalize_values([psobject] $json) { # Iterate Through Manifest Properties $json.PSObject.Properties | ForEach-Object { # Recursively edit psobjects # If the values is psobjects, its not normalized # For example if manifest have architecture and it's architecture have array with single value it's not formatted. # @see https://github.com/ScoopInstaller/Scoop/pull/2642#issue-220506263 if ($_.Value -is [System.Management.Automation.PSCustomObject]) { $_.Value = normalize_values $_.Value } # Process String Values if ($_.Value -is [String]) { # Split on new lines [Array] $parts = ($_.Value -split '\r?\n').Trim() # Replace with string array if result is multiple lines if ($parts.Count -gt 1) { $_.Value = $parts } } # Convert single value array into string if ($_.Value -is [Array]) { # Array contains only 1 element String or Array if ($_.Value.Count -eq 1) { # Array if ($_.Value[0] -is [Array]) { $_.Value = $_.Value } else { # String $_.Value = $_.Value[0] } } else { # Array of Arrays $resulted_arrs = @() foreach ($element in $_.Value) { if ($element.Count -eq 1) { $resulted_arrs += $element } else { $resulted_arrs += , $element } } $_.Value = $resulted_arrs } } # Process other values as needed... } return $json } ================================================ FILE: lib/manifest.ps1 ================================================ function manifest_path($app, $bucket) { (Get-ChildItem (Find-BucketDirectory $bucket) -Filter "$(sanitary_path $app).json" -Recurse).FullName } function parse_json($path) { if ($null -eq $path -or !(Test-Path $path)) { return $null } try { Get-Content $path -Raw -Encoding UTF8 | ConvertFrom-Json -ErrorAction Stop } catch { warn "Error parsing JSON at '$path'." } } function url_manifest($url) { $str = $null try { $wc = New-Object Net.Webclient $wc.Headers.Add('User-Agent', (Get-UserAgent)) $data = $wc.DownloadData($url) $str = (Get-Encoding($wc)).GetString($data) } catch [system.management.automation.methodinvocationexception] { warn "error: $($_.exception.innerexception.message)" } catch { throw } if (!$str) { return $null } try { $str | ConvertFrom-Json -ErrorAction Stop } catch { warn "Error parsing JSON at '$url'." } } function Get-Manifest($app) { $bucket, $manifest, $url = $null $app = $app.TrimStart('/') # check if app is a URL or UNC path if ($app -match '^(ht|f)tps?://|\\\\') { $url = $app $app = appname_from_url $url $manifest = url_manifest $url } else { # Check if the manifest is already installed if (installed $app) { $global = installed $app $true $ver = Select-CurrentVersion -AppName $app -Global:$global if (!$ver) { $app, $bucket, $ver = parse_app $app $ver = Select-CurrentVersion -AppName $app -Global:$global } $install_info_path = "$(versiondir $app $ver $global)\install.json" if (Test-Path $install_info_path) { $install_info = parse_json $install_info_path $bucket = $install_info.bucket if (!$bucket) { $url = $install_info.url if ($url -match '^(ht|f)tps?://|\\\\') { $manifest = url_manifest $url } if (!$manifest) { if (Test-Path $url) { $manifest = parse_json $url } else { # Fallback to installed manifest $manifest = installed_manifest $app $ver $global } } } else { $manifest = manifest $app $bucket if (!$manifest) { $deprecated_dir = (Find-BucketDirectory -Name $bucket -Root) + '\deprecated' $manifest = parse_json (Get-ChildItem $deprecated_dir -Filter "$(sanitary_path $app).json" -Recurse).FullName } } } } else { $app, $bucket, $version = parse_app $app if ($bucket) { $manifest = manifest $app $bucket } else { $matched_buckets = @() foreach ($tekcub in Get-LocalBucket) { $current_manifest = manifest $app $tekcub if (!$manifest -and $current_manifest) { $manifest = $current_manifest $bucket = $tekcub } if ($current_manifest) { $matched_buckets += $tekcub } } } if (!$manifest) { # couldn't find app in buckets: check if it's a local path if (Test-Path $app) { $url = Convert-Path $app $app = appname_from_url $url $manifest = parse_json $url } else { if (($app -match '\\/') -or $app.EndsWith('.json')) { $url = $app } $app = appname_from_url $app } } } } if ($matched_buckets.Length -gt 1) { warn "Multiple buckets contain manifest '$app', the current selection is '$bucket/$app'." } return $app, $manifest, $bucket, $url } function manifest($app, $bucket, $url) { if ($url) { return url_manifest $url } parse_json (manifest_path $app $bucket) } function save_installed_manifest($app, $bucket, $dir, $url) { if ($url) { $wc = New-Object Net.Webclient $wc.Headers.Add('User-Agent', (Get-UserAgent)) $data = $wc.DownloadData($url) (Get-Encoding($wc)).GetString($data) | Out-UTF8File "$dir\manifest.json" } else { Copy-Item (manifest_path $app $bucket) "$dir\manifest.json" } } function installed_manifest($app, $version, $global) { parse_json "$(versiondir $app $version $global)\manifest.json" } function save_install_info($info, $dir) { $nulls = $info.keys | Where-Object { $null -eq $info[$_] } $nulls | ForEach-Object { $info.remove($_) } # strip null-valued $file_content = $info | ConvertToPrettyJson # in 'json.ps1' [System.IO.File]::WriteAllLines("$dir\install.json", $file_content) } function install_info($app, $version, $global) { $path = "$(versiondir $app $version $global)\install.json" if (!(Test-Path $path)) { return $null } parse_json $path } function arch_specific($prop, $manifest, $architecture) { if ($manifest.architecture) { $val = $manifest.architecture.$architecture.$prop if ($val) { return $val } # else fallback to generic prop } if ($manifest.$prop) { return $manifest.$prop } } function Get-SupportedArchitecture($manifest, $architecture) { if ($architecture -eq 'arm64' -and ($manifest | ConvertToPrettyJson) -notmatch '[''"]arm64["'']') { # Windows 10 enables existing unmodified x86 apps to run on Arm devices. # Windows 11 adds the ability to run unmodified x64 Windows apps on Arm devices! # Ref: https://learn.microsoft.com/en-us/windows/arm/overview if ($WindowsBuild -ge 22000) { # Windows 11 $architecture = '64bit' } else { # Windows 10 $architecture = '32bit' } } if (![String]::IsNullOrEmpty((arch_specific 'url' $manifest $architecture))) { return $architecture } } function generate_user_manifest($app, $bucket, $version) { # 'autoupdate.ps1' 'buckets.ps1' 'manifest.ps1' $app, $manifest, $bucket, $null = Get-Manifest "$bucket/$app" if ("$($manifest.version)" -eq "$version") { return manifest_path $app $bucket } warn "Given version ($version) does not match manifest ($($manifest.version))" warn "Attempting to generate manifest for '$app' ($version)" ensure (usermanifestsdir) | Out-Null $manifest_path = "$(usermanifestsdir)\$app.json" if (get_config USE_SQLITE_CACHE) { $cached_manifest = (Get-ScoopDBItem -Name $app -Bucket $bucket -Version $version).manifest if ($cached_manifest) { $cached_manifest | Out-UTF8File $manifest_path return $manifest_path } } if (!($manifest.autoupdate)) { abort "'$app' does not have autoupdate capability`r`ncouldn't find manifest for '$app@$version'" } try { Invoke-AutoUpdate $app $manifest_path $manifest $version $(@{ }) return $manifest_path } catch { Write-Host -ForegroundColor DarkRed "Could not install $app@$version" } return $null } function url($manifest, $arch) { arch_specific 'url' $manifest $arch } function installer($manifest, $arch) { arch_specific 'installer' $manifest $arch } function uninstaller($manifest, $arch) { arch_specific 'uninstaller' $manifest $arch } function hash($manifest, $arch) { arch_specific 'hash' $manifest $arch } function extract_dir($manifest, $arch) { arch_specific 'extract_dir' $manifest $arch } function extract_to($manifest, $arch) { arch_specific 'extract_to' $manifest $arch } ================================================ FILE: lib/psmodules.ps1 ================================================ function install_psmodule($manifest, $dir, $global) { $psmodule = $manifest.psmodule if (!$psmodule) { return } $targetdir = ensure (modulesdir $global) ensure_in_psmodulepath $targetdir $global $module_name = $psmodule.name if (!$module_name) { abort "Invalid manifest: The 'name' property is missing from 'psmodule'." } $linkfrom = "$targetdir\$module_name" Write-Host "Installing PowerShell module '$module_name'" Write-Host "Linking $(friendly_path $linkfrom) => $(friendly_path $dir)" if (Test-Path $linkfrom) { warn "$(friendly_path $linkfrom) already exists. It will be replaced." Remove-Item -Path $linkfrom -Force -Recurse -ErrorAction SilentlyContinue } New-DirectoryJunction $linkfrom $dir | Out-Null } function uninstall_psmodule($manifest, $dir, $global) { $psmodule = $manifest.psmodule if (!$psmodule) { return } $module_name = $psmodule.name Write-Host "Uninstalling PowerShell module '$module_name'." $targetdir = modulesdir $global $linkfrom = "$targetdir\$module_name" if (Test-Path $linkfrom) { Write-Host "Removing $(friendly_path $linkfrom)" $linkfrom = Convert-Path $linkfrom Remove-Item -Path $linkfrom -Force -Recurse -ErrorAction SilentlyContinue } } function ensure_in_psmodulepath($dir, $global) { $path = Get-EnvVar -Name 'PSModulePath' -Global:$global if (!$global -and $null -eq $path) { $path = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules" } if ($path -notmatch [Regex]::Escape($dir)) { Write-Output "Adding $(friendly_path $dir) to $(if($global){'global'}else{'your'}) PowerShell module path." Set-EnvVar -Name 'PSModulePath' -Value "$dir;$path" -Global:$global } } ================================================ FILE: lib/shortcuts.ps1 ================================================ # Creates shortcut for the app in the start menu function create_startmenu_shortcuts($manifest, $dir, $global, $arch) { $shortcuts = @(arch_specific 'shortcuts' $manifest $arch) $shortcuts | Where-Object { $_ -ne $null } | ForEach-Object { $target = [System.IO.Path]::Combine($dir, $_.item(0)) $target = New-Object System.IO.FileInfo($target) $name = $_.item(1) $arguments = '' $icon = $null if ($_.length -ge 3) { $arguments = $_.item(2) } if ($_.length -ge 4) { $icon = [System.IO.Path]::Combine($dir, $_.item(3)) $icon = New-Object System.IO.FileInfo($icon) } $arguments = (substitute $arguments @{ '$dir' = $dir; '$original_dir' = $original_dir; '$persist_dir' = $persist_dir }) startmenu_shortcut $target $name $arguments $icon $global } } function shortcut_folder($global) { if ($global) { $startmenu = 'CommonStartMenu' } else { $startmenu = 'StartMenu' } return Convert-Path (ensure ([System.IO.Path]::Combine([Environment]::GetFolderPath($startmenu), 'Programs', 'Scoop Apps'))) } function startmenu_shortcut([System.IO.FileInfo] $target, $shortcutName, $arguments, [System.IO.FileInfo]$icon, $global) { if (!$target.Exists) { Write-Host -f DarkRed "Creating shortcut for $shortcutName ($(fname $target)) failed: Couldn't find $target" return } if ($icon -and !$icon.Exists) { Write-Host -f DarkRed "Creating shortcut for $shortcutName ($(fname $target)) failed: Couldn't find icon $icon" return } $scoop_startmenu_folder = shortcut_folder $global $subdirectory = [System.IO.Path]::GetDirectoryName($shortcutName) if ($subdirectory) { $subdirectory = ensure $([System.IO.Path]::Combine($scoop_startmenu_folder, $subdirectory)) } $wsShell = New-Object -ComObject WScript.Shell $wsShell = $wsShell.CreateShortcut("$scoop_startmenu_folder\$shortcutName.lnk") $wsShell.TargetPath = $target.FullName $wsShell.WorkingDirectory = $target.DirectoryName if ($arguments) { $wsShell.Arguments = $arguments } if ($icon -and $icon.Exists) { $wsShell.IconLocation = $icon.FullName } $wsShell.Save() Write-Host "Creating shortcut for $shortcutName ($(fname $target))" } # Removes the Startmenu shortcut if it exists function rm_startmenu_shortcuts($manifest, $global, $arch) { $shortcuts = @(arch_specific 'shortcuts' $manifest $arch) $shortcuts | Where-Object { $_ -ne $null } | ForEach-Object { $name = $_.item(1) $shortcut = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$(shortcut_folder $global)\$name.lnk") Write-Host "Removing shortcut $(friendly_path $shortcut)" if (Test-Path -Path $shortcut) { Remove-Item $shortcut } } } ================================================ FILE: lib/system.ps1 ================================================ # System-related functions ## Environment Variables function Publish-EnvVar { if (-not ('Win32.NativeMethods' -as [Type])) { Add-Type -Namespace Win32 -Name NativeMethods -MemberDefinition @' [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout( IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult ); '@ } $HWND_BROADCAST = [IntPtr] 0xffff $WM_SETTINGCHANGE = 0x1a $result = [UIntPtr]::Zero [Win32.NativeMethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref] $result ) | Out-Null } function Get-EnvVar { param( [string]$Name, [switch]$Global ) $registerKey = if ($Global) { Get-Item -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager' } else { Get-Item -Path 'HKCU:' } $envRegisterKey = $registerKey.OpenSubKey('Environment') $registryValueOption = [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames $envRegisterKey.GetValue($Name, $null, $registryValueOption) } function Set-EnvVar { param( [string]$Name, [string]$Value, [switch]$Global ) $registerKey = if ($Global) { Get-Item -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager' } else { Get-Item -Path 'HKCU:' } $envRegisterKey = $registerKey.OpenSubKey('Environment', $true) if ($null -eq $Value -or $Value -eq '') { if ($envRegisterKey.GetValue($Name)) { $envRegisterKey.DeleteValue($Name) } } else { $registryValueKind = if ($Value.Contains('%')) { [Microsoft.Win32.RegistryValueKind]::ExpandString } elseif ($envRegisterKey.GetValue($Name)) { $envRegisterKey.GetValueKind($Name) } else { [Microsoft.Win32.RegistryValueKind]::String } $envRegisterKey.SetValue($Name, $Value, $registryValueKind) } Publish-EnvVar } function Split-PathLikeEnvVar { param( [string[]]$Pattern, [string]$Path ) if ($null -eq $Path -and $Path -eq '') { return $null, $null } else { $splitPattern = $Pattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries) $splitPath = $Path.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries) $inPath = @() foreach ($p in $splitPattern) { $inPath += $splitPath.Where({ $_ -like $p }) $splitPath = $splitPath.Where({ $_ -notlike $p }) } return ($inPath -join ';'), ($splitPath -join ';') } } function Add-Path { param( [string[]]$Path, [string]$TargetEnvVar = 'PATH', [switch]$Global, [switch]$Force, [switch]$Quiet ) # future sessions $inPath, $strippedPath = Split-PathLikeEnvVar $Path (Get-EnvVar -Name $TargetEnvVar -Global:$Global) if (!$inPath -or $Force) { if (!$Quiet) { $Path | ForEach-Object { Write-Host "Adding $(friendly_path $_) to $(if ($Global) {'global'} else {'your'}) path." } } Set-EnvVar -Name $TargetEnvVar -Value ((@($Path) + $strippedPath) -join ';') -Global:$Global } # current session $inPath, $strippedPath = Split-PathLikeEnvVar $Path $env:PATH if (!$inPath -or $Force) { $env:PATH = (@($Path) + $strippedPath) -join ';' } } function Remove-Path { param( [string[]]$Path, [string]$TargetEnvVar = 'PATH', [switch]$Global, [switch]$Quiet, [switch]$PassThru ) # future sessions $inPath, $strippedPath = Split-PathLikeEnvVar $Path (Get-EnvVar -Name $TargetEnvVar -Global:$Global) if ($inPath) { if (!$Quiet) { $Path | ForEach-Object { Write-Host "Removing $(friendly_path $_) from $(if ($Global) {'global'} else {'your'}) path." } } Set-EnvVar -Name $TargetEnvVar -Value $strippedPath -Global:$Global } # current session $inSessionPath, $strippedPath = Split-PathLikeEnvVar $Path $env:PATH if ($inSessionPath) { $env:PATH = $strippedPath } if ($PassThru) { return $inPath } } ## Deprecated functions function env($name, $global, $val) { if ($PSBoundParameters.ContainsKey('val')) { Show-DeprecatedWarning $MyInvocation 'Set-EnvVar' Set-EnvVar -Name $name -Value $val -Global:$global } else { Show-DeprecatedWarning $MyInvocation 'Get-EnvVar' Get-EnvVar -Name $name -Global:$global } } function strip_path($orig_path, $dir) { Show-DeprecatedWarning $MyInvocation 'Split-PathLikeEnvVar' Split-PathLikeEnvVar -Pattern @($dir) -Path $orig_path } function add_first_in_path($dir, $global) { Show-DeprecatedWarning $MyInvocation 'Add-Path' Add-Path -Path $dir -Global:$global -Force } function remove_from_path($dir, $global) { Show-DeprecatedWarning $MyInvocation 'Remove-Path' Remove-Path -Path $dir -Global:$global } ================================================ FILE: lib/versions.ps1 ================================================ function Get-LatestVersion { <# .SYNOPSIS Get latest version of app from manifest .PARAMETER AppName App's name .PARAMETER Bucket Bucket which the app belongs to .PARAMETER Uri Remote app manifest's URI #> [OutputType([String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [Alias('App')] [String] $AppName, [Parameter(Position = 1)] [String] $Bucket, [Parameter(Position = 2)] [String] $Uri ) process { return (manifest $AppName $Bucket $Uri).version } } function Select-CurrentVersion { # 'manifest.ps1' <# .SYNOPSIS Select current version of installed app, from 'current\manifest.json' or modified time of version directory .PARAMETER AppName App's name .PARAMETER Global Globally installed application #> [OutputType([String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [Alias('App')] [String] $AppName, [Parameter(Position = 1)] [Switch] $Global ) process { $currentPath = "$(appdir $AppName $Global)\current" if (!(get_config NO_JUNCTION)) { $currentVersion = (parse_json "$currentPath\manifest.json").version if ($currentVersion -eq 'nightly') { $currentVersion = (Get-Item $currentPath).Target | Split-Path -Leaf } } if ($null -eq $currentVersion) { $installedVersion = Get-InstalledVersion -AppName $AppName -Global:$Global if ($installedVersion) { $currentVersion = @($installedVersion)[-1] } else { $currentVersion = $null } } return $currentVersion } } function Get-InstalledVersion { <# .SYNOPSIS Get all installed version of app, by checking version directories' 'install.json' .PARAMETER AppName App's name .PARAMETER Global Globally installed application .NOTES Versions are sorted from oldest to newest, i.e., latest installed version is the last one in the output array. If no installed version found, empty array will be returned. #> [OutputType([Object[]])] [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [Alias('App')] [String] $AppName, [Parameter(Position = 1)] [Switch] $Global ) process { $appPath = appdir $AppName $Global if (Test-Path $appPath) { $versions = @((Get-ChildItem "$appPath\*\install.json" | Sort-Object -Property LastWriteTimeUtc).Directory.Name) return $versions | Where-Object { ($_ -ne 'current') -and ($_ -notlike '_*.old*') } } else { return @() } } # Deprecated # sort_versions (Get-ChildItem $appPath -dir -attr !reparsePoint | Where-Object { $null -ne $(Get-ChildItem $_.FullName) } | ForEach-Object { $_.Name }) } function Compare-Version { <# .SYNOPSIS Compare versions, mainly according to SemVer's rules .PARAMETER ReferenceVersion Specifies a version used as a reference for comparison .PARAMETER DifferenceVersion Specifies the version that are compared to the reference version .PARAMETER Delimiter Specifies the delimiter of versions .OUTPUTS System.Int32 '0' if DifferenceVersion is equal to ReferenceVersion, '1' if DifferenceVersion is greater then ReferenceVersion, '-1' if DifferenceVersion is less then ReferenceVersion #> [OutputType([Int32])] [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0)] [AllowEmptyString()] [String] $ReferenceVersion, [Parameter(Mandatory = $true, Position = 1, ValueFromPipeline = $true)] [AllowEmptyString()] [String] $DifferenceVersion, [String] $Delimiter = '-' ) process { # Use '+' sign as post-release, see https://github.com/ScoopInstaller/Scoop/pull/3721#issuecomment-553718093 $ReferenceVersion, $DifferenceVersion = @($ReferenceVersion, $DifferenceVersion) -replace '\+', '-' # Return 0 if versions are equal if ($DifferenceVersion -eq $ReferenceVersion) { return 0 } # Preprocess versions (split, convert and separate) $splitReferenceVersion = @(SplitVersion -Version $ReferenceVersion -Delimiter $Delimiter) $splitDifferenceVersion = @(SplitVersion -Version $DifferenceVersion -Delimiter $Delimiter) # Nightly versions are always equal unless UPDATE_NIGHTLY is $true if ($splitReferenceVersion[0] -eq 'nightly' -and $splitDifferenceVersion[0] -eq 'nightly') { if (get_config UPDATE_NIGHTLY) { # nightly versions will be compared by date if UPDATE_NIGHTLY is $true if ($null -eq $splitReferenceVersion[1]) { $splitReferenceVersion += Get-Date -Format 'yyyyMMdd' } if ($null -eq $splitDifferenceVersion[1]) { $splitDifferenceVersion += Get-Date -Format 'yyyyMMdd' } return [Math]::Sign($splitDifferenceVersion[1] - $splitReferenceVersion[1]) } else { return 0 } } for ($i = 0; $i -lt [Math]::Max($splitReferenceVersion.Length, $splitDifferenceVersion.Length); $i++) { # '1.1-alpha' is less then '1.1' if ($i -ge $splitReferenceVersion.Length) { if ($splitDifferenceVersion[$i] -match 'alpha|beta|rc|pre') { return -1 } else { return 1 } } # '1.1' is greater then '1.1-beta' if ($i -ge $splitDifferenceVersion.Length) { if ($splitReferenceVersion[$i] -match 'alpha|beta|rc|pre') { return 1 } else { return -1 } } # If some parts of versions have '.', compare them with delimiter '.' if (($splitReferenceVersion[$i] -match '\.') -or ($splitDifferenceVersion[$i] -match '\.')) { $Result = Compare-Version -ReferenceVersion $splitReferenceVersion[$i] -DifferenceVersion $splitDifferenceVersion[$i] -Delimiter '.' # If the parts are equal, continue to next part, otherwise return if ($Result -ne 0) { return $Result } else { continue } } # If some parts of versions have '_', compare them with delimiter '_' if (($splitReferenceVersion[$i] -match '_') -or ($splitDifferenceVersion[$i] -match '_')) { $Result = Compare-Version -ReferenceVersion $splitReferenceVersion[$i] -DifferenceVersion $splitDifferenceVersion[$i] -Delimiter '_' # If the parts are equal, continue to next part, otherwise return if ($Result -ne 0) { return $Result } else { continue } } # Don't try to compare [Long] to [String] if ($null -ne $splitReferenceVersion[$i] -and $null -ne $splitDifferenceVersion[$i]) { if ($splitReferenceVersion[$i] -is [String] -and $splitDifferenceVersion[$i] -isnot [String]) { $splitDifferenceVersion[$i] = "$($splitDifferenceVersion[$i])" } if ($splitDifferenceVersion[$i] -is [String] -and $splitReferenceVersion[$i] -isnot [String]) { $splitReferenceVersion[$i] = "$($splitReferenceVersion[$i])" } } # Compare [String] or [Long] if ($splitDifferenceVersion[$i] -gt $splitReferenceVersion[$i]) { return 1 } if ($splitDifferenceVersion[$i] -lt $splitReferenceVersion[$i]) { return -1 } } } } # Helper function function SplitVersion { <# .SYNOPSIS Split version by Delimiter, convert number string to number, and separate letters from numbers .PARAMETER Version Specifies a version .PARAMETER Delimiter Specifies the delimiter of version (Literal) #> [OutputType([Object[]])] [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)] [AllowEmptyString()] [String] $Version, [String] $Delimiter = '-' ) process { $Version = $Version -replace '[a-zA-Z]+', "$Delimiter$&$Delimiter" return ($Version -split [Regex]::Escape($Delimiter) -ne '' | ForEach-Object { if ($_ -match '^\d+$') { [Long]$_ } else { $_ } }) } } # Deprecated # Not used anymore in scoop core function qsort($ary, $fn) { warn '"qsort" is deprecated. Please avoid using it anymore.' if ($null -eq $ary) { return @() } if (!($ary -is [array])) { return @($ary) } $pivot = $ary[0] $rem = $ary[1..($ary.length - 1)] $lesser = qsort ($rem | Where-Object { (& $fn $pivot $_) -lt 0 }) $fn $greater = qsort ($rem | Where-Object { (& $fn $pivot $_) -ge 0 }) $fn return @() + $lesser + @($pivot) + $greater } # Deprecated # Not used anymore in scoop core function sort_versions($versions) { warn '"sort_versions" is deprecated. Please avoid using it anymore.' qsort $versions Compare-Version } function compare_versions($a, $b) { Show-DeprecatedWarning $MyInvocation 'Compare-Version' # Please note the parameters' sequence return Compare-Version -ReferenceVersion $b -DifferenceVersion $a } function latest_version($app, $bucket, $url) { Show-DeprecatedWarning $MyInvocation 'Get-LatestVersion' return Get-LatestVersion -AppName $app -Bucket $bucket -Uri $url } function current_version($app, $global) { Show-DeprecatedWarning $MyInvocation 'Select-CurrentVersion' return Select-CurrentVersion -AppName $app -Global:$global } function versions($app, $global) { Show-DeprecatedWarning $MyInvocation 'Get-InstalledVersion' return Get-InstalledVersion -AppName $app -Global:$global } ================================================ FILE: libexec/scoop-alias.ps1 ================================================ # Usage: scoop alias [options] [] # Summary: Manage scoop aliases # Help: Available subcommands: add, rm, list. # # Aliases are custom Scoop subcommands that can be created to make common tasks easier. # # To add an alias: # # scoop alias add [] # # e.g., # # scoop alias add rm 'scoop uninstall $args[0]' 'Uninstall an app' # scoop alias add upgrade 'scoop update *' 'Update all apps, just like "brew" or "apt"' # # To remove an alias: # # scoop alias rm # # To list all aliases: # # scoop alias list [-v|--verbose] # # Options: # -v, --verbose Show alias description and table headers (works only for "list") param($SubCommand) . "$PSScriptRoot\..\lib\getopt.ps1" $SubCommands = @('add', 'rm', 'list') if ($SubCommand -notin $SubCommands) { if (!$SubCommand) { error ' missing' } else { error "'$SubCommand' is not one of available subcommands: $($SubCommands -join ', ')" } my_usage exit 1 } $opt, $other, $err = getopt $Args 'v' 'verbose' if ($err) { "scoop alias: $err"; exit 1 } $name, $command, $description = $other $verbose = $opt.v -or $opt.verbose switch ($SubCommand) { 'add' { if (!$name -or !$command) { error " and must be specified for subcommand 'add'" exit 1 } add_alias $name $command $description } 'rm' { if (!$name) { error " must be specified for subcommand 'rm'" exit 1 } rm_alias $name } 'list' { list_aliases $verbose } } exit 0 ================================================ FILE: libexec/scoop-bucket.ps1 ================================================ # Usage: scoop bucket add|list|known|rm [] # Summary: Manage Scoop buckets # Help: Add, list or remove buckets. # # Buckets are repositories of apps available to install. Scoop comes with # a default bucket, but you can also add buckets that you or others have # published. # # To add a bucket: # scoop bucket add [] # # e.g.: # scoop bucket add extras https://github.com/ScoopInstaller/Extras.git # # Since the 'extras' bucket is known to Scoop, this can be shortened to: # scoop bucket add extras # # To list all known buckets, use: # scoop bucket known param($cmd, $name, $repo) if (get_config NO_JUNCTION) { . "$PSScriptRoot\..\lib\versions.ps1" } if (get_config USE_SQLITE_CACHE) { . "$PSScriptRoot\..\lib\manifest.ps1" . "$PSScriptRoot\..\lib\database.ps1" } $usage_add = 'usage: scoop bucket add []' $usage_rm = 'usage: scoop bucket rm ' switch ($cmd) { 'add' { if (!$name) { ' missing' $usage_add exit 1 } if (!$repo) { $repo = known_bucket_repo $name if (!$repo) { "Unknown bucket '$name'. Try specifying ." $usage_add exit 1 } } $status = add_bucket $name $repo exit $status } 'rm' { if (!$name) { ' missing' $usage_rm exit 1 } $status = rm_bucket $name exit $status } 'list' { $buckets = list_buckets if (!$buckets.Length) { warn "No bucket found. Please run 'scoop bucket add main' to add the default 'main' bucket." exit 2 } else { $buckets exit 0 } } 'known' { known_buckets exit 0 } default { "scoop bucket: cmd '$cmd' not supported" my_usage exit 1 } } ================================================ FILE: libexec/scoop-cache.ps1 ================================================ # Usage: scoop cache show|rm [app(s)] # Summary: Show or clear the download cache # Help: Scoop caches downloads so you don't need to download the same files # when you uninstall and re-install the same version of an app. # # You can use # scoop cache show # to see what's in the cache, and # scoop cache rm to remove downloads for a specific app. # # To clear everything in your cache, use: # scoop cache rm * # You can also use the `-a/--all` switch in place of `*` here param($cmd) function cacheinfo($file) { $app, $version, $url = $file.Name -split '#' New-Object PSObject -Property @{ Name = $app; Version = $version; Length = $file.Length } } function cacheshow($app) { if (!$app -or $app -eq '*') { $app = '.*?' } else { $app = '(' + ($app -join '|') + ')' } $files = @(Get-ChildItem $cachedir | Where-Object -Property Name -Value "^$app#" -Match) $totalLength = ($files | Measure-Object -Property Length -Sum).Sum $files | ForEach-Object { cacheinfo $_ } | Select-Object Name, Version, Length Write-Host "Total: $($files.Length) $(pluralize $files.Length 'file' 'files'), $(filesize $totalLength)" -ForegroundColor Yellow } function cacheremove($app) { if (!$app) { 'ERROR: missing' my_usage exit 1 } elseif ($app -eq '*' -or $app -eq '-a' -or $app -eq '--all') { $files = @(Get-ChildItem $cachedir) } else { $app = '(' + ($app -join '|') + ')' $files = @(Get-ChildItem $cachedir | Where-Object -Property Name -Value "^$app#" -Match) } $totalLength = ($files | Measure-Object -Property Length -Sum).Sum $files | ForEach-Object { $curr = cacheinfo $_ Write-Host "Removing $($_.Name)..." Remove-Item $_.FullName if(Test-Path "$cachedir\$($curr.Name).txt") { Remove-Item "$cachedir\$($curr.Name).txt" } } Write-Host "Deleted: $($files.Length) $(pluralize $files.Length 'file' 'files'), $(filesize $totalLength)" -ForegroundColor Yellow } switch($cmd) { 'rm' { cacheremove $Args } 'show' { cacheshow $Args } default { cacheshow (@($cmd) + $Args) } } exit 0 ================================================ FILE: libexec/scoop-cat.ps1 ================================================ # Usage: scoop cat # Summary: Show content of specified manifest. # Help: Show content of specified manifest. # If configured, `bat` will be used to pretty-print the JSON. # See `cat_style` in `scoop help config` for further information. param($app) . "$PSScriptRoot\..\lib\json.ps1" # 'ConvertToPrettyJson' . "$PSScriptRoot\..\lib\versions.ps1" # 'Select-CurrentVersion' . "$PSScriptRoot\..\lib\manifest.ps1" # 'Get-Manifest' . "$PSScriptRoot\..\lib\download.ps1" # 'Get-UserAgent' if (!$app) { error ' missing'; my_usage; exit 1 } $null, $manifest, $bucket, $url = Get-Manifest $app if ($manifest) { $style = get_config CAT_STYLE if ($style) { $manifest | ConvertToPrettyJson | bat --no-paging --style $style --language json } else { $manifest | ConvertToPrettyJson } } else { abort "Couldn't find manifest for '$app'$(if($bucket) { " from '$bucket' bucket" } elseif($url) { " at '$url'" })." } exit $exitCode ================================================ FILE: libexec/scoop-checkup.ps1 ================================================ # Usage: scoop checkup # Summary: Check for potential problems # Help: Performs a series of diagnostic tests to try to identify things that may # cause problems with Scoop. . "$PSScriptRoot\..\lib\diagnostic.ps1" $issues = 0 $defenderIssues = 0 $adminPrivileges = ([System.Security.Principal.WindowsPrincipal] [System.Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator) if ($adminPrivileges -and $env:USERNAME -ne 'WDAGUtilityAccount') { $defenderIssues += !(check_windows_defender $false) $defenderIssues += !(check_windows_defender $true) } $issues += !(check_main_bucket) $issues += !(check_long_paths) $issues += !(Get-WindowsDeveloperModeStatus) if (!(Test-HelperInstalled -Helper 7zip) -and !(get_config USE_EXTERNAL_7ZIP)) { warn "'7-Zip' is not installed! It's required for unpacking most programs. Please Run 'scoop install 7zip'." $issues++ } if (!(Test-HelperInstalled -Helper Innounp)) { warn "'Inno Setup Unpacker' is not installed! It's required for unpacking InnoSetup files. Please run 'scoop install innounp'." $issues++ } if (!(Test-HelperInstalled -Helper Dark)) { warn "'dark' is not installed! It's required for unpacking installers created with the WiX Toolset. Please run 'scoop install dark' or 'scoop install wixtoolset'." $issues++ } $globaldir = New-Object System.IO.DriveInfo($globaldir) if ($globaldir.DriveFormat -ne 'NTFS') { error "Scoop requires an NTFS volume to work! Please point `$env:SCOOP_GLOBAL or 'global_path' variable in '~/.config/scoop/config.json' to another Drive." $issues++ } $scoopdir = New-Object System.IO.DriveInfo($scoopdir) if ($scoopdir.DriveFormat -ne 'NTFS') { error "Scoop requires an NTFS volume to work! Please point `$env:SCOOP or 'root_path' variable in '~/.config/scoop/config.json' to another Drive." $issues++ } if ($issues) { warn "Found $issues potential $(pluralize $issues problem problems)." } elseif ($defenderIssues) { info "Found $defenderIssues performance $(pluralize $defenderIssues problem problems)." warn "Security is more important than performance, in most cases." } else { success "No problems identified!" } exit 0 ================================================ FILE: libexec/scoop-cleanup.ps1 ================================================ # Usage: scoop cleanup [options] # Summary: Cleanup apps by removing old versions # Help: 'scoop cleanup' cleans Scoop apps by removing old versions. # 'scoop cleanup ' cleans up the old versions of that app if said versions exist. # # You can use '*' in place of or `-a`/`--all` switch to cleanup all apps. # # Options: # -a, --all Cleanup all apps (alternative to '*') # -g, --global Cleanup a globally installed app # -k, --cache Remove outdated download cache . "$PSScriptRoot\..\lib\getopt.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" # 'Select-CurrentVersion' (indirectly) . "$PSScriptRoot\..\lib\versions.ps1" # 'Select-CurrentVersion' . "$PSScriptRoot\..\lib\install.ps1" # persist related $opt, $apps, $err = getopt $args 'agk' 'all', 'global', 'cache' if ($err) { "scoop cleanup: $err"; exit 1 } $global = $opt.g -or $opt.global $cache = $opt.k -or $opt.cache $all = $opt.a -or $opt.all if (!$apps -and !$all) { 'ERROR: missing'; my_usage; exit 1 } if ($global -and !(is_admin)) { 'ERROR: you need admin rights to cleanup global apps'; exit 1 } function cleanup($app, $global, $verbose, $cache) { $current_version = Select-CurrentVersion -AppName $app -Global:$global if ($cache) { Remove-Item "$cachedir\$app#*" -Exclude "$app#$current_version#*" } $appDir = appdir $app $global $versions = Get-ChildItem $appDir -Name $versions = $versions | Where-Object { $current_version -ne $_ -and $_ -ne 'current' } if (!$versions) { if ($verbose) { success "$app is already clean" } return } Write-Host -f yellow "Removing $app`:" -NoNewline $versions | ForEach-Object { $version = $_ Write-Host " $version" -NoNewline $dir = versiondir $app $version $global # unlink all potential old link before doing recursive Remove-Item unlink_persist_data (installed_manifest $app $version $global) $dir Remove-Item $dir -ErrorAction Stop -Recurse -Force } $leftVersions = Get-ChildItem $appDir if ($leftVersions.Length -eq 1 -and $leftVersions.Name -eq 'current' -and $leftVersions.LinkType) { attrib $leftVersions.FullName -R /L Remove-Item $leftVersions.FullName -ErrorAction Stop -Force $leftVersions = $null } if (!$leftVersions) { Remove-Item $appDir -ErrorAction Stop -Force } Write-Host '' } if ($apps -or $all) { if ($apps -eq '*' -or $all) { $verbose = $false $apps = applist (installed_apps $false) $false if ($global) { $apps += applist (installed_apps $true) $true } } else { $verbose = $true $apps = Confirm-InstallationStatus $apps -Global:$global } # $apps is now a list of ($app, $global) tuples $apps | ForEach-Object { cleanup @_ $verbose $cache } if ($cache) { Remove-Item "$cachedir\*.download" -ErrorAction Ignore } if (!$verbose) { success 'Everything is shiny now!' } } exit 0 ================================================ FILE: libexec/scoop-config.ps1 ================================================ # Usage: scoop config [rm] name [value] # Summary: Get or set configuration values # Help: The scoop configuration file is saved at ~/.config/scoop/config.json. # # To get all configuration settings: # # scoop config # # To get a configuration setting: # # scoop config # # To set a configuration setting: # # scoop config # # To remove a configuration setting: # # scoop config rm # # Settings # -------- # # use_external_7zip: $true|$false # External 7zip (from path) will be used for archives extraction. # # use_lessmsi: $true|$false # Prefer lessmsi utility over native msiexec. # # use_sqlite_cache: $true|$false # Use SQLite database for caching. This is useful for speeding up 'scoop search' and 'scoop shim' commands. # # no_junction: $true|$false # The 'current' version alias will not be used. Shims and shortcuts will point to specific version instead. # # scoop_repo: http://github.com/ScoopInstaller/Scoop # Git repository containining scoop source code. # This configuration is useful for custom forks. # # scoop_branch: master|develop # Allow to use different branch than master. # Could be used for testing specific functionalities before released into all users. # If you want to receive updates earlier to test new functionalities use develop (see: 'https://github.com/ScoopInstaller/Scoop/issues/2939') # # proxy: [username:password@]host:port # By default, Scoop will use the proxy settings from Internet Options, but with anonymous authentication. # # * To use the credentials for the current logged-in user, use 'currentuser' in place of username:password # * To use the system proxy settings configured in Internet Options, use 'default' in place of host:port # * An empty or unset value for proxy is equivalent to 'default' (with no username or password) # * To bypass the system proxy and connect directly, use 'none' (with no username or password) # # autostash_on_conflict: $true|$false # When a conflict is detected during updating, Scoop will auto-stash the uncommitted changes. # (Default is $false, which will abort the update) # # default_architecture: 64bit|32bit|arm64 # Allow to configure preferred architecture for application installation. # If not specified, architecture is determined by system. # # debug: $true|$false # Additional and detailed output will be shown. # # force_update: $true|$false # Force apps updating to bucket's version. # # show_update_log: $true|$false # Do not show changed commits on 'scoop update' # # show_manifest: $true|$false # Displays the manifest of every app that's about to # be installed, then asks user if they wish to proceed. # # shim: kiennq|scoopcs|71 # Choose scoop shim build. # # root_path: $Env:UserProfile\scoop # Path to Scoop root directory. # # global_path: $Env:ProgramData\scoop # Path to Scoop root directory for global apps. # # cache_path: # For downloads, defaults to 'cache' folder under Scoop root directory. # # gh_token: # GitHub API token used to make authenticated requests. # This is essential for checkver and similar functions to run without # incurring rate limits and download from private repositories. # # virustotal_api_key: # API key used for uploading/scanning files using virustotal. # See: 'https://support.virustotal.com/hc/en-us/articles/115002088769-Please-give-me-an-API-key' # # cat_style: # When set to a non-empty string, Scoop will use 'bat' to display the manifest for # the `scoop cat` command and while doing manifest review. This requires 'bat' to be # installed (run `scoop install bat` to install it), otherwise errors will be thrown. # The accepted values are the same as ones passed to the --style flag of 'bat'. # # ignore_running_processes: $true|$false # When set to $false (default), Scoop would stop its procedure immediately if it detects # any target app process is running. Procedure here refers to reset/uninstall/update. # When set to $true, Scoop only displays a warning message and continues procedure. # # private_hosts: # Array of private hosts that need additional authentication. # For example, if you want to access a private GitHub repository, # you need to add the host to this list with 'match' and 'headers' strings. # # hold_update_until: # Disable/Hold Scoop self-updates, until the specified date. # `scoop hold scoop` will set the value to one day later. # Should be in the format 'YYYY-MM-DD', 'YYYY/MM/DD' or any other forms that accepted by '[System.DateTime]::Parse()'. # Ref: https://docs.microsoft.com/dotnet/api/system.datetime.parse?view=netframework-4.5#StringToParse # # update_nightly: $true|$false # Nightly version is formatted as 'nightly-yyyyMMdd' and will be updated after one day if this is set to $true. # Otherwise, nightly version will not be updated unless `--force` is used. # # use_isolated_path: $true|$false|[string] # When set to $true, Scoop will use `SCOOP_PATH` environment variable to store apps' `PATH`s. # When set to arbitrary non-empty string, Scoop will use that string as the environment variable name instead. # This is useful when you want to isolate Scoop from the system `PATH`. # # ARIA2 configuration # ------------------- # # aria2-enabled: $true|$false # Aria2c will be used for downloading of artifacts. # # aria2-warning-enabled: $true|$false # Disable Aria2c warning which is shown while downloading. # # aria2-retry-wait: 2 # Number of seconds to wait between retries. # See: 'https://aria2.github.io/manual/en/html/aria2c.html#cmdoption-retry-wait' # # aria2-split: 5 # Number of connections used for downlaod. # See: 'https://aria2.github.io/manual/en/html/aria2c.html#cmdoption-s' # # aria2-max-connection-per-server: 5 # The maximum number of connections to one server for each download. # See: 'https://aria2.github.io/manual/en/html/aria2c.html#cmdoption-x' # # aria2-min-split-size: 5M # Downloaded files will be splitted by this configured size and downloaded using multiple connections. # See: 'https://aria2.github.io/manual/en/html/aria2c.html#cmdoption-k' # # aria2-options: # Array of additional aria2 options. # See: 'https://aria2.github.io/manual/en/html/aria2c.html#options' param($name, $value) if (!$name) { $scoopConfig } elseif ($name -like '--help') { my_usage } elseif ($name -like 'rm') { set_config $value $null | Out-Null Write-Host "'$value' has been removed" } elseif ($null -ne $value) { set_config $name $value | Out-Null Write-Host "'$name' has been set to '$value'" } else { $value = get_config $name if($null -eq $value) { Write-Host "'$name' is not set" } else { if ($value -is [System.DateTime]) { $value.ToString('o') } else { $value } } } exit 0 ================================================ FILE: libexec/scoop-create.ps1 ================================================ # Usage: scoop create # Summary: Create a custom app manifest # Help: Create your own custom app manifest param($url) function create_manifest($url) { $manifest = new_manifest $manifest.url = $url $url_parts = $null try { $url_parts = parse_url $url } catch { abort "Error: $url is not a valid URL" } $name = choose_item $url_parts 'App name' $name = if ($name.Length -gt 0) { $name } else { file_name ($url_parts | Select-Object -Last 1) } $manifest.version = choose_item $url_parts 'Version' $manifest | ConvertTo-Json | Out-File -FilePath "$name.json" -Encoding ASCII $manifest_path = Join-Path $pwd "$name.json" Write-Host "Created '$manifest_path'." } function new_manifest() { @{ 'homepage' = ''; 'license' = ''; 'version' = ''; 'url' = ''; 'hash' = ''; 'extract_dir' = ''; 'bin' = ''; 'depends' = '' } } function file_name($segment) { $segment.substring(0, $segment.lastindexof('.')) } function parse_url($url) { $uri = New-Object Uri $url $uri.pathandquery.substring(1).split('/') } function choose_item($list, $query) { for ($i = 0; $i -lt $list.count; $i++) { $item = $list[$i] Write-Host "$($i + 1)) $item" } $sel = Read-Host $query if ($sel.trim() -match '^[0-9+]$') { return $list[$sel - 1] } $sel } if (!$url) { & "$PSScriptRoot\scoop-help.ps1" create } else { create_manifest $url } exit 0 ================================================ FILE: libexec/scoop-depends.ps1 ================================================ # Usage: scoop depends # Summary: List dependencies for an app, in the order they'll be installed . "$PSScriptRoot\..\lib\getopt.ps1" . "$PSScriptRoot\..\lib\depends.ps1" # 'Get-Dependency' . "$PSScriptRoot\..\lib\versions.ps1" # 'Select-CurrentVersion' . "$PSScriptRoot\..\lib\manifest.ps1" # 'Get-Manifest' (indirectly) . "$PSScriptRoot\..\lib\download.ps1" # 'Get-UserAgent' $opt, $apps, $err = getopt $args 'a:' 'arch=' $app = $apps[0] if(!$app) { error ' missing'; my_usage; exit 1 } $architecture = Get-DefaultArchitecture try { $architecture = Format-ArchitectureString ($opt.a + $opt.arch) } catch { abort "ERROR: $_" } $deps = @() Get-Dependency $app $architecture | ForEach-Object { $dep = [ordered]@{} $app, $null, $bucket, $url = Get-Manifest $_ if (!$url) { $bucket, $app = $_ -split '/' } $dep.Source = if ($url) { $url } else { $bucket } $dep.Name = $app $deps += [PSCustomObject]$dep } $deps exit 0 ================================================ FILE: libexec/scoop-download.ps1 ================================================ # Usage: scoop download [options] # Summary: Download apps in the cache folder and verify hashes # Help: e.g. The usual way to download an app, without installing it (uses your local 'buckets'): # scoop download git # # To download a different version of the app # (note that this will auto-generate the manifest using current version): # scoop download gh@2.7.0 # # To download an app from a manifest at a URL: # scoop download https://raw.githubusercontent.com/ScoopInstaller/Main/master/bucket/runat.json # # To download an app from a manifest on your computer # scoop download path\to\app.json # # Options: # -f, --force Force download (overwrite cache) # -s, --skip-hash-check Skip hash verification (use with caution!) # -u, --no-update-scoop Don't update Scoop before downloading if it's outdated # -a, --arch <32bit|64bit|arm64> Use the specified architecture, if the app supports it . "$PSScriptRoot\..\lib\getopt.ps1" . "$PSScriptRoot\..\lib\json.ps1" # 'autoupdate.ps1' (indirectly) . "$PSScriptRoot\..\lib\autoupdate.ps1" # 'generate_user_manifest' (indirectly) . "$PSScriptRoot\..\lib\versions.ps1" # 'Select-CurrentVersion' . "$PSScriptRoot\..\lib\manifest.ps1" # 'generate_user_manifest' 'Get-Manifest' . "$PSScriptRoot\..\lib\download.ps1" if (get_config USE_SQLITE_CACHE) { . "$PSScriptRoot\..\lib\database.ps1" } $opt, $apps, $err = getopt $args 'fsua:' 'force', 'skip-hash-check', 'no-update-scoop', 'arch=' if ($err) { error "scoop download: $err"; exit 1 } $check_hash = !($opt.s -or $opt.'skip-hash-check') $use_cache = !($opt.f -or $opt.force) $architecture = Get-DefaultArchitecture try { $architecture = Format-ArchitectureString ($opt.a + $opt.arch) } catch { abort "ERROR: $_" } if (!$apps) { error ' missing'; my_usage; exit 1 } if (is_scoop_outdated) { if ($opt.u -or $opt.'no-update-scoop') { warn "Scoop is out of date." } else { & "$PSScriptRoot\scoop-update.ps1" } } # we only want to show this warning once if(!$use_cache) { warn "Cache is being ignored." } foreach ($curr_app in $apps) { # Prevent leaking variables from previous iteration $bucket = $version = $app = $manifest = $url = $null $app, $bucket, $version = parse_app $curr_app $app, $manifest, $bucket, $url = Get-Manifest "$bucket/$app" info "Downloading '$app'$(if ($version) { " ($version)" }) [$architecture]$(if ($bucket) { " from $bucket bucket" })" # Generate manifest if there is different version in manifest if (($null -ne $version) -and ($manifest.version -ne $version)) { $generated = generate_user_manifest $app $bucket $version if ($null -eq $generated) { error 'Manifest cannot be generated with provided version' continue } $manifest = parse_json($generated) } if(!$manifest) { error "Couldn't find manifest for '$app'$(if($bucket) { " from '$bucket' bucket" } elseif($url) { " at '$url'" })." continue } $version = $manifest.version if(!$version) { error "Manifest doesn't specify a version." continue } if($version -match '[^\w\.\-\+_]') { error "Manifest version has unsupported character '$($matches[0])'." continue } $curr_check_hash = $check_hash if ($version -eq 'nightly') { $version = nightly_version $curr_check_hash = $false } $architecture = Get-SupportedArchitecture $manifest $architecture if ($null -eq $architecture) { error "'$app' doesn't support current architecture!" continue } if(Test-Aria2Enabled) { Invoke-CachedAria2Download $app $version $manifest $architecture $cachedir $manifest.cookie $use_cache $curr_check_hash } else { foreach($url in script:url $manifest $architecture) { try { Invoke-CachedDownload $app $version $url $null $manifest.cookie $use_cache } catch { write-host -f darkred $_ error "URL $url is not valid" $dl_failure = $true continue } if($curr_check_hash) { $manifest_hash = hash_for_url $manifest $url $architecture $cached = cache_path $app $version $url $ok, $err = check_hash $cached $manifest_hash (show_app $app $bucket) if(!$ok) { error $err if(test-path $cached) { # rm cached file Remove-Item -force $cached } if ($url -like '*sourceforge.net*') { warn 'SourceForge.net is known for causing hash validation fails. Please try again before opening a ticket.' } error (new_issue_msg $app $bucket "hash check failed") continue } } else { info "Skipping hash verification." } } } if (!$dl_failure) { success "'$app' ($version) was downloaded successfully!" } } exit 0 ================================================ FILE: libexec/scoop-export.ps1 ================================================ # Usage: scoop export > scoopfile.json # Summary: Exports installed apps, buckets (and optionally configs) in JSON format # Help: Options: # -c, --config Export the Scoop configuration file too . "$PSScriptRoot\..\lib\json.ps1" # 'ConvertToPrettyJson' $export = @{} if ($args[0] -eq '-c' -or $args[0] -eq '--config') { $export.config = $scoopConfig # Remove machine-specific properties foreach ($prop in 'last_update', 'root_path', 'global_path', 'cache_path', 'alias') { $export.config.PSObject.Properties.Remove($prop) } } $export.buckets = list_buckets $export.apps = @(& "$PSScriptRoot\scoop-list.ps1" 6>$null) $export | ConvertToPrettyJSON exit 0 ================================================ FILE: libexec/scoop-help.ps1 ================================================ # Usage: scoop help # Summary: Show help for a command param($cmd) function print_help($cmd) { $file = Get-Content (command_path $cmd) -Raw $usage = usage $file $help = scoop_help $file if ($usage) { "$usage`n" } if ($help) { $help } } function print_summaries { $commands = @() command_files | ForEach-Object { $command = [ordered]@{} $command.Command = command_name $_ $command.Summary = summary (Get-Content (command_path $command.Command)) $commands += [PSCustomObject]$command } $commands } $commands = commands if(!($cmd)) { Write-Host "Usage: scoop [] Available commands are listed below. Type 'scoop help ' to get more help for a specific command." print_summaries } elseif($commands -contains $cmd) { print_help $cmd } else { warn "scoop help: no such command '$cmd'" exit 1 } exit 0 ================================================ FILE: libexec/scoop-hold.ps1 ================================================ # Usage: scoop hold # Summary: Hold an app to disable updates # Help: To hold a user-scoped app: # scoop hold # # To hold a global app: # scoop hold -g # # Options: # -g, --global Hold globally installed apps . "$PSScriptRoot\..\lib\getopt.ps1" . "$PSScriptRoot\..\lib\json.ps1" # 'save_install_info' (indirectly) . "$PSScriptRoot\..\lib\manifest.ps1" # 'install_info' 'Select-CurrentVersion' (indirectly) . "$PSScriptRoot\..\lib\versions.ps1" # 'Select-CurrentVersion' $opt, $apps, $err = getopt $args 'g' 'global' if ($err) { "scoop hold: $err"; exit 1 } $global = $opt.g -or $opt.global if (!$apps) { my_usage exit 1 } if ($global -and !(is_admin)) { error 'You need admin rights to hold a global app.' exit 1 } foreach ($app in $apps) { if ($app -eq 'scoop') { $hold_update_until = [System.DateTime]::Now.AddDays(1) set_config HOLD_UPDATE_UNTIL $hold_update_until.ToString('o') | Out-Null success "$app is now held and might not be updated until $($hold_update_until.ToLocalTime())." continue } if (!(installed $app $global)) { if ($global) { error "'$app' is not installed globally." } else { error "'$app' is not installed." } continue } if (get_config NO_JUNCTION) { $version = Select-CurrentVersion -App $app -Global:$global } else { $version = 'current' } $dir = versiondir $app $version $global $json = install_info $app $version $global if (!$json) { error "Failed to hold '$app'." continue } $install = @{} $json | Get-Member -MemberType Properties | ForEach-Object { $install.Add($_.Name, $json.($_.Name)) } if ($install.hold) { info "'$app' is already held." continue } $install.hold = $true save_install_info $install $dir success "$app is now held and can not be updated anymore." } exit $exitcode ================================================ FILE: libexec/scoop-home.ps1 ================================================ # Usage: scoop home # Summary: Opens the app homepage param($app) . "$PSScriptRoot\..\lib\versions.ps1" # 'Select-CurrentVersion' . "$PSScriptRoot\..\lib\manifest.ps1" # 'Get-Manifest' . "$PSScriptRoot\..\lib\download.ps1" # 'Get-UserAgent' if ($app) { $null, $manifest, $bucket, $null = Get-Manifest $app if ($manifest) { if ($manifest.homepage) { Start-Process $manifest.homepage } else { abort "Could not find homepage in manifest for '$app'." } } else { abort "Could not find manifest for '$app'." } } else { my_usage exit 1 } exit 0 ================================================ FILE: libexec/scoop-import.ps1 ================================================ # Usage: scoop import # Summary: Imports apps, buckets and configs from a Scoopfile in JSON format # Help: To replicate a Scoop installation from a file stored on Desktop, run # scoop import Desktop\scoopfile.json param( [Parameter(Mandatory)] [String] $scoopfile ) . "$PSScriptRoot\..\lib\manifest.ps1" $import = $null $bucket_names = @() $def_arch = Get-DefaultArchitecture if (Test-Path $scoopfile) { $import = parse_json $scoopfile } elseif ($scoopfile -match '^(ht|f)tps?://|\\\\') { $import = url_manifest $scoopfile } if (!$import) { abort 'Input file not a valid JSON.' } foreach ($item in $import.config.PSObject.Properties) { set_config $item.Name $item.Value | Out-Null Write-Host "'$($item.Name)' has been set to '$($item.Value)'" } foreach ($item in $import.buckets) { add_bucket $item.Name $item.Source | Out-Null $bucket_names += $item.Name } foreach ($item in $import.apps) { $instArgs = @() $holdArgs = @() $info = $item.Info -Split ', ' if ('Global install' -in $info) { $instArgs += '--global' $holdArgs += '--global' } if ('64bit' -in $info -and '64bit' -ne $def_arch) { $instArgs += '--arch', '64bit' } elseif ('32bit' -in $info -and '32bit' -ne $def_arch) { $instArgs += '--arch', '32bit' } elseif ('arm64' -in $info -and 'arm64' -ne $def_arch) { $instArgs += '--arch', 'arm64' } $app = if ($item.Source -in $bucket_names) { "$($item.Source)/$($item.Name)" } elseif ($item.Source -eq '') { "$($item.Name)@$($item.Version)" } else { $item.Source } & "$PSScriptRoot\scoop-install.ps1" $app @instArgs if ('Held package' -in $info) { & "$PSScriptRoot\scoop-hold.ps1" $item.Name @holdArgs } } ================================================ FILE: libexec/scoop-info.ps1 ================================================ # Usage: scoop info [options] # Summary: Display information about an app # Help: Options: # -v, --verbose Show full paths and URLs . "$PSScriptRoot\..\lib\getopt.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" # 'Get-Manifest' . "$PSScriptRoot\..\lib\versions.ps1" # 'Get-InstalledVersion', 'Select-CurrentVersion' . "$PSScriptRoot\..\lib\download.ps1" # 'Get-RemoteFileSize' $opt, $app, $err = getopt $args 'v' 'verbose' $original_app = $app if ($err) { error "scoop info: $err"; exit 1 } $verbose = $opt.v -or $opt.verbose if (!$app) { my_usage; exit 1 } $app, $manifest, $bucket, $url = Get-Manifest $app if (!$manifest) { abort "Could not find manifest for '$(show_app $app)' in local buckets." } $global = installed $app $true $status = app_status $app $global $install = install_info $app $status.version $global $status.installed = ($bucket -and $install.bucket -eq $bucket) -or (installed $app) $version_output = $manifest.version $manifest_file = if ($bucket) { manifest_path $app $bucket } else { $url } # Standalone and Source detection if ((Test-Path $original_app) -or ($original_app -match '^(ht|f)tps?://|\\\\')) { $standalone = $true if (Test-Path $original_app) { $original_app = (Get-AbsolutePath "$original_app") } if ($install.url) { if (Test-Path $install.url) { $install_url = (Get-AbsolutePath $install.url) } else { $install_url = $install.url } } if ($original_app -eq $install_url) { $same_source = $true } } if ($verbose) { $dir = currentdir $app $global $original_dir = versiondir $app $manifest.version $global $persist_dir = persistdir $app $global } else { $dir, $original_dir, $persist_dir = '', '', '' } if ($status.installed) { $manifest_file = manifest_path $app $install.bucket if ($install.url) { $manifest_file = $install.url } if ($status.deprecated) { $manifest_file = $status.deprecated } elseif ($standalone -and !$same_source) { $version_output = $manifest.version } elseif ($status.version -eq $manifest.version) { $version_output = $status.version } else { $version_output = "$($status.version) (Update to $($manifest.version) available)" } } $item = [ordered]@{ Name = $app } if ($status.deprecated) { $item.Name += ' (DEPRECATED)' } if ($manifest.description) { $item.Description = $manifest.description } $item.Version = $version_output $item.Source = if ($standalone) { $original_app } else { if ($install.bucket) { $install.bucket } elseif ($install.url) { $install.url } else { $bucket } } if ($manifest.homepage) { $item.Website = $manifest.homepage.TrimEnd('/') } # Show license if ($manifest.license) { $item.License = if ($manifest.license.identifier -and $manifest.license.url) { if ($verbose) { "$($manifest.license.identifier) ($($manifest.license.url))" } else { $manifest.license.identifier } } elseif ($manifest.license -match '^((ht)|f)tps?://') { $manifest.license } elseif ($manifest.license -match '[|,]') { if ($verbose) { "$($manifest.license) ($(($manifest.license -Split '\||,' | ForEach-Object { "https://spdx.org/licenses/$_.html" }) -join ', '))" } else { $manifest.license } } else { if ($verbose) { "$($manifest.license) (https://spdx.org/licenses/$($manifest.license).html)" } else { $manifest.license } } } if ($manifest.depends) { $item.Dependencies = $manifest.depends -join ' | ' } if (Test-Path $manifest_file) { if (Get-Command git -ErrorAction Ignore) { $gitinfo = (Invoke-Git -Path (Split-Path $manifest_file) -ArgumentList @('log', '-1', '-s', '--format=%aD#%an', $manifest_file) 2> $null) -Split '#' } if ($gitinfo) { $item.'Updated at' = $gitinfo[0] | Get-Date $item.'Updated by' = $gitinfo[1] } else { $item.'Updated at' = (Get-Item $manifest_file).LastWriteTime $item.'Updated by' = (Get-Acl $manifest_file).Owner.Split('\')[-1] } } # Manifest file if ($verbose) { $item.Manifest = $manifest_file } if ($status.installed) { # Show installed versions if (!$standalone -or $same_source) { $installed_output = @() Get-InstalledVersion -AppName $app -Global:$global | ForEach-Object { $installed_output += if ($verbose) { versiondir $app $_ $global } else { "$_$(if ($global) { ' *global*' })" } } $item.Installed = $installed_output -join "`n" } if ($verbose) { # Show size of installation $appsdir = appsdir $global # Collect file list from each location $appFiles = Get-ChildItem $appsdir -Filter $app $currentFiles = Get-ChildItem $appFiles.FullName -Filter (Select-CurrentVersion $app $global) $persistFiles = Get-ChildItem $persist_dir -ErrorAction Ignore # Will fail if app does not persist data $cacheFiles = Get-ChildItem $cachedir -Filter "$app#*" # Get the sum of each file list $fileTotals = @() foreach ($fileType in ($appFiles, $currentFiles, $persistFiles, $cacheFiles)) { if ($null -ne $fileType) { $fileSum = (Get-ChildItem $fileType.FullName -Recurse -File | Measure-Object -Property Length -Sum).Sum $fileTotals += coalesce $fileSum 0 } else { $fileTotals += 0 } } # Old versions = app total - current version size $fileTotals += $fileTotals[0] - $fileTotals[1] if ($fileTotals[2] + $fileTotals[3] + $fileTotals[4] -eq 0) { # Simple app size output if no old versions, persisted data, cached downloads $item.'Installed size' = filesize $fileTotals[1] } else { $fileSizes = [ordered] @{ 'Current version: ' = $fileTotals[1] 'Old versions: ' = $fileTotals[4] 'Persisted data: ' = $fileTotals[2] 'Cached downloads: ' = $fileTotals[3] 'Total: ' = $fileTotals[0] + $fileTotals[2] + $fileTotals[3] } $fileSizeOutput = @() # Don't output empty categories $fileSizes.GetEnumerator() | ForEach-Object { if ($_.Value -ne 0) { $fileSizeOutput += $_.Key + (filesize $_.Value) } } $item.'Installed size' = $fileSizeOutput -join "`n" } } } else { if ($verbose) { # Get download size if app not installed $totalPackage = 0 foreach ($url in @(url $manifest (Get-DefaultArchitecture))) { try { if (Test-Path (cache_path $app $manifest.version $url)) { $cached = ' (latest version is cached)' } else { $cached = $null } $urlLength = Get-RemoteFileSize $url $totalPackage += $urlLength } catch [System.Management.Automation.RuntimeException] { $totalPackage = 0 $packageError = "the server at $(([System.Uri]$url).Host) did not send a Content-Length header" break } catch { $totalPackage = 0 $packageError = "the server at $(([System.Uri]$url).Host) is down" break } } if ($totalPackage -ne 0) { $item.'Download size' = "$(filesize $totalPackage)$cached" } else { $item.'Download size' = "Unknown ($packageError)$cached" } } } $binaries = @(arch_specific 'bin' $manifest $install.architecture) if ($binaries) { $binary_output = @() $binaries | ForEach-Object { if ($_ -is [System.Array]) { $binary_output += "$($_[1]).$($_[0].Split('.')[-1])" } else { $binary_output += $_ } } $item.Binaries = $binary_output -join ' | ' } $shortcuts = @(arch_specific 'shortcuts' $manifest $install.architecture) if ($shortcuts) { $shortcut_output = @() $shortcuts | ForEach-Object { $shortcut_output += $_[1] } $item.Shortcuts = $shortcut_output -join ' | ' } $env_set = arch_specific 'env_set' $manifest $install.architecture if ($env_set) { $env_vars = @() $env_set | Get-Member -member noteproperty | ForEach-Object { $env_vars += "$($_.name) = $(substitute $env_set.$($_.name) @{ '$dir' = $dir })" } $item.Environment = $env_vars -join "`n" } $env_add_path = arch_specific 'env_add_path' $manifest $install.architecture if ($env_add_path) { $env_path = @() $env_add_path | Where-Object { $_ } | ForEach-Object { $env_path += if ($_ -eq '.') { $dir } else { "$dir\$_" } } $item.'Path Added' = $env_path -join "`n" } if ($manifest.suggest) { $suggest_output = @() $manifest.suggest.PSObject.Properties | ForEach-Object { $suggest_output += $_.Value -join ' | ' } $item.Suggestions = $suggest_output -join ' | ' } if ($manifest.notes) { # Show notes $item.Notes = (substitute $manifest.notes @{ '$dir' = $dir; '$original_dir' = $original_dir; '$persist_dir' = $persist_dir }) -join "`n" } [PSCustomObject]$item exit 0 ================================================ FILE: libexec/scoop-install.ps1 ================================================ # Usage: scoop install [options] # Summary: Install apps # Help: e.g. The usual way to install an app (uses your local 'buckets'): # scoop install git # # To install a different version of the app # (note that this will auto-generate the manifest using current version): # scoop install gh@2.7.0 # # To install an app from a manifest at a URL: # scoop install https://raw.githubusercontent.com/ScoopInstaller/Main/master/bucket/runat.json # # To install a different version of the app from a URL: # scoop install https://raw.githubusercontent.com/ScoopInstaller/Main/master/bucket/neovim.json@0.9.0 # # To install an app from a manifest on your computer # scoop install \path\to\app.json # # To install an app from a manifest on your computer # scoop install \path\to\app.json@version # # Options: # -g, --global Install the app globally # -i, --independent Don't install dependencies automatically # -k, --no-cache Don't use the download cache # -s, --skip-hash-check Skip hash validation (use with caution!) # -u, --no-update-scoop Don't update Scoop before installing if it's outdated # -a, --arch <32bit|64bit|arm64> Use the specified architecture, if the app supports it . "$PSScriptRoot\..\lib\getopt.ps1" . "$PSScriptRoot\..\lib\json.ps1" # 'autoupdate.ps1' 'manifest.ps1' (indirectly) . "$PSScriptRoot\..\lib\autoupdate.ps1" # 'generate_user_manifest' (indirectly) . "$PSScriptRoot\..\lib\manifest.ps1" # 'generate_user_manifest' 'Get-Manifest' 'Select-CurrentVersion' (indirectly) . "$PSScriptRoot\..\lib\system.ps1" . "$PSScriptRoot\..\lib\install.ps1" . "$PSScriptRoot\..\lib\download.ps1" . "$PSScriptRoot\..\lib\decompress.ps1" . "$PSScriptRoot\..\lib\shortcuts.ps1" . "$PSScriptRoot\..\lib\psmodules.ps1" . "$PSScriptRoot\..\lib\versions.ps1" . "$PSScriptRoot\..\lib\depends.ps1" if (get_config USE_SQLITE_CACHE) { . "$PSScriptRoot\..\lib\database.ps1" } $opt, $apps, $err = getopt $args 'giksua:' 'global', 'independent', 'no-cache', 'skip-hash-check', 'no-update-scoop', 'arch=' if ($err) { "scoop install: $err"; exit 1 } $global = $opt.g -or $opt.global $check_hash = !($opt.s -or $opt.'skip-hash-check') $independent = $opt.i -or $opt.independent $use_cache = !($opt.k -or $opt.'no-cache') $architecture = Get-DefaultArchitecture try { $architecture = Format-ArchitectureString ($opt.a + $opt.arch) } catch { abort "ERROR: $_" } if (!$apps) { error ' missing'; my_usage; exit 1 } if ($global -and !(is_admin)) { abort 'ERROR: you need admin rights to install global apps' } if (is_scoop_outdated) { if ($opt.u -or $opt.'no-update-scoop') { warn "Scoop is out of date." } else { & "$PSScriptRoot\scoop-update.ps1" } } ensure_none_failed $apps if ($apps.length -eq 1) { $app, $null, $version = parse_app $apps if ($app.EndsWith('.json')) { $app = [System.IO.Path]::GetFileNameWithoutExtension($app) } $curVersion = Select-CurrentVersion -AppName $app -Global:$global if ($null -eq $version -and $curVersion) { warn "'$app' ($curVersion) is already installed.`nUse 'scoop update $app$(if ($global) { ' --global' })' to install a new version." exit 0 } } # get any specific versions that we need to handle first $specific_versions = $apps | Where-Object { $null, $null, $version = parse_app $_ return $null -ne $version } # compare object does not like nulls if ($specific_versions.Count -gt 0) { $difference = Compare-Object -ReferenceObject $apps -DifferenceObject $specific_versions -PassThru } else { $difference = $apps } $specific_versions_paths = $specific_versions | ForEach-Object { $app, $bucket, $version = parse_app $_ if (installed_manifest $app $version) { warn "'$app' ($version) is already installed.`nUse 'scoop update $app$(if ($global) { ' --global' })' to install a new version." continue } generate_user_manifest $app $bucket $version } $apps = @((@($specific_versions_paths) + $difference) | Where-Object { $_ } | Select-Object -Unique) # remember which were explictly requested so that we can # differentiate after dependencies are added $explicit_apps = $apps if (!$independent) { $apps = $apps | Get-Dependency -Architecture $architecture | Select-Object -Unique # adds dependencies } ensure_none_failed $apps $apps, $skip = prune_installed $apps $global $skip | Where-Object { $explicit_apps -contains $_ } | ForEach-Object { $app, $null, $null = parse_app $_ $version = Select-CurrentVersion -AppName $app -Global:$global warn "'$app' ($version) is already installed. Skipping." } $suggested = @{ }; if ((Test-Aria2Enabled) -and (get_config 'aria2-warning-enabled' $true)) { warn "Scoop uses 'aria2c' for multi-connection downloads." warn "Should it cause issues, run 'scoop config aria2-enabled false' to disable it." warn "To disable this warning, run 'scoop config aria2-warning-enabled false'." } $apps | ForEach-Object { install_app $_ $architecture $global $suggested $use_cache $check_hash } show_suggestions $suggested exit 0 ================================================ FILE: libexec/scoop-list.ps1 ================================================ # Usage: scoop list [query] # Summary: List installed apps # Help: Lists all installed apps, or the apps matching the supplied query. param($query) . "$PSScriptRoot\..\lib\versions.ps1" # 'Select-CurrentVersion' . "$PSScriptRoot\..\lib\manifest.ps1" # 'parse_json' 'Select-CurrentVersion' (indirectly) . "$PSScriptRoot\..\lib\download.ps1" # 'Get-UserAgent' $defaultArchitecture = Get-DefaultArchitecture if (-not (Get-FormatData ScoopApps)) { Update-FormatData "$PSScriptRoot\..\supporting\formats\ScoopTypes.Format.ps1xml" } $local = installed_apps $false | ForEach-Object { @{ name = $_ } } $global = installed_apps $true | ForEach-Object { @{ name = $_; global = $true } } $apps = @($local) + @($global) if (-not $apps) { Write-Host "There aren't any apps installed." exit 1 } $list = @() Write-Host "Installed apps$(if($query) { `" matching '$query'`"}):" $apps | Where-Object { !$query -or ($_.name -match $query) } | ForEach-Object { $app = $_.name $global = $_.global $item = @{} $ver = Select-CurrentVersion -AppName $app -Global:$global $item.Name = $app $item.Version = $ver $install_info_path = "$(versiondir $app $ver $global)\install.json" $updated = (Get-Item (appdir $app $global)).LastWriteTime $install_info = $null if (Test-Path $install_info_path) { $install_info = parse_json $install_info_path $updated = (Get-Item $install_info_path).LastWriteTime } $item.Source = if ($install_info.bucket) { $install_info.bucket } elseif ($install_info.url) { if ($install_info.url -eq (usermanifest $app)) { '' } else { $install_info.url } } $item.Updated = $updated $info = @() if ((app_status $app $global).deprecated) { $info += 'Deprecated package'} if ($global) { $info += 'Global install' } if (failed $app $global) { $info += 'Install failed' } if ($install_info.hold) { $info += 'Held package' } if ($install_info.architecture -and $defaultArchitecture -ne $install_info.architecture) { $info += $install_info.architecture } $item.Info = $info -join ', ' $list += [PSCustomObject]$item } $list | Add-Member -TypeName 'ScoopApps' -PassThru exit 0 ================================================ FILE: libexec/scoop-prefix.ps1 ================================================ # Usage: scoop prefix # Summary: Returns the path to the specified app param($app) . "$PSScriptRoot\..\lib\versions.ps1" # 'currentdir' (indirectly) if (!$app) { my_usage exit 1 } $app_path = currentdir $app $false if (!(Test-Path $app_path)) { $app_path = currentdir $app $true } if (Test-Path $app_path) { Write-Output $app_path } else { abort "Could not find app path for '$app'." } exit 0 ================================================ FILE: libexec/scoop-reset.ps1 ================================================ # Usage: scoop reset # Summary: Reset an app to resolve conflicts # Help: Used to resolve conflicts in favor of a particular app. For example, # if you've installed 'python' and 'python27', you can use 'scoop reset' to switch between # using one or the other. # # You can use '*' in place of or `-a`/`--all` switch to reset all apps. . "$PSScriptRoot\..\lib\getopt.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" # 'Select-CurrentVersion' (indirectly) . "$PSScriptRoot\..\lib\system.ps1" # 'env_add_path' (indirectly) . "$PSScriptRoot\..\lib\install.ps1" . "$PSScriptRoot\..\lib\versions.ps1" # 'Select-CurrentVersion' . "$PSScriptRoot\..\lib\shortcuts.ps1" $opt, $apps, $err = getopt $args 'a' 'all' if($err) { "scoop reset: $err"; exit 1 } $all = $opt.a -or $opt.all if(!$apps -and !$all) { error ' missing'; my_usage; exit 1 } if($apps -eq '*' -or $all) { $local = installed_apps $false | ForEach-Object { ,@($_, $false) } $global = installed_apps $true | ForEach-Object { ,@($_, $true) } $apps = @($local) + @($global) } $apps | ForEach-Object { ($app, $global) = $_ $app, $bucket, $version = parse_app $app if(($global -eq $null) -and (installed $app $true)) { # set global flag when running reset command on specific app $global = $true } if($app -eq 'scoop') { # skip scoop return } if(!(installed $app)) { error "'$app' isn't installed" return } if ($null -eq $version) { $version = Select-CurrentVersion -AppName $app -Global:$global } $manifest = installed_manifest $app $version $global # if this is null we know the version they're resetting to # is not installed if ($manifest -eq $null) { error "'$app ($version)' isn't installed" return } if($global -and !(is_admin)) { warn "'$app' ($version) is a global app. You need admin rights to reset it. Skipping." return } write-host "Resetting $app ($version)." $dir = Convert-Path (versiondir $app $version $global) $original_dir = $dir $persist_dir = persistdir $app $global #region Workaround for #2952 if (test_running_process $app $global) { return } #endregion Workaround for #2952 $install = install_info $app $version $global $architecture = $install.architecture $dir = link_current $dir create_shims $manifest $dir $global $architecture create_startmenu_shortcuts $manifest $dir $global $architecture # unset all potential old env before re-adding env_rm_path $manifest $dir $global $architecture env_rm $manifest $global $architecture env_add_path $manifest $dir $global $architecture env_set $manifest $global $architecture # unlink all potential old link before re-persisting unlink_persist_data $manifest $original_dir persist_data $manifest $original_dir $persist_dir persist_permission $manifest $global } exit 0 ================================================ FILE: libexec/scoop-search.ps1 ================================================ # Usage: scoop search # Summary: Search available apps # Help: Searches for apps that are available to install. # # If used with [query], shows app names that match the query. # - With 'use_sqlite_cache' enabled, [query] is partially matched against app names, binaries, and shortcuts. # - Without 'use_sqlite_cache', [query] can be a regular expression to match against app names and binaries. # Without [query], shows all the available apps. param($query) . "$PSScriptRoot\..\lib\manifest.ps1" # 'manifest' . "$PSScriptRoot\..\lib\versions.ps1" # 'Get-LatestVersion' . "$PSScriptRoot\..\lib\download.ps1" $list = [System.Collections.Generic.List[PSCustomObject]]::new() function bin_match($manifest, $query) { if (!$manifest.bin) { return $false } $bins = foreach ($bin in $manifest.bin) { $exe, $alias, $args = $bin $fname = Split-Path $exe -Leaf -ErrorAction Stop if ((strip_ext $fname) -match $query) { $fname } elseif ($alias -match $query) { $alias } } if ($bins) { return $bins } else { return $false } } function bin_match_json($json, $query) { [System.Text.Json.JsonElement]$bin = [System.Text.Json.JsonElement]::new() if (!$json.RootElement.TryGetProperty('bin', [ref] $bin)) { return $false } $bins = @() if ($bin.ValueKind -eq [System.Text.Json.JsonValueKind]::String -and [System.IO.Path]::GetFileNameWithoutExtension($bin) -match $query) { $bins += [System.IO.Path]::GetFileName($bin) } elseif ($bin.ValueKind -eq [System.Text.Json.JsonValueKind]::Array) { foreach ($subbin in $bin.EnumerateArray()) { if ($subbin.ValueKind -eq [System.Text.Json.JsonValueKind]::String -and [System.IO.Path]::GetFileNameWithoutExtension($subbin) -match $query) { $bins += [System.IO.Path]::GetFileName($subbin) } elseif ($subbin.ValueKind -eq [System.Text.Json.JsonValueKind]::Array) { if ([System.IO.Path]::GetFileNameWithoutExtension($subbin[0]) -match $query) { $bins += [System.IO.Path]::GetFileName($subbin[0]) } elseif ($subbin.GetArrayLength() -ge 2 -and $subbin[1] -match $query) { $bins += $subbin[1] } } } } if ($bins) { return $bins } else { return $false } } function search_bucket($bucket, $query) { $apps = Get-ChildItem (Find-BucketDirectory $bucket) -Filter '*.json' -Recurse $apps | ForEach-Object { $filepath = $_.FullName $json = try { [System.Text.Json.JsonDocument]::Parse([System.IO.File]::ReadAllText($filepath)) } catch { debug "Failed to parse manifest file: $filepath (error: $_)" return } $name = $_.BaseName if ($name -match $query) { $list.Add([PSCustomObject]@{ Name = $name Version = $json.RootElement.GetProperty('version') Source = $bucket Binaries = '' }) } else { $bin = bin_match_json $json $query if ($bin) { $list.Add([PSCustomObject]@{ Name = $name Version = $json.RootElement.GetProperty('version') Source = $bucket Binaries = $bin -join ' | ' }) } } } } # fallback function for PowerShell 5 function search_bucket_legacy($bucket, $query) { $apps = Get-ChildItem (Find-BucketDirectory $bucket) -Filter '*.json' -Recurse $apps | ForEach-Object { $manifest = [System.IO.File]::ReadAllText($_.FullName) | ConvertFrom-Json -ErrorAction Continue $name = $_.BaseName if ($name -match $query) { $list.Add([PSCustomObject]@{ Name = $name Version = $manifest.Version Source = $bucket Binaries = '' }) } else { $bin = bin_match $manifest $query if ($bin) { $list.Add([PSCustomObject]@{ Name = $name Version = $manifest.Version Source = $bucket Binaries = $bin -join ' | ' }) } } } } function search_remote($bucket, $query) { $uri = [System.Uri](known_bucket_repo $bucket) if ($uri.AbsolutePath -match '/([a-zA-Z0-9]*)/([a-zA-Z0-9-]*)(?:.git|/)?') { $user = $Matches[1] $repo_name = $Matches[2] $api_link = "https://api.github.com/repos/$user/$repo_name/git/trees/HEAD?recursive=1" $result = download_json $api_link | Select-Object -ExpandProperty tree | Where-Object -Value "^bucket/(.*$query.*)\.json$" -Property Path -Match | ForEach-Object { $Matches[1] } } $result } function search_remotes($query) { $buckets = known_bucket_repos $names = $buckets | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty name $results = $names | Where-Object { !(Test-Path $(Find-BucketDirectory $_)) } | ForEach-Object { @{ 'bucket' = $_; 'results' = (search_remote $_ $query) } } | Where-Object { $_.results } if ($results.count -gt 0) { Write-Host "Results from other known buckets... (add them using 'scoop bucket add ')" } $remote_list = @() $results | ForEach-Object { $bucket = $_.bucket $_.results | ForEach-Object { $item = [ordered]@{} $item.Name = $_ $item.Source = $bucket $remote_list += [PSCustomObject]$item } } $remote_list } if (get_config USE_SQLITE_CACHE) { . "$PSScriptRoot\..\lib\database.ps1" Select-ScoopDBItem $query -From @('name', 'binary', 'shortcut') | Select-Object -Property name, version, bucket, binary | ForEach-Object { $list.Add([PSCustomObject]@{ Name = $_.name Version = $_.version Source = $_.bucket Binaries = $_.binary }) } } else { try { $query = New-Object Regex $query, 'IgnoreCase' } catch { abort "Invalid regular expression: $($_.Exception.InnerException.Message)" } $jsonTextAvailable = [System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { [System.IO.Path]::GetFileNameWithoutExtension($_.Location) -eq 'System.Text.Json' } Get-LocalBucket | ForEach-Object { if ($jsonTextAvailable) { search_bucket $_ $query } else { search_bucket_legacy $_ $query } } } if ($list.Count -gt 0) { Write-Host 'Results from local buckets...' $list } if ($list.Count -eq 0 -and !(github_ratelimit_reached)) { $remote_results = search_remotes $query if (!$remote_results) { warn 'No matches found.' exit 1 } $remote_results } exit 0 ================================================ FILE: libexec/scoop-shim.ps1 ================================================ # Usage: scoop shim [...] [options] [other_args] # Summary: Manipulate Scoop shims # Help: Available subcommands: add, rm, list, info, alter. # # To add a custom shim, use the 'add' subcommand: # # scoop shim add [...] # # To remove shims, use the 'rm' subcommand: (CAUTION: this could remove shims added by an app manifest) # # scoop shim rm [...] # # To list all shims or matching shims, use the 'list' subcommand: # # scoop shim list [...] # # To show a shim's information, use the 'info' subcommand: # # scoop shim info # # To alternate a shim's target source, use the 'alter' subcommand: # # scoop shim alter # # Options: # -g, --global Manipulate global shim(s) # # HINT: The FIRST double-hyphen '--', if any, will be treated as the POSIX-style command option terminator # and will NOT be included in arguments, so if you want to pass arguments like '-g' or '--global' to # the shim, put them after a '--'. Note that in PowerShell, you must use a QUOTED '--', e.g., # # scoop shim add myapp 'D:\path\myapp.exe' '--' myapp_args --global param($SubCommand) . "$PSScriptRoot\..\lib\getopt.ps1" . "$PSScriptRoot\..\lib\install.ps1" # for rm_shim . "$PSScriptRoot\..\lib\system.ps1" # 'Add-Path' (indirectly) if ($SubCommand -notin @('add', 'rm', 'list', 'info', 'alter')) { if (!$SubCommand) { error ' missing' } else { error "'$SubCommand' is not one of available subcommands: add, rm, list, info, alter" } my_usage exit 1 } $opt, $other, $err = getopt $Args 'g' 'global' if ($err) { "scoop shim: $err"; exit 1 } $global = $opt.g -or $opt.global if ($SubCommand -ne 'list' -and $other.Length -eq 0) { error " must be specified for subcommand '$SubCommand'" my_usage exit 1 } if (-not (Get-FormatData ScoopShims)) { Update-FormatData "$PSScriptRoot\..\supporting\formats\ScoopTypes.Format.ps1xml" } $localShimDir = shimdir $false $globalShimDir = shimdir $true function Get-ShimInfo($ShimPath) { $info = [Ordered]@{} $info.Name = strip_ext (fname $ShimPath) $info.Path = $ShimPath -replace 'shim$', 'exe' $info.Source = (get_app_name_from_shim $ShimPath) -replace '^$', 'External' $info.Type = if ($ShimPath.EndsWith('.ps1')) { 'ExternalScript' } else { 'Application' } $altShims = Get-Item -Path "$ShimPath.*" -Exclude '*.shim', '*.cmd', '*.ps1' if ($altShims) { $info.Alternatives = (@($info.Source) + ($altShims | ForEach-Object { $_.Extension.Remove(0, 1) } | Select-Object -Unique)) -join ' ' } $info.IsGlobal = $ShimPath.StartsWith("$globalShimDir") $info.IsHidden = !((Get-Command -Name $info.Name).Path -eq $info.Path) [PSCustomObject]$info } function Get-ShimPath($ShimName, $Global) { '.shim', '.ps1' | ForEach-Object { $shimPath = Join-Path (shimdir $Global) "$ShimName$_" if (Test-Path -LiteralPath $shimPath) { return $shimPath } } } switch ($SubCommand) { 'add' { if ($other.Length -lt 2 -or $other[1] -eq '') { error " must be specified for subcommand 'add'" my_usage exit 1 } $shimName = $other[0] $commandPath = $other[1] if ($other.Length -gt 2) { $commandArgs = $other[2..($other.Length - 1)] } if ($commandPath -notmatch '[\\/]') { $shortPath = $commandPath $commandPath = Get-ShimTarget (Get-ShimPath $shortPath $global) if (!$commandPath) { $exCommand = Get-Command $shortPath -ErrorAction SilentlyContinue if ($exCommand -and $exCommand.CommandType -eq 'Application') { $commandPath = $exCommand.Path } # TODO - add support for more command types: Alias, Cmdlet, ExternalScript, Filter, Function, Script, and Workflow } } if ($commandPath -and (Test-Path $commandPath)) { Write-Host "Adding $(if ($global) { 'global' } else { 'local' }) shim " -NoNewline Write-Host $shimName -ForegroundColor Cyan -NoNewline Write-Host '...' shim $commandPath $global $shimName $commandArgs } else { Write-Host "ERROR: Command path does not exist: " -ForegroundColor Red -NoNewline Write-Host $($other[1]) -ForegroundColor Cyan exit 3 } } 'rm' { $failed = @() $other | ForEach-Object { if (Get-ShimPath $_ $global) { rm_shim $_ (shimdir $global) } else { $failed += $_ } } if ($failed) { $failed | ForEach-Object { Write-Host "ERROR: $(if ($global) { 'Global' } else {'Local' }) shim not found: " -ForegroundColor Red -NoNewline Write-Host $_ -ForegroundColor Cyan } exit 3 } } 'list' { $other = @($other) -ne '*' # Validate all given patterns before matching. $other | ForEach-Object { try { $pattern = $_ [void][Regex]::New($pattern) } catch { Write-Host "ERROR: Invalid pattern: " -ForegroundColor Red -NoNewline Write-Host $pattern -ForegroundColor Magenta exit 1 } } $pattern = $other -join '|' $shims = @() if (!$global) { $shims += Get-ChildItem -Path $localShimDir -Recurse -Include '*.shim', '*.ps1' | Where-Object { !$pattern -or ($_.BaseName -match $pattern) } | Select-Object -ExpandProperty FullName } if (Test-Path $globalShimDir) { $shims += Get-ChildItem -Path $globalShimDir -Recurse -Include '*.shim', '*.ps1' | Where-Object { !$pattern -or ($_.BaseName -match $pattern) } | Select-Object -ExpandProperty FullName } $shims.ForEach({ Get-ShimInfo $_ }) | Add-Member -TypeName 'ScoopShims' -PassThru } 'info' { $shimName = $other[0] $shimPath = Get-ShimPath $shimName $global if ($shimPath) { Get-ShimInfo $shimPath } else { Write-Host "ERROR: $(if ($global) { 'Global' } else { 'Local' }) shim not found: " -ForegroundColor Red -NoNewline Write-Host $shimName -ForegroundColor Cyan if (Get-ShimPath $shimName (!$global)) { Write-Host "But a $(if ($global) { 'local' } else {'global' }) shim exists, " -NoNewline Write-Host "run 'scoop shim info $shimName$(if (!$global) { ' --global' })' to show its info" exit 2 } exit 3 } } 'alter' { $shimName = $other[0] $shimPath = Get-ShimPath $shimName $global if ($shimPath) { $shimInfo = Get-ShimInfo $shimPath if ($null -eq $shimInfo.Alternatives) { Write-Host 'ERROR: No alternatives of ' -ForegroundColor Red -NoNewline Write-Host $shimName -ForegroundColor Cyan -NoNewline Write-Host ' found.' -ForegroundColor Red exit 2 } $shimInfo.Alternatives = $shimInfo.Alternatives.Split(' ') [System.Management.Automation.Host.ChoiceDescription[]]$altApps = 1..$shimInfo.Alternatives.Length | ForEach-Object { New-Object System.Management.Automation.Host.ChoiceDescription "&$($_)`b$($shimInfo.Alternatives[$_ - 1])", "Sets '$shimName' shim from $($shimInfo.Alternatives[$_ - 1])." } $selected = $Host.UI.PromptForChoice("Alternatives of '$shimName' command", "Please choose one that provides '$shimName' as default:", $altApps, 0) if ($selected -eq 0) { Write-Host 'INFO: ' -ForegroundColor Blue -NoNewline Write-Host $shimName -ForegroundColor Cyan -NoNewline Write-Host ' is already from ' -NoNewline Write-Host $shimInfo.Source -ForegroundColor DarkYellow -NoNewline Write-Host ', nothing changed.' } else { $newApp = $shimInfo.Alternatives[$selected] Write-Host 'Use ' -NoNewline Write-Host $shimName -ForegroundColor Cyan -NoNewline Write-Host ' from ' -NoNewline Write-Host $newApp -ForegroundColor DarkYellow -NoNewline Write-Host ' as default...' -NoNewline $pathNoExt = strip_ext $shimPath '', '.shim', '.cmd', '.ps1' | ForEach-Object { $oldShimPath = "$pathNoExt$_" $newShimPath = "$oldShimPath.$newApp" if (Test-Path -Path $oldShimPath -PathType Leaf) { Rename-Item -Path $oldShimPath -NewName "$oldShimPath.$($shimInfo.Source)" -Force if (Test-Path -Path $newShimPath -PathType Leaf) { Rename-Item -Path $newShimPath -NewName $oldShimPath -Force } } } Write-Host 'done.' } } else { Write-Host "ERROR: $(if ($global) { 'Global' } else { 'Local' }) shim not found: " -ForegroundColor Red -NoNewline Write-Host $shimName -ForegroundColor Cyan if (Get-ShimPath $shimName (!$global)) { Write-Host "But a $(if ($global) { 'local' } else {'global' }) shim exists, " -NoNewline Write-Host "run 'scoop shim alter $shimName$(if (!$global) { ' --global' })' to alternate its source" exit 2 } exit 3 } } } exit 0 ================================================ FILE: libexec/scoop-status.ps1 ================================================ # Usage: scoop status # Summary: Show status and check for new app versions # Help: Options: # -l, --local Checks the status for only the locally installed apps, # and disables remote fetching/checking for Scoop and buckets . "$PSScriptRoot\..\lib\manifest.ps1" # 'manifest' 'parse_json' "install_info" . "$PSScriptRoot\..\lib\versions.ps1" # 'Select-CurrentVersion' . "$PSScriptRoot\..\lib\download.ps1" # 'Get-UserAgent' # check if scoop needs updating $currentdir = versiondir 'scoop' 'current' $needs_update = $false $bucket_needs_update = $false $script:network_failure = $false $no_remotes = $args[0] -eq '-l' -or $args[0] -eq '--local' if (!(Get-Command git -ErrorAction SilentlyContinue)) { $no_remotes = $true } $list = @() if (!(Get-FormatData ScoopStatus)) { Update-FormatData "$PSScriptRoot\..\supporting\formats\ScoopTypes.Format.ps1xml" } function Test-UpdateStatus($repopath) { if (Test-Path "$repopath\.git") { Invoke-Git -Path $repopath -ArgumentList @('fetch', '-q', 'origin') $script:network_failure = 128 -eq $LASTEXITCODE $branch = Invoke-Git -Path $repopath -ArgumentList @('branch', '--show-current') $commits = Invoke-Git -Path $repopath -ArgumentList @('log', "HEAD..origin/$branch", '--oneline') if ($commits) { return $true } else { return $false } } else { return $true } } if (!$no_remotes) { $needs_update = Test-UpdateStatus $currentdir foreach ($bucket in Get-LocalBucket) { if (Test-UpdateStatus (Find-BucketDirectory $bucket -Root)) { $bucket_needs_update = $true break } } } if ($needs_update) { warn "Scoop out of date. Run 'scoop update' to get the latest changes." } elseif ($bucket_needs_update) { warn "Scoop bucket(s) out of date. Run 'scoop update' to get the latest changes." } elseif (!$script:network_failure -and !$no_remotes) { success 'Scoop is up to date.' } $true, $false | ForEach-Object { # local and global apps $global = $_ $dir = appsdir $global if (!(Test-Path $dir)) { return } Get-ChildItem $dir | Where-Object name -NE 'scoop' | ForEach-Object { $app = $_.name $status = app_status $app $global if (!$status.outdated -and !$status.failed -and !$status.deprecated -and !$status.removed -and !$status.missing_deps) { return } $item = [ordered]@{} $item.Name = $app $item.'Installed Version' = $status.version $item.'Latest Version' = if ($status.outdated) { $status.latest_version } else { "" } $item.'Missing Dependencies' = $status.missing_deps -Split ' ' -Join ' | ' $info = @() if ($status.failed) { $info += 'Install failed' } if ($status.hold) { $info += 'Held package' } if ($status.deprecated) { $info += 'Deprecated' } if ($status.removed) { $info += 'Manifest removed' } $item.Info = $info -join ', ' $list += [PSCustomObject]$item } } if ($list.Length -eq 0 -and !$needs_update -and !$bucket_needs_update -and !$script:network_failure) { success 'Everything is ok!' } $list | Add-Member -TypeName ScoopStatus -PassThru exit 0 ================================================ FILE: libexec/scoop-unhold.ps1 ================================================ # Usage: scoop unhold # Summary: Unhold an app to enable updates # Help: To unhold a user-scoped app: # scoop unhold # # To unhold a global app: # scoop unhold -g # # Options: # -g, --global Unhold globally installed apps . "$PSScriptRoot\..\lib\getopt.ps1" . "$PSScriptRoot\..\lib\json.ps1" # 'save_install_info' (indirectly) . "$PSScriptRoot\..\lib\manifest.ps1" # 'install_info' 'Select-CurrentVersion' (indirectly) . "$PSScriptRoot\..\lib\versions.ps1" # 'Select-CurrentVersion' $opt, $apps, $err = getopt $args 'g' 'global' if ($err) { "scoop unhold: $err"; exit 1 } $global = $opt.g -or $opt.global if (!$apps) { my_usage exit 1 } if ($global -and !(is_admin)) { error 'You need admin rights to unhold a global app.' exit 1 } $apps | ForEach-Object { $app = $_ if ($app -eq 'scoop') { set_config HOLD_UPDATE_UNTIL $null | Out-Null success "$app is no longer held and can be updated again." return } if (!(installed $app $global)) { if ($global) { error "'$app' is not installed globally." } else { error "'$app' is not installed." } return } if (get_config NO_JUNCTION){ $version = Select-CurrentVersion -App $app -Global:$global } else { $version = 'current' } $dir = versiondir $app $version $global $json = install_info $app $version $global if (!$json) { error "Failed to unhold '$app'" continue } $install = @{} $json | Get-Member -MemberType Properties | ForEach-Object { $install.Add($_.Name, $json.($_.Name)) } if (!$install.hold) { info "'$app' is not held." continue } $install.hold = $null save_install_info $install $dir success "$app is no longer held and can be updated again." } exit $exitcode ================================================ FILE: libexec/scoop-uninstall.ps1 ================================================ # Usage: scoop uninstall [options] # Summary: Uninstall an app # Help: e.g. scoop uninstall git # # Options: # -g, --global Uninstall a globally installed app # -p, --purge Remove all persistent data . "$PSScriptRoot\..\lib\getopt.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" # 'Get-Manifest' 'Select-CurrentVersion' (indirectly) . "$PSScriptRoot\..\lib\system.ps1" . "$PSScriptRoot\..\lib\install.ps1" . "$PSScriptRoot\..\lib\shortcuts.ps1" . "$PSScriptRoot\..\lib\psmodules.ps1" . "$PSScriptRoot\..\lib\versions.ps1" # 'Select-CurrentVersion' # options $opt, $apps, $err = getopt $args 'gp' 'global', 'purge' if ($err) { error "scoop uninstall: $err" exit 1 } $global = $opt.g -or $opt.global $purge = $opt.p -or $opt.purge if (!$apps) { error ' missing' my_usage exit 1 } if ($global -and !(is_admin)) { error 'You need admin rights to uninstall global apps.' exit 1 } if ($apps -eq 'scoop') { & "$PSScriptRoot\..\bin\uninstall.ps1" $global $purge exit } $apps = Confirm-InstallationStatus $apps -Global:$global if (!$apps) { exit 0 } :app_loop foreach ($_ in $apps) { ($app, $global) = $_ $version = Select-CurrentVersion -AppName $app -Global:$global $appDir = appdir $app $global if ($version) { Write-Host "Uninstalling '$app' ($version)." $dir = versiondir $app $version $global $persist_dir = persistdir $app $global $manifest = installed_manifest $app $version $global $install = install_info $app $version $global $architecture = $install.architecture Invoke-HookScript -HookType 'pre_uninstall' -Manifest $manifest -Arch $architecture #region Workaround for #2952 if (test_running_process $app $global) { continue } #endregion Workaround for #2952 try { Test-Path $dir -ErrorAction Stop | Out-Null } catch [UnauthorizedAccessException] { error "Access denied: $dir. You might need to restart." continue } Invoke-Installer -Path $dir -Manifest $manifest -ProcessorArchitecture $architecture -Global $global -Uninstall rm_shims $app $manifest $global $architecture rm_startmenu_shortcuts $manifest $global $architecture # If a junction was used during install, that will have been used # as the reference directory. Otherwise it will just be the version # directory. $refdir = unlink_current $dir uninstall_psmodule $manifest $refdir $global env_rm_path $manifest $refdir $global $architecture env_rm $manifest $global $architecture try { # unlink all potential old link before doing recursive Remove-Item unlink_persist_data $manifest $dir Remove-Item $dir -Recurse -Force -ErrorAction Stop } catch { if (Test-Path $dir) { error "Couldn't remove '$(friendly_path $dir)'; it may be in use." continue } } Invoke-HookScript -HookType 'post_uninstall' -Manifest $manifest -Arch $architecture } # remove older versions $oldVersions = @(Get-ChildItem $appDir -Name -Exclude 'current') foreach ($version in $oldVersions) { Write-Host "Removing older version ($version)." $dir = versiondir $app $version $global try { # unlink all potential old link before doing recursive Remove-Item unlink_persist_data $manifest $dir Remove-Item $dir -Recurse -Force -ErrorAction Stop } catch { error "Couldn't remove '$(friendly_path $dir)'; it may be in use." continue app_loop } } if (Test-Path ($currentDir = Join-Path $appDir 'current')) { attrib $currentDir -R /L Remove-Item $currentDir -ErrorAction Stop -Force } if (!(Get-ChildItem $appDir)) { try { # if last install failed, the directory seems to be locked and this # will throw an error about the directory not existing Remove-Item $appdir -Recurse -Force -ErrorAction Stop } catch { if ((Test-Path $appdir)) { throw } # only throw if the dir still exists } } # purge persistant data if ($purge) { Write-Host 'Removing persisted data.' $persist_dir = persistdir $app $global if (Test-Path $persist_dir) { try { Remove-Item $persist_dir -Recurse -Force -ErrorAction Stop } catch { error "Couldn't remove '$(friendly_path $persist_dir)'; it may be in use." continue } } } success "'$app' was uninstalled." } exit 0 ================================================ FILE: libexec/scoop-update.ps1 ================================================ # Usage: scoop update [options] # Summary: Update apps, or Scoop itself # Help: 'scoop update' updates Scoop to the latest version. # 'scoop update ' installs a new version of that app, if there is one. # # You can use '*' in place of to update all apps. # # Options: # -f, --force Force update even when there isn't a newer version # -g, --global Update a globally installed app # -i, --independent Don't install dependencies automatically # -k, --no-cache Don't use the download cache # -s, --skip-hash-check Skip hash validation (use with caution!) # -q, --quiet Hide extraneous messages # -a, --all Update all apps (alternative to '*') . "$PSScriptRoot\..\lib\getopt.ps1" . "$PSScriptRoot\..\lib\json.ps1" # 'save_install_info' in 'manifest.ps1' (indirectly) . "$PSScriptRoot\..\lib\system.ps1" . "$PSScriptRoot\..\lib\shortcuts.ps1" . "$PSScriptRoot\..\lib\psmodules.ps1" . "$PSScriptRoot\..\lib\decompress.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" . "$PSScriptRoot\..\lib\versions.ps1" . "$PSScriptRoot\..\lib\depends.ps1" . "$PSScriptRoot\..\lib\install.ps1" . "$PSScriptRoot\..\lib\download.ps1" if (get_config USE_SQLITE_CACHE) { . "$PSScriptRoot\..\lib\database.ps1" } $opt, $apps, $err = getopt $args 'gfiksqa' 'global', 'force', 'independent', 'no-cache', 'skip-hash-check', 'quiet', 'all' if ($err) { "scoop update: $err"; exit 1 } $global = $opt.g -or $opt.global $force = $opt.f -or $opt.force $check_hash = !($opt.s -or $opt.'skip-hash-check') $use_cache = !($opt.k -or $opt.'no-cache') $quiet = $opt.q -or $opt.quiet $independent = $opt.i -or $opt.independent $all = $opt.a -or $opt.all # load config $configRepo = get_config SCOOP_REPO if (!$configRepo) { $configRepo = 'https://github.com/ScoopInstaller/Scoop' set_config SCOOP_REPO $configRepo | Out-Null } # Find current update channel from config $configBranch = get_config SCOOP_BRANCH if (!$configBranch) { $configBranch = 'master' set_config SCOOP_BRANCH $configBranch | Out-Null } if (($PSVersionTable.PSVersion.Major) -lt 5) { # check powershell version Write-Output 'PowerShell 5 or later is required to run Scoop.' Write-Output 'Upgrade PowerShell: https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-windows' break } $show_update_log = get_config SHOW_UPDATE_LOG $true function Sync-Scoop { [CmdletBinding()] Param ( [Switch]$Log ) # Test if Scoop Core is hold if (Test-ScoopCoreOnHold) { return } # check for git if (!(Test-GitAvailable)) { abort "Scoop uses Git to update itself. Run 'scoop install git' and try again." } Write-Host 'Updating Scoop...' $currentdir = versiondir 'scoop' 'current' if (!(Test-Path "$currentdir\.git")) { $newdir = "$currentdir\..\new" $olddir = "$currentdir\..\old" # get git scoop Invoke-Git -ArgumentList @('clone', '-q', $configRepo, '--branch', $configBranch, '--single-branch', $newdir) # check if scoop was successful downloaded if (!(Test-Path "$newdir\bin\scoop.ps1")) { Remove-Item $newdir -Force -Recurse abort "Scoop download failed. If this appears several times, try removing SCOOP_REPO by 'scoop config rm SCOOP_REPO'" } else { # replace non-git scoop with the git version try { Rename-Item $currentdir 'old' -ErrorAction Stop Rename-Item $newdir 'current' -ErrorAction Stop } catch { Write-Warning $_ abort "Scoop update failed. Folder in use. Please rename folders $currentdir to ``old`` and $newdir to ``current``." } } } else { if (Test-Path "$currentdir\..\old") { Remove-Item "$currentdir\..\old" -Recurse -Force -ErrorAction SilentlyContinue } $previousCommit = Invoke-Git -Path $currentdir -ArgumentList @('rev-parse', 'HEAD') $currentRepo = Invoke-Git -Path $currentdir -ArgumentList @('config', 'remote.origin.url') $currentBranch = Invoke-Git -Path $currentdir -ArgumentList @('branch') $isRepoChanged = !($currentRepo -match $configRepo) $isBranchChanged = !($currentBranch -match "\*\s+$configBranch") # Stash uncommitted changes if (Invoke-Git -Path $currentdir -ArgumentList @('diff', 'HEAD', '--name-only')) { if (get_config AUTOSTASH_ON_CONFLICT) { warn 'Uncommitted changes detected. Stashing...' Invoke-Git -Path $currentdir -ArgumentList @('stash', 'push', '-m', "WIP at $([System.DateTime]::Now.ToString('o'))", '-u', '-q') } else { warn 'Uncommitted changes detected. Update aborted.' return } } # Change remote url if the repo is changed if ($isRepoChanged) { Invoke-Git -Path $currentdir -ArgumentList @('config', 'remote.origin.url', $configRepo) } # Fetch and reset local repo if the repo or the branch is changed if ($isRepoChanged -or $isBranchChanged) { # Reset git fetch refs, so that it can fetch all branches (GH-3368) Invoke-Git -Path $currentdir -ArgumentList @('config', 'remote.origin.fetch', '+refs/heads/*:refs/remotes/origin/*') # fetch remote branch Invoke-Git -Path $currentdir -ArgumentList @('fetch', '--force', 'origin', "refs/heads/$configBranch`:refs/remotes/origin/$configBranch", '-q') # checkout and track the branch Invoke-Git -Path $currentdir -ArgumentList @('checkout', '-B', $configBranch, '-t', "origin/$configBranch", '-q') # reset branch HEAD Invoke-Git -Path $currentdir -ArgumentList @('reset', '--hard', "origin/$configBranch", '-q') } else { Invoke-Git -Path $currentdir -ArgumentList @('pull', '-q') } $res = $lastexitcode if ($Log) { Invoke-GitLog -Path $currentdir -CommitHash $previousCommit } if ($res -ne 0) { abort 'Update failed.' } } shim "$currentdir\bin\scoop.ps1" $false } function Sync-Bucket { Param ( [Switch]$Log ) Write-Host 'Updating Buckets...' if (!(Test-Path (Join-Path (Find-BucketDirectory 'main' -Root) '.git'))) { info "Converting 'main' bucket to git repo..." $status = rm_bucket 'main' if ($status -ne 0) { abort "Failed to remove local 'main' bucket." } $status = add_bucket 'main' (known_bucket_repo 'main') if ($status -ne 0) { abort "Failed to add remote 'main' bucket." } } $buckets = Get-LocalBucket | ForEach-Object { $path = Find-BucketDirectory $_ -Root return @{ name = $_ valid = Test-Path (Join-Path $path '.git') path = $path } } $buckets | Where-Object { !$_.valid } | ForEach-Object { Write-Host "'$($_.name)' is not a git repository. Skipped." } $updatedFiles = [System.Collections.ArrayList]::Synchronized([System.Collections.ArrayList]::new()) $removedFiles = [System.Collections.ArrayList]::Synchronized([System.Collections.ArrayList]::new()) if ($PSVersionTable.PSVersion.Major -ge 7) { # Parallel parameter is available since PowerShell 7 $buckets | Where-Object { $_.valid } | ForEach-Object -ThrottleLimit 5 -Parallel { . "$using:PSScriptRoot\..\lib\core.ps1" . "$using:PSScriptRoot\..\lib\buckets.ps1" $name = $_.name $bucketLoc = $_.path $innerBucketLoc = Find-BucketDirectory $name $previousCommit = Invoke-Git -Path $bucketLoc -ArgumentList @('rev-parse', 'HEAD') Invoke-Git -Path $bucketLoc -ArgumentList @('pull', '-q') if ($using:Log) { Invoke-GitLog -Path $bucketLoc -Name $name -CommitHash $previousCommit } if (get_config USE_SQLITE_CACHE) { Invoke-Git -Path $bucketLoc -ArgumentList @('diff', '--name-status', $previousCommit) | ForEach-Object { $status, $file = $_ -split '\s+', 2 $filePath = Join-Path $bucketLoc $file if ($filePath -match "^$([regex]::Escape($innerBucketLoc)).*\.json$") { switch ($status) { { $_ -in 'A', 'M', 'R' } { [void]($using:updatedFiles).Add($filePath) } 'D' { [void]($using:removedFiles).Add([pscustomobject]@{ Name = ([System.IO.FileInfo]$file).BaseName Bucket = $name }) } } } } } } } else { $buckets | Where-Object { $_.valid } | ForEach-Object { $name = $_.name $bucketLoc = $_.path $innerBucketLoc = Find-BucketDirectory $name $previousCommit = Invoke-Git -Path $bucketLoc -ArgumentList @('rev-parse', 'HEAD') Invoke-Git -Path $bucketLoc -ArgumentList @('pull', '-q') if ($Log) { Invoke-GitLog -Path $bucketLoc -Name $name -CommitHash $previousCommit } if (get_config USE_SQLITE_CACHE) { Invoke-Git -Path $bucketLoc -ArgumentList @('diff', '--name-status', $previousCommit) | ForEach-Object { $status, $file = $_ -split '\s+', 2 $filePath = Join-Path $bucketLoc $file if ($filePath -match "^$([regex]::Escape($innerBucketLoc)).*\.json$") { switch ($status) { { $_ -in 'A', 'M', 'R' } { [void]($updatedFiles).Add($filePath) } 'D' { [void]($removedFiles).Add([pscustomobject]@{ Name = ([System.IO.FileInfo]$file).BaseName Bucket = $name }) } } } } } } } if ((get_config USE_SQLITE_CACHE) -and ($updatedFiles.Count -gt 0 -or $removedFiles.Count -gt 0)) { info 'Updating cache...' Set-ScoopDB -Path $updatedFiles $removedFiles | Remove-ScoopDBItem } } function update($app, $global, $quiet = $false, $independent, $suggested, $use_cache = $true, $check_hash = $true) { $old_version = Select-CurrentVersion -AppName $app -Global:$global $old_manifest = installed_manifest $app $old_version $global $install = install_info $app $old_version $global # re-use architecture, bucket and url from first install $architecture = Format-ArchitectureString $install.architecture $bucket = $install.bucket if ($null -eq $bucket) { $bucket = 'main' } $url = $install.url $manifest = manifest $app $bucket $url $version = $manifest.version $is_nightly = $version -eq 'nightly' if ($is_nightly) { $version = nightly_version $quiet $check_hash = $false } if (!$force -and ($old_version -eq $version)) { if (!$quiet) { warn "The latest version of '$app' ($version) is already installed." } return } if (!$version) { # installed from a custom bucket/no longer supported error "No manifest available for '$app'." return } Write-Host "Updating '$app' ($old_version -> $version)" #region Workaround for #2952 if (test_running_process $app $global) { Write-Host 'Running process detected, skip updating.' return } #endregion Workaround for #2952 # region Workaround # Workaround for https://github.com/ScoopInstaller/Scoop/issues/2220 until install is refactored # Remove and replace whole region after proper fix Write-Host 'Downloading new version' if (Test-Aria2Enabled) { Invoke-CachedAria2Download $app $version $manifest $architecture $cachedir $manifest.cookie $true $check_hash } else { $urls = script:url $manifest $architecture foreach ($url in $urls) { Invoke-CachedDownload $app $version $url $null $manifest.cookie $true if ($check_hash) { $manifest_hash = hash_for_url $manifest $url $architecture $source = cache_path $app $version $url $ok, $err = check_hash $source $manifest_hash $(show_app $app $bucket) if (!$ok) { error $err if (Test-Path $source) { # rm cached file Remove-Item -Force $source } if ($url.Contains('sourceforge.net')) { Write-Host -f yellow 'SourceForge.net is known for causing hash validation fails. Please try again before opening a ticket.' } abort $(new_issue_msg $app $bucket 'hash check failed') } } } } # There is no need to check hash again while installing $check_hash = $false # endregion Workaround $dir = versiondir $app $old_version $global $persist_dir = persistdir $app $global Invoke-HookScript -HookType 'pre_uninstall' -Manifest $old_manifest -Arch $architecture Write-Host "Uninstalling '$app' ($old_version)" Invoke-Installer -Path $dir -Manifest $old_manifest -ProcessorArchitecture $architecture -Uninstall rm_shims $app $old_manifest $global $architecture # If a junction was used during install, that will have been used # as the reference directory. Otherwise it will just be the version # directory. $refdir = unlink_current $dir uninstall_psmodule $old_manifest $refdir $global env_rm_path $old_manifest $refdir $global $architecture env_rm $old_manifest $global $architecture if ($force -and ($old_version -eq $version)) { if (!(Test-Path "$dir/../_$version.old")) { Move-Item "$dir" "$dir/../_$version.old" } else { $i = 1 While (Test-Path "$dir/../_$version.old($i)") { $i++ } Move-Item "$dir" "$dir/../_$version.old($i)" } } Invoke-HookScript -HookType 'post_uninstall' -Manifest $old_manifest -Arch $architecture if ($bucket) { # add bucket name it was installed from $app = "$bucket/$app" } if ($install.url) { # use the url of the install json if the application was installed through url $app = $install.url } if ($independent) { install_app $app $architecture $global $suggested $use_cache $check_hash } else { # Also add missing dependencies $apps = @(Get-Dependency $app $architecture) -ne $app ensure_none_failed $apps $apps.Where({ !(installed $_) }) + $app | ForEach-Object { install_app $_ $architecture $global $suggested $use_cache $check_hash } } } if (-not ($apps -or $all)) { if ($global) { error 'scoop update: --global is invalid when is not specified.' exit 1 } if (!$use_cache) { error 'scoop update: --no-cache is invalid when is not specified.' exit 1 } Sync-Scoop -Log:$show_update_log Sync-Bucket -Log:$show_update_log set_config LAST_UPDATE ([System.DateTime]::Now.ToString('o')) | Out-Null success 'Scoop was updated successfully!' } else { if ($global -and !(is_admin)) { 'ERROR: You need admin rights to update global apps.'; exit 1 } $outdated = @() $updateScoop = $null -ne ($apps | Where-Object { $_ -eq 'scoop' }) -or (is_scoop_outdated) $apps = $apps | Where-Object { $_ -ne 'scoop' } $apps_param = $apps if ($updateScoop) { Sync-Scoop -Log:$show_update_log Sync-Bucket -Log:$show_update_log set_config LAST_UPDATE ([System.DateTime]::Now.ToString('o')) | Out-Null success 'Scoop was updated successfully!' } if ($apps_param -eq '*' -or $all) { $apps = applist (installed_apps $false) $false if ($global) { $apps += applist (installed_apps $true) $true } } else { if ($apps_param) { $apps = Confirm-InstallationStatus $apps_param -Global:$global } } if ($apps) { $apps | ForEach-Object { ($app, $global) = $_ $status = app_status $app $global if ($status.installed -and ($force -or $status.outdated)) { if (!$status.hold) { $outdated += applist $app $global Write-Host -f yellow ("$app`: $($status.version) -> $($status.latest_version){0}" -f ('', ' (global)')[$global]) } else { warn "'$app' is held to version $($status.version)" } } elseif ($apps_param -ne '*' -and !$all) { if ($status.installed) { ensure_none_failed $app Write-Host "$app`: $($status.version) (latest version)" -ForegroundColor Green } else { info 'Please reinstall it or fix the manifest.' } } } if ($outdated -and ((Test-Aria2Enabled) -and (get_config 'aria2-warning-enabled' $true))) { warn "Scoop uses 'aria2c' for multi-connection downloads." warn "Should it cause issues, run 'scoop config aria2-enabled false' to disable it." warn "To disable this warning, run 'scoop config aria2-warning-enabled false'." } if ($outdated.Length -gt 1) { Write-Host -f DarkCyan "Updating $($outdated.Length) outdated apps:" } elseif ($outdated.Length -eq 0) { Write-Host -f Green "Latest versions for all apps are installed! For more information try 'scoop status'" } else { Write-Host -f DarkCyan 'Updating one outdated app:' } } $suggested = @{} # $outdated is a list of ($app, $global) tuples $outdated | ForEach-Object { update @_ $quiet $independent $suggested $use_cache $check_hash } } exit 0 ================================================ FILE: libexec/scoop-virustotal.ps1 ================================================ # Usage: scoop virustotal [* | app1 app2 ...] [options] # Summary: Look for app's hash or url on virustotal.com # Help: Look for app's hash or url on virustotal.com # # Use a single '*' or the '-a/--all' switch to check all installed apps. # # To use this command, you have to sign up to VirusTotal's community, # and get an API key. Then, tell scoop about your API key with: # # scoop config virustotal_api_key # # Exit codes: # 0 -> success # 1 -> problem parsing arguments # 2 -> at least one package was marked unsafe by VirusTotal # 4 -> at least one exception was raised while looking for info # 8 -> at least one package couldn't be queried because the manifest couldn't be found # 16 -> VirusTotal API key is not configured # Note: the exit codes (2, 4 & 8) may be combined, e.g. 6 -> exit codes # 2 & 4 combined # # Options: # -a, --all Check for all installed apps # -s, --scan For packages where VirusTotal has no information, send download URL # for analysis (and future retrieval). This requires you to configure # your virustotal_api_key. # -n, --no-depends By default, all dependencies are checked too. This flag avoids it. # -u, --no-update-scoop Don't update Scoop before checking if it's outdated # -p, --passthru Return reports as objects . "$PSScriptRoot\..\lib\getopt.ps1" . "$PSScriptRoot\..\lib\versions.ps1" # 'Select-CurrentVersion' . "$PSScriptRoot\..\lib\manifest.ps1" # 'Get-Manifest' . "$PSScriptRoot\..\lib\json.ps1" # 'json_path' . "$PSScriptRoot\..\lib\download.ps1" # 'hash_for_url' . "$PSScriptRoot\..\lib\depends.ps1" # 'Get-Dependency' $opt, $apps, $err = getopt $args 'asnup' @('all', 'scan', 'no-depends', 'no-update-scoop', 'passthru') if ($err) { "scoop virustotal: $err"; exit 1 } $all = $apps -eq '*' -or $opt.a -or $opt.all if (!$apps -and !$all) { my_usage; exit 1 } $architecture = Get-DefaultArchitecture if (is_scoop_outdated) { if ($opt.u -or $opt.'no-update-scoop') { warn 'Scoop is out of date.' } else { & "$PSScriptRoot\scoop-update.ps1" } } if ($all) { $apps = (installed_apps $false) + (installed_apps $true) } if (!$opt.n -and !$opt.'no-depends') { $apps = $apps | Get-Dependency -Architecture $architecture | Select-Object -Unique } $_ERR_UNSAFE = 2 $_ERR_EXCEPTION = 4 $_ERR_NO_INFO = 8 $_ERR_NO_API_KEY = 16 $exit_code = 0 # Global API key: $api_key = get_config VIRUSTOTAL_API_KEY if (!$api_key) { abort ("VirusTotal API key is not configured`n" + " You could get one from https://www.virustotal.com/gui/my-apikey and set with`n" + " scoop config virustotal_api_key ") $_ERR_NO_API_KEY } # Global flag to explain only once about sleep between requests $explained_rate_limit_sleeping = $False # Requests counter to slow down requests submitted to VirusTotal as # script execution progresses $requests = 0 Function ConvertTo-VirusTotalUrlId ($url) { $url_id = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($url)) $url_id = $url_id -replace '\+', '-' $url_id = $url_id -replace '/', '_' $url_id = $url_id -replace '=', '' $url_id } Function Get-VirusTotalResultByHash ($hash, $url, $app) { $hash = $hash.ToLower() $api_url = "https://www.virustotal.com/api/v3/files/$hash" $headers = @{} $headers.Add('Accept', 'application/json') $headers.Add('x-apikey', $api_key) $response = Invoke-WebRequest -Uri $api_url -Method GET -Headers $headers -UseBasicParsing $result = $response.Content $stats = json_path $result '$.data.attributes.last_analysis_stats' [int]$malicious = json_path $stats '$.malicious' [int]$suspicious = json_path $stats '$.suspicious' [int]$timeout = json_path $stats '$.timeout' [int]$undetected = json_path $stats '$.undetected' [int]$unsafe = $malicious + $suspicious [int]$total = $unsafe + $undetected [int]$fileSize = json_path $result '$.data.attributes.size' $report_hash = json_path $result '$.data.attributes.sha256' $report_url = "https://www.virustotal.com/gui/file/$report_hash" if ($total -eq 0) { info "$app`: Analysis in progress." [PSCustomObject] @{ 'App.Name' = $app 'App.Url' = $url 'App.Hash' = $hash 'App.HashType' = $null 'App.Size' = filesize $fileSize 'FileReport.Url' = $report_url 'FileReport.Hash' = $report_hash 'UrlReport.Url' = $null } } else { $vendorResults = (ConvertFrom-Json((json_path $result '$.data.attributes.last_analysis_results'))).PSObject.Properties.Value switch ($unsafe) { 0 { success "$app`: $unsafe/$total, see $report_url" } 1 { warn "$app`: $unsafe/$total, see $report_url" } 2 { warn "$app`: $unsafe/$total, see $report_url" } Default { warn "$([char]0x1b)[31m$app`: $unsafe/$total, see $report_url$([char]0x1b)[0m" } } $maliciousResults = $vendorResults | Where-Object -Property category -EQ 'malicious' | Select-Object -ExpandProperty engine_name $suspiciousResults = $vendorResults | Where-Object -Property category -EQ 'suspicious' | Select-Object -ExpandProperty engine_name [PSCustomObject] @{ 'App.Name' = $app 'App.Url' = $url 'App.Hash' = $hash 'App.HashType' = $null 'App.Size' = filesize $fileSize 'FileReport.Url' = $report_url 'FileReport.Hash' = $report_hash 'FileReport.Malicious' = if ($maliciousResults) { $maliciousResults } else { 0 } 'FileReport.Suspicious' = if ($suspiciousResults) { $suspiciousResults } else { 0 } 'FileReport.Timeout' = $timeout 'FileReport.Undetected' = $undetected 'UrlReport.Url' = $null } } if ($unsafe -gt 0) { $Script:exit_code = $exit_code -bor $_ERR_UNSAFE } } Function Get-VirusTotalResultByUrl ($url, $app) { $id = ConvertTo-VirusTotalUrlId $url $api_url = "https://www.virustotal.com/api/v3/urls/$id" $headers = @{} $headers.Add('Accept', 'application/json') $headers.Add('x-apikey', $api_key) $response = Invoke-WebRequest -Uri $api_url -Method GET -Headers $headers -UseBasicParsing $result = $response.Content $id = json_path $result '$.data.id' $hash = json_path $result '$.data.attributes.last_http_response_content_sha256' 6>$null $last_analysis_date = json_path $result '$.data.attributes.last_analysis_date' 6>$null $url_report_url = "https://www.virustotal.com/gui/url/$id" info "$app`: Url report found." if (!$hash) { if (!$last_analysis_date) { info "$app`: Analysis in progress." } else { info "$app`: Related file report not found." warn "$app`: Manual file upload is required (instead of url submission)." } [PSCustomObject] @{ 'App.Name' = $app 'App.Url' = $url 'App.Hash' = $null 'App.HashType' = $null 'FileReport.Url' = $null 'UrlReport.Url' = $url_report_url 'UrlReport.Hash' = $null } } else { info "$app`: Related file report found." [PSCustomObject] @{ 'App.Name' = $app 'App.Url' = $url 'App.Hash' = $null 'App.HashType' = $null 'FileReport.Url' = $null 'UrlReport.Url' = $url_report_url 'UrlReport.Hash' = $hash } } } # Submit-ToVirusTotal # - $url: where file to check can be downloaded # - $app: Name of the application (used for reporting) # - $do_scan: [boolean flag] whether to actually submit to VirusTotal # This is a parameter instead of conditionnally calling # the function to consolidate the warning message # - $retrying: [boolean] Optional, for internal use to retry # submitting the file after a delay if the rate limit is # exceeded, without risking an infinite loop (as stack # overflow) if the submission keeps failing. Function Submit-ToVirusTotal ($url, $app, $do_scan, $retrying = $False) { if (!$do_scan) { warn "$app`: not found`: you can manually submit $url" return } try { $requests += 1 $encoded_url = [System.Web.HttpUtility]::UrlEncode($url) $api_url = 'https://www.virustotal.com/api/v3/urls' $content_type = 'application/x-www-form-urlencoded' $headers = @{} $headers.Add('Accept', 'application/json') $headers.Add('x-apikey', $api_key) $headers.Add('Content-Type', $content_type) $body = "url=$encoded_url" $result = Invoke-WebRequest -Uri $api_url -Method POST -Headers $headers -ContentType $content_type -Body $body -UseBasicParsing if ($result.StatusCode -eq 200) { $id = ((json_path $result '$.data.id') -split '-')[1] $url_report_url = "https://www.virustotal.com/gui/url/$id" $fileSize = Get-RemoteFileSize $url if ($fileSize -gt 80000000) { info "$app`: Remote file size: $(filesize $fileSize). Large files might require manual file upload instead of url submission." } info "$app`: Analysis in progress." [PSCustomObject] @{ 'App.Name' = $app 'App.Url' = $url 'App.Size' = filesize $fileSize 'FileReport.Url' = $null 'UrlReport.Url' = $url_report_url } return } # EAFP: submission failed -> sleep, then retry if (!$retrying) { if (!$explained_rate_limit_sleeping) { $explained_rate_limit_sleeping = $True info "Sleeping 60+ seconds between requests due to VirusTotal's 4/min limit" } Start-Sleep -s (60 + $requests) Submit-ToVirusTotal $url $app $do_scan $True } else { warn "$app`: VirusTotal submission of $url failed`:`n" + "`tAPI returned $($result.StatusCode) after retrying" } } catch [Exception] { warn "$app`: VirusTotal submission failed`: $($_.Exception.Message)" return } } $reports = $apps | ForEach-Object { $app = $_ $null, $manifest, $bucket, $null = Get-Manifest $app if (!$manifest) { $exit_code = $exit_code -bor $_ERR_NO_INFO warn "$app`: manifest not found" return } [int]$index = 0 $urls = script:url $manifest $architecture $urls | ForEach-Object { $url = $_ $index++ if ($urls.GetType().IsArray) { info "$app`: url $index" } $hash = hash_for_url $manifest $url $architecture try { $isHashUnsupported = $false if ($hash -match '(?[^:]+):(?.*)') { $algo = $matches.algo $hash = $matches.hash if ($matches.algo -inotin 'md5', 'sha1', 'sha256') { $hash = $null $isHashUnsupported = $true warn "$app`: Unsupported hash $($matches.algo). Will search by url instead." } } elseif ($hash) { $algo = 'sha256' } if ($hash) { $file_report = Get-VirusTotalResultByHash $hash $url $app $file_report.'App.HashType' = $algo $file_report return } elseif (!$isHashUnsupported) { warn "$app`: Hash not found. Will search by url instead." } } catch [Exception] { $exit_code = $exit_code -bor $_ERR_EXCEPTION if ($_.Exception.Response.StatusCode -eq 404) { $file_report_not_found = $true warn "$app`: File report not found. Will search by url instead." } else { if ($_.Exception.Response.StatusCode -in 204, 429) { abort "$app`: VirusTotal request failed`: $($_.Exception.Message)" $exit_code } warn "$app`: VirusTotal request failed`: $($_.Exception.Message)" return } } try { $url_report = Get-VirusTotalResultByUrl $url $app $url_report.'App.Hash' = $hash $url_report.'App.HashType' = $algo if ($url_report.'UrlReport.Hash' -and ($file_report_not_found -eq $true) -and $hash) { if ($algo -eq 'sha256') { if ($url_report.'UrlReport.Hash' -eq $hash) { warn "$app`: Manual file upload is required (instead of url submission) for $url" } else { error "$app`: Hash not matched for $url" } } else { error "$app`: Hash not matched or manual file upload is required (instead of url submission) for $url" } $url_report return } if (!$url_report.'UrlReport.Hash') { $url_report return } } catch [Exception] { $exit_code = $exit_code -bor $_ERR_EXCEPTION if ($_.Exception.Response.StatusCode -eq 404) { warn "$app`: Url report not found. Will submit $url" Submit-ToVirusTotal $url $app ($opt.scan -or $opt.s) return } else { if ($_.Exception.Response.StatusCode -in 204, 429) { abort "$app`: VirusTotal request failed`: $($_.Exception.Message)" $exit_code } warn "$app`: VirusTotal request failed`: $($_.Exception.Message)" return } } try { $file_report = Get-VirusTotalResultByHash $url_report.'UrlReport.Hash' $url $app $file_report.'App.Hash' = $hash $file_report.'App.HashType' = $algo $file_report.'UrlReport.Url' = $url_report.'UrlReport.Url' $file_report warn "$app`: Unable to check hash match for $url" } catch [Exception] { $exit_code = $exit_code -bor $_ERR_EXCEPTION if ($_.Exception.Response.StatusCode -eq 404) { warn "$app`: File report not found for unknown reason. Manual file upload is required (instead of url submission)." $url_report } else { if ($_.Exception.Response.StatusCode -in 204, 429) { abort "$app`: VirusTotal request failed`: $($_.Exception.Message)" $exit_code } warn "$app`: VirusTotal request failed`: $($_.Exception.Message)" return } } } } if ($opt.p -or $opt.'passthru') { $reports } exit $exit_code ================================================ FILE: libexec/scoop-which.ps1 ================================================ # Usage: scoop which # Summary: Locate a shim/executable (similar to 'which' on Linux) # Help: Locate the path to a shim/executable that was installed with Scoop (similar to 'which' on Linux) param($command) if (!$command) { error ' missing' my_usage exit 1 } $path = Get-CommandPath $command if ($null -eq $path) { warn "'$command' not found, not a scoop shim, or a broken shim." exit 2 } else { friendly_path $path exit 0 } ================================================ FILE: schema.json ================================================ { "$id": "http://scoop.sh/draft/schema#", "$schema": "http://json-schema.org/draft-07/schema#", "additionalProperties": false, "definitions": { "hashPattern": { "pattern": "^([a-fA-F0-9]{64}|(sha1|sha256|sha512|md5):([a-fA-F0-9]{32}|[a-fA-F0-9]{40}|[a-fA-F0-9]{64}|[a-fA-F0-9]{128}))$", "type": "string" }, "jsonPathPattern": { "pattern": "^\\$[.\\[].*$", "type": "string" }, "hash": { "anyOf": [ { "$ref": "#/definitions/hashPattern" }, { "items": { "$ref": "#/definitions/hashPattern" }, "minItems": 1, "type": "array", "uniqueItems": true } ] }, "hashExtraction": { "additionalProperties": false, "properties": { "find": { "format": "regex", "type": "string", "description": "Same as 'regex'" }, "regex": { "format": "regex", "type": "string" }, "jp": { "$ref": "#/definitions/jsonPathPattern", "description": "Same as 'jsonpath'" }, "jsonpath": { "$ref": "#/definitions/jsonPathPattern" }, "xpath": { "type": "string" }, "mode": { "enum": [ "download", "extract", "json", "xpath", "rdf", "metalink", "fosshub", "sourceforge" ] }, "type": { "enum": [ "md5", "sha1", "sha256", "sha512" ], "description": "Deprecated, hash type is determined automatically" }, "url": { "anyOf": [ { "format": "uri", "type": "string" }, { "pattern": "^(\\$url|\\$baseurl).[\\w\\d]+$", "type": "string" }, { "pattern": "^.*(\\$url|\\$baseurl).*$", "type": "string" } ] } }, "type": "object" }, "hashExtractionOrArrayOfHashExtractions": { "anyOf": [ { "$ref": "#/definitions/hashExtraction" }, { "items": { "$ref": "#/definitions/hashExtraction" }, "minItems": 1, "type": "array", "uniqueItems": false } ] }, "architecture": { "additionalProperties": false, "properties": { "bin": { "$ref": "#/definitions/stringOrArrayOfStringsOrAnArrayOfArrayOfStrings" }, "checkver": { "$ref": "#/definitions/checkver" }, "env_add_path": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "env_set": { "type": "object" }, "extract_dir": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "hash": { "$ref": "#/definitions/hash" }, "installer": { "$ref": "#/definitions/installer" }, "post_install": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "post_uninstall": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "pre_install": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "pre_uninstall": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "shortcuts": { "$ref": "#/definitions/shortcutsArray" }, "uninstaller": { "$ref": "#/definitions/uninstaller" }, "url": { "$ref": "#/definitions/uriOrArrayOfUris" } }, "type": "object" }, "arrayOfArrayOfStrings": { "items": { "items": { "type": "string" }, "minItems": 1, "type": "array" }, "minItems": 1, "type": "array" }, "shortcutsArray": { "items": { "items": { "type": "string" }, "minItems": 2, "maxItems": 4, "type": "array" }, "minItems": 1, "type": "array" }, "autoupdateArch": { "type": "object", "additionalProperties": false, "properties": { "bin": { "$ref": "#/definitions/stringOrArrayOfStringsOrAnArrayOfArrayOfStrings" }, "env_add_path": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "env_set": { "type": "object" }, "extract_dir": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "hash": { "$ref": "#/definitions/hashExtractionOrArrayOfHashExtractions" }, "installer": { "type": "object", "additionalProperties": false, "properties": { "file": { "type": "string" } } }, "shortcuts": { "$ref": "#/definitions/shortcutsArray" }, "url": { "$ref": "#/definitions/autoupdateUriOrArrayOfAutoupdateUris" } } }, "autoupdate": { "type": "object", "additionalProperties": false, "properties": { "architecture": { "type": "object", "additionalProperties": false, "properties": { "32bit": { "$ref": "#/definitions/autoupdateArch" }, "64bit": { "$ref": "#/definitions/autoupdateArch" }, "arm64": { "$ref": "#/definitions/autoupdateArch" } } }, "bin": { "$ref": "#/definitions/stringOrArrayOfStringsOrAnArrayOfArrayOfStrings" }, "env_add_path": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "env_set": { "type": "object" }, "extract_dir": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "hash": { "$ref": "#/definitions/hashExtractionOrArrayOfHashExtractions" }, "installer": { "type": "object", "additionalProperties": false, "properties": { "file": { "type": "string" } } }, "license": { "$ref": "#/definitions/license" }, "notes": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "persist": { "$ref": "#/definitions/stringOrArrayOfStringsOrAnArrayOfArrayOfStrings" }, "psmodule": { "type": "object", "additionalProperties": false, "properties": { "name": { "type": "string" } } }, "shortcuts": { "$ref": "#/definitions/shortcutsArray" }, "url": { "$ref": "#/definitions/autoupdateUriOrArrayOfAutoupdateUris" } } }, "checkver": { "anyOf": [ { "format": "regex", "type": "string" }, { "additionalProperties": false, "properties": { "github": { "format": "uri", "type": "string" }, "re": { "format": "regex", "type": "string", "description": "Same as 'regex'" }, "regex": { "format": "regex", "type": "string" }, "url": { "format": "uri", "type": "string" }, "jp": { "$ref": "#/definitions/jsonPathPattern", "description": "Same as 'jsonpath'" }, "jsonpath": { "$ref": "#/definitions/jsonPathPattern" }, "xpath": { "type": "string" }, "reverse": { "description": "Reverse the order of regex matches", "type": "boolean" }, "replace": { "description": "Allows rearrange the regexp matches", "type": "string" }, "useragent": { "type": "string" }, "script": { "$ref": "#/definitions/stringOrArrayOfStrings", "description": "Custom PowerShell script to retrieve application version using more complex approach." }, "sourceforge": { "anyOf": [ { "type": "string" }, { "additionalProperties": false, "properties": { "project": { "type": "string" }, "path": { "type": "string" } }, "type": "object" } ] } }, "type": "object" } ] }, "installer": { "additionalProperties": false, "properties": { "_comment": { "description": "Undocumented: only used in scoop-extras/oraclejdk* and scoop-extras/appengine-go", "type": "string" }, "args": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "file": { "type": "string" }, "script": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "keep": { "type": "boolean" } }, "type": "object" }, "stringOrArrayOfStrings": { "anyOf": [ { "type": "string" }, { "items": { "type": "string" }, "minItems": 1, "type": "array" } ] }, "stringOrArrayOfStringsOrAnArrayOfArrayOfStrings": { "anyOf": [ { "type": "string" }, { "items": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "minItems": 1, "type": "array" } ] }, "uninstaller": { "properties": { "args": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "file": { "type": "string" }, "script": { "$ref": "#/definitions/stringOrArrayOfStrings" } }, "oneOf": [ { "required": [ "file" ] }, { "required": [ "script" ] } ], "type": "object" }, "uriOrArrayOfUris": { "anyOf": [ { "format": "uri", "not": { "pattern": "(\\$)" }, "type": "string" }, { "items": { "format": "uri", "not": { "pattern": "(\\$)" }, "type": "string" }, "minItems": 1, "type": "array", "uniqueItems": true } ] }, "autoupdateUriOrArrayOfAutoupdateUris": { "anyOf": [ { "format": "uri", "type": "string" }, { "items": { "format": "uri", "type": "string" }, "minItems": 1, "type": "array", "uniqueItems": true } ] }, "licenseIdentifiers": { "type": "string", "description": "License identifier based on SPDX License List https://spdx.org/licenses/", "examples": [ "Apache-2.0", "BSD-3-Clause", "Freeware", "GPL-2.0-only", "GPL-2.0-or-later", "GPL-3.0-only", "GPL-3.0-or-later", "ISC", "LGPL-2.0-only", "LGPL-2.0-or-later", "LGPL-2.1-only", "LGPL-2.1-or-later", "LGPL-3.0-only", "LGPL-3.0-or-later", "MIT", "MS-PL", "Proprietary", "Public Domain", "Shareware", "Unlicense" ] }, "license": { "anyOf": [ { "$ref": "#/definitions/licenseIdentifiers" }, { "additionalProperties": false, "properties": { "url": { "format": "uri", "type": "string" }, "identifier": { "$ref": "#/definitions/licenseIdentifiers" } }, "required": [ "identifier" ], "type": "object" } ] } }, "properties": { "$schema": { "type": "string", "format": "uri" }, "_comment": { "description": "Deprecated. Use ## instead.", "$ref": "#/definitions/stringOrArrayOfStrings" }, "##": { "description": "A comment.", "$ref": "#/definitions/stringOrArrayOfStrings" }, "architecture": { "additionalProperties": false, "properties": { "32bit": { "$ref": "#/definitions/architecture" }, "64bit": { "$ref": "#/definitions/architecture" }, "arm64": { "$ref": "#/definitions/architecture" } }, "type": "object" }, "autoupdate": { "$ref": "#/definitions/autoupdate" }, "bin": { "$ref": "#/definitions/stringOrArrayOfStringsOrAnArrayOfArrayOfStrings" }, "persist": { "$ref": "#/definitions/stringOrArrayOfStringsOrAnArrayOfArrayOfStrings" }, "checkver": { "$ref": "#/definitions/checkver" }, "cookie": { "description": "Undocumented: Found at https://github.com/se35710/scoop-java/search?l=JSON&q=cookie", "type": "object" }, "depends": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "description": { "type": "string" }, "env_add_path": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "env_set": { "type": "object" }, "extract_dir": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "extract_to": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "hash": { "$ref": "#/definitions/hash" }, "homepage": { "format": "uri", "type": "string" }, "innosetup": { "description": "True if the installer InnoSetup based. Found in https://github.com/ScoopInstaller/Main/search?l=JSON&q=innosetup", "type": "boolean" }, "installer": { "$ref": "#/definitions/installer" }, "license": { "$ref": "#/definitions/license" }, "notes": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "post_install": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "post_uninstall": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "pre_install": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "pre_uninstall": { "$ref": "#/definitions/stringOrArrayOfStrings" }, "psmodule": { "additionalProperties": false, "properties": { "name": { "type": "string" } }, "type": "object" }, "shortcuts": { "$ref": "#/definitions/shortcutsArray" }, "suggest": { "additionalProperties": false, "patternProperties": { "^(.*)$": { "$ref": "#/definitions/stringOrArrayOfStrings" } }, "type": "object" }, "uninstaller": { "$ref": "#/definitions/uninstaller" }, "url": { "$ref": "#/definitions/uriOrArrayOfUris" }, "version": { "pattern": "^[\\w\\.\\-+_]+$", "type": "string" } }, "if": { "properties": { "architecture": { "properties": { "64bit": { "properties": { "url": false } }, "32bit": { "properties": { "url": false } }, "arm64": { "properties": { "url": false } } } } } }, "then": { "required": [ "url" ] }, "required": [ "version", "homepage", "license" ], "title": "scoop app manifest schema", "type": "object" } ================================================ FILE: supporting/formats/ScoopTypes.Format.ps1xml ================================================ ScoopAppsType ScoopApps Name Version Source Updated yyyy-MM-dd HH:mm:ss Info ScoopShimsType ScoopShims Name Source Alternatives IsGlobal IsHidden ScoopStatusType ScoopStatus Name Installed Version Latest Version Missing Dependencies Info ================================================ FILE: supporting/shims/71/checksum.sha256 ================================================ 70d4690b8ac3b3f715f537cdea6e07a39fda4bc0347bf6b958e4f3ff2f0e04d4 shim.exe ================================================ FILE: supporting/shims/71/checksum.sha512 ================================================ ecde07b32192846c4885cf4d2208eedc170765ea115ae49b81509fed0ce474e21064100bb2f3d815ee79f1c12463d32ef013d4182647eae71855cd18e4196176 shim.exe ================================================ FILE: supporting/shims/kiennq/checksum.sha256 ================================================ 140e3801d8adeda639a21b14e62b93a4c7d26b7a758421f43c82be59753be49b *shim.exe ================================================ FILE: supporting/shims/kiennq/checksum.sha512 ================================================ 59d9da9f9714003b915bcafbe1b41f53b121dde206ecc23984f62273e957766eece8d64ffc53011c328d3a2ad627aa0f4f7c39bbec8e7b64d0d2ee7b7e771423 *shim.exe ================================================ FILE: supporting/shims/kiennq/version.txt ================================================ v3.1.2 ================================================ FILE: supporting/shims/scoopcs/checksum.sha256 ================================================ 0116068768fc992fc536738396b33db3dafe6b0cf0e6f54f6d1aa8b0331f3cec *shim.exe ================================================ FILE: supporting/shims/scoopcs/checksum.sha512 ================================================ d734c528e9f20581ed3c7aa71a458f7dff7e2780fa0c319ccb9c813cd8dbf656bd7e550b81d2aa3ee8775bff9a4e507bc0b25f075697405adca0f47d37835848 *shim.exe ================================================ FILE: supporting/shims/scoopcs/version.txt ================================================ 1.1.0 ================================================ FILE: supporting/validator/.gitignore ================================================ packages/ ================================================ FILE: supporting/validator/Scoop.Validator.cs ================================================ using System; using System.Collections.Generic; using System.IO; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Schema; namespace Scoop { public class JsonParserException : Exception { public string FileName { get; set; } public JsonParserException(string file, string message) : base(message) { this.FileName = file; } public JsonParserException(string file, string message, Exception inner) : base(message, inner) { this.FileName = file; } } public class Validator { private bool CI { get; set; } public JSchema Schema { get; private set; } public FileInfo SchemaFile { get; private set; } public JObject Manifest { get; private set; } public FileInfo ManifestFile { get; private set; } public IList Errors { get; private set; } public string ErrorsAsString { get { return String.Join(System.Environment.NewLine, this.Errors); } } private JSchema ParseSchema(string file) { try { return JSchema.Parse(File.ReadAllText(file, System.Text.Encoding.UTF8)); } catch (Newtonsoft.Json.JsonReaderException e) { throw new JsonParserException(Path.GetFileName(file), e.Message, e); } catch (FileNotFoundException e) { throw e; } } private JObject ParseManifest(string file) { try { return JObject.Parse(File.ReadAllText(file, System.Text.Encoding.UTF8)); } catch (Newtonsoft.Json.JsonReaderException e) { throw new JsonParserException(Path.GetFileName(file), e.Message, e); } catch (FileNotFoundException e) { throw e; } } public Validator(string schemaFile) { this.SchemaFile = new FileInfo(schemaFile); this.Errors = new List(); } public Validator(string schemaFile, bool ci) { this.SchemaFile = new FileInfo(schemaFile); this.Errors = new List(); this.CI = ci; } public bool Validate(string file) { this.ManifestFile = new FileInfo(file); return this.Validate(); } public bool Validate() { if (!this.SchemaFile.Exists) { Console.WriteLine("ERROR: Please provide schema.json!"); return false; } if (!this.ManifestFile.Exists) { Console.WriteLine("ERROR: Please provide manifest.json!"); return false; } this.Errors.Clear(); try { if (this.Schema == null) { this.Schema = this.ParseSchema(this.SchemaFile.FullName); } this.Manifest = this.ParseManifest(this.ManifestFile.FullName); } catch (FileNotFoundException e) { this.Errors.Add(e.Message); } catch (JsonParserException e) { this.Errors.Add(String.Format("{0}{1}: {2}", (this.CI ? " [*] " : ""), e.FileName, e.Message)); } if (this.Schema == null || this.Manifest == null) return false; IList validationErrors = new List(); this.Manifest.IsValid(this.Schema, out validationErrors); if (validationErrors.Count == 0) { return true; } traverseErrors(validationErrors, this.CI ? 3 : 1); return (this.Errors.Count == 0); } public void traverseErrors(IList errors, int level = 1) { if(errors == null) { return; } foreach (ValidationError error in errors) { StringBuilder sb = new StringBuilder(); sb.Insert(sb.Length, " ", level * 2); sb.Insert(sb.Length, this.CI ? "[*] " : "- "); sb.AppendFormat("Error: {0}\n", error.Message); sb.Insert(sb.Length, " ", level * 2); sb.Insert(sb.Length, this.CI ? " [^] " : " "); sb.AppendFormat("Line: {0}:{1}:{2}\n", this.ManifestFile.FullName, error.LineNumber, error.LinePosition); sb.Insert(sb.Length, " ", level * 2); sb.Insert(sb.Length, this.CI ? " [^] " : " "); sb.AppendFormat("Path: {0}/{1}", error.SchemaId, error.ErrorType); if(!this.CI) { sb.Insert(sb.Length, "\n"); } this.Errors.Add(sb.ToString()); if(error.ChildErrors != null || error.ChildErrors.Count > 0) { traverseErrors(error.ChildErrors, level + 1); } } } } } ================================================ FILE: supporting/validator/bin/checksum.sha256 ================================================ e1e27af7b07eeedf5ce71a9255f0422816a6fc5849a483c6714e1b472044fa9d *Newtonsoft.Json.dll 7496d5349a123a6e3696085662b2ff17b156ccdb0e30e0c396ac72d2da36ce1c *Newtonsoft.Json.Schema.dll 83b1006443e8c340ca4c631614fc2ce0d5cb9a28c851e3b59724299f58b1397f *Scoop.Validator.dll 87f8f8db2202a3fbef6f431d0b7e20cec9d32095c441927402041f3c4076c1b6 *validator.exe ================================================ FILE: supporting/validator/bin/checksum.sha512 ================================================ 56eb7f070929b239642dab729537dde2c2287bdb852ad9e80b5358c74b14bc2b2dded910d0e3b6304ea27eb587e5f19db0a92e1cbae6a70fb20b4ef05057e4ac *Newtonsoft.Json.dll 78b12beb1e67ac4f6efa0fcba57b4b34ea6a31d8b369934d6b6a6617386ef9939ea453ac262916e5857ce0359eb809424ea33c676a87a8fdfd77a59b2ce96db0 *Newtonsoft.Json.Schema.dll e9da4370aee4df47eedcf15d9749712eee513e5a9115b808617ddfcfde5bc47a0410edfb57508fcf51033c0be967611b2fd2c2ba944de7290c020cc67f77ac57 *Scoop.Validator.dll 58a0c37e98cac17822c7756bf6686a5fb74e711b8d986d13bd2f689f6b3b1f485fcd908d92cbc6a162a0e5974c2c5a43de57d15f1996be0aa405e41ec2ec8393 *validator.exe ================================================ FILE: supporting/validator/build.ps1 ================================================ Param([Switch]$Fast) Push-Location $PSScriptRoot . "$PSScriptRoot\..\..\lib\core.ps1" . "$PSScriptRoot\..\..\lib\install.ps1" if (!$Fast) { Write-Host 'Install dependencies ...' & "$PSScriptRoot\install.ps1" } $output = "$PSScriptRoot\bin" if (!$Fast) { Get-ChildItem "$PSScriptRoot\packages\Newtonsoft.*\lib\net45\*.dll" -File | ForEach-Object { Copy-Item $_ $output } } Write-Output 'Compiling Scoop.Validator.cs ...' & "$PSScriptRoot\packages\Microsoft.Net.Compilers.Toolset\tasks\net472\csc.exe" -deterministic -platform:anycpu -nologo -optimize -target:library -reference:"$output\Newtonsoft.Json.dll" -reference:"$output\Newtonsoft.Json.Schema.dll" -out:"$output\Scoop.Validator.dll" Scoop.Validator.cs Write-Output 'Compiling validator.cs ...' & "$PSScriptRoot\packages\Microsoft.Net.Compilers.Toolset\tasks\net472\csc.exe" -deterministic -platform:anycpu -nologo -optimize -target:exe -reference:"$output\Scoop.Validator.dll" -reference:"$output\Newtonsoft.Json.dll" -reference:"$output\Newtonsoft.Json.Schema.dll" -out:"$output\validator.exe" validator.cs Write-Output 'Computing checksums ...' Remove-Item "$PSScriptRoot\bin\checksum.sha256" -ErrorAction Ignore Remove-Item "$PSScriptRoot\bin\checksum.sha512" -ErrorAction Ignore Get-ChildItem "$PSScriptRoot\bin\*" -Include *.exe, *.dll | ForEach-Object { "$((Get-FileHash -Path $_ -Algorithm SHA256).Hash.ToLower()) *$($_.Name)" | Out-File "$PSScriptRoot\bin\checksum.sha256" -Append -Encoding oem "$((Get-FileHash -Path $_ -Algorithm SHA512).Hash.ToLower()) *$($_.Name)" | Out-File "$PSScriptRoot\bin\checksum.sha512" -Append -Encoding oem } Pop-Location ================================================ FILE: supporting/validator/install.ps1 ================================================ # https://github.com/edymtt/nugetstandalone $destinationFolder = "$PSScriptRoot\packages" if ((Test-Path -Path $destinationFolder)) { Remove-Item -Path $destinationFolder -Recurse | Out-Null } New-Item $destinationFolder -Type Directory | Out-Null nuget install packages.config -o $destinationFolder -ExcludeVersion ================================================ FILE: supporting/validator/packages.config ================================================  ================================================ FILE: supporting/validator/update.ps1 ================================================ # https://github.com/edymtt/nugetstandalone $destinationFolder = "$PSScriptRoot\packages" if (!(Test-Path -Path $destinationFolder)) { Write-Host -f Red "Run .\install.ps1 first!" exit 1 } nuget update packages.config -r $destinationFolder Remove-Item $destinationFolder -Force -Recurse | Out-Null nuget install packages.config -o $destinationFolder -ExcludeVersion ================================================ FILE: supporting/validator/validator.cs ================================================ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; namespace Scoop { public class Program { public static int Main(string[] args) { bool ci = String.Format("{0}", Environment.GetEnvironmentVariable("CI")).ToLower() == "true"; bool valid = true; if (args.Length < 2) { Console.WriteLine("Usage: validator.exe [...]"); return 1; } IList manifests = args.ToList(); String schema = manifests.First(); manifests.RemoveAt(0); String combinedArgs = String.Join("", manifests); if(combinedArgs.Contains("*") || combinedArgs.Contains("?")) { try { var path = new Uri(Path.Combine(Directory.GetCurrentDirectory(), combinedArgs)).LocalPath; var drive = Path.GetPathRoot(path); var pattern = path.Replace(drive, ""); manifests = Directory.GetFiles(drive, pattern).ToList(); } catch (System.ArgumentException ex) { Console.WriteLine("Invalid path provided! ({0})", ex.Message); return 1; } } Scoop.Validator validator = new Scoop.Validator(schema, ci); foreach(var manifest in manifests) { if (validator.Validate(manifest)) { if(ci) { Console.WriteLine(" [+] {0} validates against the schema!", Path.GetFileName(manifest)); } else { Console.WriteLine("- {0} validates against the schema!", Path.GetFileName(manifest)); } } else { if(ci) { Console.WriteLine(" [-] {0} has {1} Error{2}!", Path.GetFileName(manifest), validator.Errors.Count, validator.Errors.Count > 1 ? "s" : ""); } else { Console.WriteLine("- {0} has {1} Error{2}!", Path.GetFileName(manifest), validator.Errors.Count, validator.Errors.Count > 1 ? "s" : ""); } valid = false; foreach (var error in validator.Errors) { Console.WriteLine(error); } } } return valid ? 0 : 1; } } } ================================================ FILE: supporting/validator/validator.csproj ================================================ Debug AnyCPU {8EB9B38A-1BAB-4D89-B4CB-ACE5E7C1073B} Exe Scoop.Validator Scoop.Validator v4.5.0 512 true packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll True packages\Newtonsoft.Json.Schema.4.0.1\lib\net45\Newtonsoft.Json.Schema.dll True This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. ================================================ FILE: test/Import-Bucket-Tests.ps1 ================================================ #Requires -Version 5.1 #Requires -Modules @{ ModuleName = 'BuildHelpers'; ModuleVersion = '2.0.1' } #Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.2.0' } param( [String] $BucketPath = $MyInvocation.PSScriptRoot ) . "$PSScriptRoot\Scoop-00File.Tests.ps1" -TestPath $BucketPath Describe 'Manifest validates against the schema' { BeforeDiscovery { $bucketDir = if (Test-Path "$BucketPath\bucket") { "$BucketPath\bucket" } else { $BucketPath } if ($env:CI -eq $true) { Set-BuildEnvironment -Force $manifestFiles = @(Get-GitChangedFile -Path $bucketDir -Include '*.json' -Commit $env:BHCommitHash) } else { $manifestFiles = (Get-ChildItem $bucketDir -Filter '*.json' -Recurse).FullName } } BeforeAll { Add-Type -Path "$PSScriptRoot\..\supporting\validator\bin\Scoop.Validator.dll" # Could not use backslash '\' in Linux/macOS for .NET object 'Scoop.Validator' $validator = New-Object Scoop.Validator("$PSScriptRoot/../schema.json", $true) $global:quotaExceeded = $false } It '<_>' -TestCases $manifestFiles { if ($global:quotaExceeded) { Set-ItResult -Skipped -Because 'Schema validation limit exceeded.' } else { $file = $_ # exception handling may overwrite $_ try { $validator.Validate($file) if ($validator.Errors.Count -gt 0) { Write-Host " [-] $_ has $($validator.Errors.Count) Error$(If($validator.Errors.Count -gt 1) { 's' })!" -ForegroundColor Red Write-Host $validator.ErrorsAsString -ForegroundColor Yellow } $validator.Errors.Count | Should -Be 0 } catch { if ($_.Exception.Message -like '*The free-quota limit of 1000 schema validations per hour has been reached.*') { $global:quotaExceeded = $true Set-ItResult -Skipped -Because 'Schema validation limit exceeded.' } else { throw } } } } } ================================================ FILE: test/Scoop-00File.Tests.ps1 ================================================ param( [String] $TestPath = "$PSScriptRoot\.." ) BeforeDiscovery { $project_file_exclusions = @( '[\\/]\.git[\\/]', '\.sublime-workspace$', '\.DS_Store$', 'supporting(\\|/)validator(\\|/)packages(\\|/)*' ) $repo_files = (Get-ChildItem $TestPath -File -Recurse).FullName | Where-Object { $_ -inotmatch $($project_file_exclusions -join '|') } } Describe 'Code Syntax' -ForEach @(, $repo_files) -Tag 'File' { BeforeAll { $files = @( $_ | Where-Object { $_ -imatch '.(ps1|psm1)$' } ) function Test-PowerShellSyntax { # ref: http://powershell.org/wp/forums/topic/how-to-check-syntax-of-scripts-automatically @@ https://archive.is/xtSv6 # originally created by Alexander Petrovskiy & Dave Wyatt [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string[]] $Path ) process { foreach ($scriptPath in $Path) { $contents = Get-Content -Path $scriptPath if ($null -eq $contents) { continue } $errors = $null $null = [System.Management.Automation.PSParser]::Tokenize($contents, [ref]$errors) New-Object psobject -Property @{ Path = $scriptPath SyntaxErrorsFound = ($errors.Count -gt 0) } } } } } It 'PowerShell code files do not contain syntax errors' { $badFiles = @( foreach ($file in $files) { if ( (Test-PowerShellSyntax $file).SyntaxErrorsFound ) { $file } } ) if ($badFiles.Count -gt 0) { throw "The following files have syntax errors: `r`n`r`n$($badFiles -join "`r`n")" } } } Describe 'Style constraints for non-binary project files' -ForEach @(, $repo_files) -Tag 'File' { BeforeAll { $files = @( # gather all files except '*.exe', '*.zip', or any .git repository files $_ | Where-Object { $_ -inotmatch '(.exe|.zip|.dll)$' } | Where-Object { $_ -inotmatch '(unformatted)' } ) } It 'files do not contain leading UTF-8 BOM' { # UTF-8 BOM == 0xEF 0xBB 0xBF # see http://www.powershellmagazine.com/2012/12/17/pscxtip-how-to-determine-the-byte-order-mark-of-a-text-file @@ https://archive.is/RgT42 # ref: http://poshcode.org/2153 @@ https://archive.is/sGnnu $badFiles = @( foreach ($file in $files) { if ((Get-Command Get-Content).parameters.ContainsKey('AsByteStream')) { # PowerShell Core (6.0+) '-Encoding byte' is replaced by '-AsByteStream' $content = ([char[]](Get-Content $file -AsByteStream -TotalCount 3) -join '') } else { $content = ([char[]](Get-Content $file -Encoding byte -TotalCount 3) -join '') } if ([regex]::match($content, '(?ms)^\xEF\xBB\xBF').success) { $file } } ) if ($badFiles.Count -gt 0) { throw "The following files have utf-8 BOM: `r`n`r`n$($badFiles -join "`r`n")" } } It 'files end with a newline' { $badFiles = @( foreach ($file in $files) { # Ignore previous TestResults.xml if ($file -match 'TestResults.xml') { continue } $string = [System.IO.File]::ReadAllText($file) if ($string.Length -gt 0 -and $string[-1] -ne "`n") { $file } } ) if ($badFiles.Count -gt 0) { throw "The following files do not end with a newline: `r`n`r`n$($badFiles -join "`r`n")" } } It 'file newlines are CRLF' { $badFiles = @( foreach ($file in $files) { $content = [System.IO.File]::ReadAllText($file) if (!$content) { throw "File contents are null: $($file)" } $lines = [regex]::split($content, '\r\n') $lineCount = $lines.Count for ($i = 0; $i -lt $lineCount; $i++) { if ( [regex]::match($lines[$i], '\r|\n').success ) { $file break } } } ) if ($badFiles.Count -gt 0) { throw "The following files have non-CRLF line endings: `r`n`r`n$($badFiles -join "`r`n")" } } It 'files have no lines containing trailing whitespace' { $badLines = @( foreach ($file in $files) { # Ignore previous TestResults.xml if ($file -match 'TestResults.xml') { continue } $lines = [System.IO.File]::ReadAllLines($file) $lineCount = $lines.Count for ($i = 0; $i -lt $lineCount; $i++) { if ($lines[$i] -match '\s+$') { 'File: {0}, Line: {1}' -f $file, ($i + 1) } } } ) if ($badLines.Count -gt 0) { throw "The following $($badLines.Count) lines contain trailing whitespace: `r`n`r`n$($badLines -join "`r`n")" } } It 'any leading whitespace consists only of spaces (excepting makefiles)' { $badLines = @( foreach ($file in $files) { if ($file -inotmatch '(^|.)makefile$') { $lines = [System.IO.File]::ReadAllLines($file) $lineCount = $lines.Count for ($i = 0; $i -lt $lineCount; $i++) { if ($lines[$i] -notmatch '^[ ]*(\S|$)') { 'File: {0}, Line: {1}' -f $file, ($i + 1) } } } } ) if ($badLines.Count -gt 0) { throw "The following $($badLines.Count) lines contain TABs within leading whitespace: `r`n`r`n$($badLines -join "`r`n")" } } } ================================================ FILE: test/Scoop-00Linting.Tests.ps1 ================================================ Describe 'PSScriptAnalyzer' -Tag 'Linter' { BeforeDiscovery { $scriptDir = @('.', 'bin', 'lib', 'libexec', 'test') } BeforeAll { $lintSettings = "$PSScriptRoot\..\PSScriptAnalyzerSettings.psd1" } It 'PSScriptAnalyzerSettings.ps1 should exist' { $lintSettings | Should -Exist } Context 'Linting all *.psd1, *.psm1 and *.ps1 files' { BeforeEach { $analysis = Invoke-ScriptAnalyzer -Path "$PSScriptRoot\..\$_" -Settings $lintSettings } It 'Should pass: <_>' -TestCases $scriptDir { $analysis | Should -HaveCount 0 if ($analysis) { foreach ($result in $analysis) { switch -wildCard ($result.ScriptName) { '*.psm1' { $type = 'Module' } '*.ps1' { $type = 'Script' } '*.psd1' { $type = 'Manifest' } } Write-Warning " [*] $($result.Severity): $($result.Message)" Write-Warning " $($result.RuleName) in $type`: $directory\$($result.ScriptName):$($result.Line)" } } } } } ================================================ FILE: test/Scoop-Commands.Tests.ps1 ================================================ BeforeAll { . "$PSScriptRoot\Scoop-TestLib.ps1" . "$PSScriptRoot\..\lib\core.ps1" . "$PSScriptRoot\..\lib\commands.ps1" } Describe 'Manipulate Alias' -Tag 'Scoop' { BeforeAll { Mock shimdir { "$TestDrive\shims" } Mock set_config {} Mock get_config { @{} } $shimdir = shimdir ensure $shimdir } It 'Creates a new alias if it does not exist' { $alias_script = "$shimdir\scoop-rm.ps1" $alias_script | Should -Not -Exist add_alias 'rm' '"hello, world!"' & $alias_script | Should -Be 'hello, world!' } It 'Skips an existing alias' { $alias_script = "$shimdir\scoop-rm.ps1" Mock abort {} New-Item $alias_script -Type File -Force $alias_script | Should -Exist add_alias 'rm' '"test"' Should -Invoke -CommandName abort -Times 1 -ParameterFilter { $msg -eq "File 'scoop-rm.ps1' already exists in shims directory." } } It 'Removes an existing alias' { $alias_script = "$shimdir\scoop-rm.ps1" $alias_script | Should -Exist Mock get_config { @(@{'rm' = 'scoop-rm' }) } Mock info {} rm_alias 'rm' $alias_script | Should -Not -Exist Should -Invoke -CommandName info -Times 1 -ParameterFilter { $msg -eq "Removing alias 'rm'..." } } } ================================================ FILE: test/Scoop-Config.Tests.ps1 ================================================ BeforeAll { . "$PSScriptRoot\Scoop-TestLib.ps1" . "$PSScriptRoot\..\lib\core.ps1" } Describe 'config' -Tag 'Scoop' { BeforeAll { $configFile = [IO.Path]::GetTempFileName() $unicode = [Regex]::Unescape('\u4f60\u597d\u3053\u3093\u306b\u3061\u306f') # 你好こんにちは } AfterAll { Remove-Item -Path $configFile -Force } It 'load_cfg should return null if config file does not exist' { load_cfg $configFile | Should -Be $null } It 'set_config should be able to save typed values correctly' { # number $scoopConfig = set_config 'one' 1 $scoopConfig.one | Should -BeExactly 1 # boolean $scoopConfig = set_config 'two' $true $scoopConfig.two | Should -BeTrue $scoopConfig = set_config 'three' $false $scoopConfig.three | Should -BeFalse # underline key $scoopConfig = set_config 'under_line' 'four' $scoopConfig.under_line | Should -BeExactly 'four' # string $scoopConfig = set_config 'five' 'not null' # datetime $scoopConfig = set_config 'time' ([System.DateTime]::Parse('2019-03-18T15:22:09.3930000+00:00', $null, [System.Globalization.DateTimeStyles]::AdjustToUniversal)) $scoopConfig.time | Should -BeOfType [System.DateTime] # non-ASCII $scoopConfig = set_config 'unicode' $unicode $scoopConfig.unicode | Should -Be $unicode } It 'load_cfg should return PSObject if config file exist' { $scoopConfig = load_cfg $configFile $scoopConfig | Should -Not -BeNullOrEmpty $scoopConfig | Should -BeOfType [System.Management.Automation.PSObject] $scoopConfig.one | Should -BeExactly 1 $scoopConfig.two | Should -BeTrue $scoopConfig.three | Should -BeFalse $scoopConfig.under_line | Should -BeExactly 'four' $scoopConfig.five | Should -Be 'not null' $scoopConfig.time | Should -BeOfType [System.DateTime] $scoopConfig.time | Should -Be ([System.DateTime]::Parse('2019-03-18T15:22:09.3930000+00:00', $null, [System.Globalization.DateTimeStyles]::AdjustToUniversal)) $scoopConfig.unicode | Should -Be $unicode } It 'get_config should return exactly the same values' { $scoopConfig = load_cfg $configFile (get_config 'one') | Should -BeExactly 1 (get_config 'two') | Should -BeTrue (get_config 'three') | Should -BeFalse (get_config 'under_line') | Should -BeExactly 'four' (get_config 'five') | Should -Be 'not null' (get_config 'time') | Should -BeOfType [System.DateTime] (get_config 'time') | Should -Be ([System.DateTime]::Parse('2019-03-18T15:22:09.3930000+00:00', $null, [System.Globalization.DateTimeStyles]::AdjustToUniversal)) (get_config 'unicode') | Should -Be $unicode } It 'set_config should remove a value if being set to $null' { $scoopConfig = load_cfg $configFile $scoopConfig = set_config 'five' $null $scoopConfig.five | Should -BeNullOrEmpty } } ================================================ FILE: test/Scoop-Core.Tests.ps1 ================================================ BeforeAll { . "$PSScriptRoot\Scoop-TestLib.ps1" . "$PSScriptRoot\..\lib\core.ps1" . "$PSScriptRoot\..\lib\system.ps1" . "$PSScriptRoot\..\lib\install.ps1" } Describe 'Get-AppFilePath' -Tag 'Scoop' { BeforeAll { $working_dir = setup_working 'is_directory' Mock currentdir { 'local' } -Verifiable -ParameterFilter { $global -eq $false } Mock currentdir { 'global' } -Verifiable -ParameterFilter { $global -eq $true } } It 'should return locally installed program' { Mock Test-Path { $true } -Verifiable -ParameterFilter { $Path -eq 'local\i_am_a_file.txt' } Mock Test-Path { $false } -Verifiable -ParameterFilter { $Path -eq 'global\i_am_a_file.txt' } Get-AppFilePath -App 'is_directory' -File 'i_am_a_file.txt' | Should -Be 'local\i_am_a_file.txt' } It 'should return globally installed program' { Mock Test-Path { $false } -Verifiable -ParameterFilter { $Path -eq 'local\i_am_a_file.txt' } Mock Test-Path { $true } -Verifiable -ParameterFilter { $Path -eq 'global\i_am_a_file.txt' } Get-AppFilePath -App 'is_directory' -File 'i_am_a_file.txt' | Should -Be 'global\i_am_a_file.txt' } It 'should return null if program is not installed' { Get-AppFilePath -App 'is_directory' -File 'i_do_not_exist' | Should -BeNullOrEmpty } It 'should throw if parameter is wrong or missing' { { Get-AppFilePath -App 'is_directory' -File } | Should -Throw { Get-AppFilePath -App -File 'i_am_a_file.txt' } | Should -Throw { Get-AppFilePath -App -File } | Should -Throw } } Describe 'Get-HelperPath' -Tag 'Scoop' { BeforeAll { $working_dir = setup_working 'is_directory' } It 'should return path if program is installed' { Mock Get-AppFilePath { '7zip\current\7z.exe' } Get-HelperPath -Helper 7zip | Should -Be '7zip\current\7z.exe' } It 'should return null if program is not installed' { Mock Get-AppFilePath { $null } Get-HelperPath -Helper 7zip | Should -BeNullOrEmpty } It 'should throw if parameter is wrong or missing' { { Get-HelperPath -Helper } | Should -Throw { Get-HelperPath -Helper Wrong } | Should -Throw } } Describe 'Test-HelperInstalled' -Tag 'Scoop' { It 'should return true if program is installed' { Mock Get-HelperPath { '7z.exe' } Test-HelperInstalled -Helper 7zip | Should -BeTrue } It 'should return false if program is not installed' { Mock Get-HelperPath { $null } Test-HelperInstalled -Helper 7zip | Should -BeFalse } It 'should throw if parameter is wrong or missing' { { Test-HelperInstalled -Helper } | Should -Throw { Test-HelperInstalled -Helper Wrong } | Should -Throw } } Describe 'Test-CommandAvailable' -Tag 'Scoop' { It 'should return true if command exists' { Test-CommandAvailable 'Write-Host' | Should -BeTrue } It "should return false if command doesn't exist" { Test-CommandAvailable 'Write-ThisWillProbablyNotExist' | Should -BeFalse } It 'should throw if parameter is wrong or missing' { { Test-CommandAvailable } | Should -Throw } } Describe 'is_directory' -Tag 'Scoop' { BeforeAll { $working_dir = setup_working 'is_directory' } It 'is_directory recognize directories' { is_directory "$working_dir\i_am_a_directory" | Should -Be $true } It 'is_directory recognize files' { is_directory "$working_dir\i_am_a_file.txt" | Should -Be $false } It 'is_directory is falsey on unknown path' { is_directory "$working_dir\i_do_not_exist" | Should -Be $false } } Describe 'movedir' -Tag 'Scoop', 'Windows' { BeforeAll { $working_dir = setup_working 'movedir' $extract_dir = 'subdir' $extract_to = $null } It 'moves directories with no spaces in path' { $dir = "$working_dir\user" movedir "$dir\_tmp\$extract_dir" "$dir\$extract_to" "$dir\test.txt" | Should -FileContentMatch 'this is the one' "$dir\_tmp\$extract_dir" | Should -Not -Exist } It 'moves directories with spaces in path' { $dir = "$working_dir\user with space" movedir "$dir\_tmp\$extract_dir" "$dir\$extract_to" "$dir\test.txt" | Should -FileContentMatch 'this is the one' "$dir\_tmp\$extract_dir" | Should -Not -Exist # test trailing \ in from dir movedir "$dir\_tmp\$null" "$dir\another" "$dir\another\test.txt" | Should -FileContentMatch 'testing' "$dir\_tmp" | Should -Not -Exist } It 'moves directories with quotes in path' { $dir = "$working_dir\user with 'quote" movedir "$dir\_tmp\$extract_dir" "$dir\$extract_to" "$dir\test.txt" | Should -FileContentMatch 'this is the one' "$dir\_tmp\$extract_dir" | Should -Not -Exist } } Describe 'shim' -Tag 'Scoop', 'Windows' { BeforeAll { $working_dir = setup_working 'shim' $shimdir = shimdir Add-Path $shimdir } It "links a file onto the user's path" { { Get-Command 'shim-test' -ea stop } | Should -Throw { Get-Command 'shim-test.ps1' -ea stop } | Should -Throw { Get-Command 'shim-test.cmd' -ea stop } | Should -Throw { shim-test } | Should -Throw shim "$working_dir\shim-test.ps1" $false 'shim-test' { Get-Command 'shim-test' -ea stop } | Should -Not -Throw { Get-Command 'shim-test.ps1' -ea stop } | Should -Not -Throw { Get-Command 'shim-test.cmd' -ea stop } | Should -Not -Throw shim-test | Should -Be 'Hello, world!' } It 'shims a file with quote in path' { { Get-Command 'shim-test' -ea stop } | Should -Throw { shim-test } | Should -Throw shim "$working_dir\user with 'quote\shim-test.ps1" $false 'shim-test' { Get-Command 'shim-test' -ea stop } | Should -Not -Throw shim-test | Should -Be 'Hello, world!' } AfterEach { rm_shim 'shim-test' $shimdir } } Describe 'rm_shim' -Tag 'Scoop', 'Windows' { BeforeAll { $working_dir = setup_working 'shim' $shimdir = shimdir Add-Path $shimdir } It 'removes shim from path' { shim "$working_dir\shim-test.ps1" $false 'shim-test' rm_shim 'shim-test' $shimdir { Get-Command 'shim-test' -ea stop } | Should -Throw { Get-Command 'shim-test.ps1' -ea stop } | Should -Throw { Get-Command 'shim-test.cmd' -ea stop } | Should -Throw { shim-test } | Should -Throw } } Describe 'get_app_name_from_shim' -Tag 'Scoop', 'Windows' { BeforeAll { $working_dir = setup_working 'shim' $shimdir = shimdir Add-Path $shimdir Mock appsdir { $working_dir } } It 'returns empty string if file does not exist' { get_app_name_from_shim 'non-existent-file' | Should -Be '' } It 'returns app name if file exists and is a shim to an app' { ensure "$working_dir/mockapp/current/" Write-Output '' | Out-File "$working_dir/mockapp/current/mockapp1.ps1" shim "$working_dir/mockapp/current/mockapp1.ps1" $false 'shim-test1' $shim_path1 = (Get-Command 'shim-test1.ps1').Path get_app_name_from_shim "$shim_path1" | Should -Be 'mockapp' ensure "$working_dir/mockapp/1.0.0/" Write-Output '' | Out-File "$working_dir/mockapp/1.0.0/mockapp2.ps1" shim "$working_dir/mockapp/1.0.0/mockapp2.ps1" $false 'shim-test2' $shim_path2 = (Get-Command 'shim-test2.ps1').Path get_app_name_from_shim "$shim_path2" | Should -Be 'mockapp' } It 'returns empty string if file exists and is not a shim' { Write-Output 'lorem ipsum' | Out-File -Encoding ascii "$working_dir/mock-shim.ps1" get_app_name_from_shim "$working_dir/mock-shim.ps1" | Should -Be '' } AfterAll { if (Get-Command 'shim-test1' -ErrorAction SilentlyContinue) { rm_shim 'shim-test1' $shimdir -ErrorAction SilentlyContinue } if (Get-Command 'shim-test2' -ErrorAction SilentlyContinue) { rm_shim 'shim-test2' $shimdir -ErrorAction SilentlyContinue } Remove-Item -Force -Recurse -ErrorAction SilentlyContinue "$working_dir/mockapp" Remove-Item -Force -ErrorAction SilentlyContinue "$working_dir/moch-shim.ps1" } } Describe 'cache_path' -Tag 'Scoop' { It 'returns the correct cache path for a given input' { $url = 'https://example.com/git.zip' $ret = cache_path 'git' '2.44.0' $url $inputStream = [System.IO.MemoryStream]::new([System.Text.Encoding]::UTF8.GetBytes($url)) $sha = (Get-FileHash -Algorithm SHA256 -InputStream $inputStream).Hash.ToLower().Substring(0, 7) $ret | Should -Be "$cachedir\git#2.44.0#$sha.zip" } # # NOTE: Remove this 6 months after the feature ships. It 'returns the old format cache path for a given input' { Mock Test-Path { $true } $ret = cache_path 'git' '2.44.0' 'https://example.com/git.zip' $ret | Should -Be "$cachedir\git#2.44.0#https_example.com_git.zip" } } Describe 'sanitary_path' -Tag 'Scoop' { It 'removes invalid path characters from a string' { $path = 'test?.json' $valid_path = sanitary_path $path $valid_path | Should -Be 'test.json' } } Describe 'app' -Tag 'Scoop' { It 'parses the bucket name from an app query' { $query = 'C:\test.json' $app, $bucket, $version = parse_app $query $app | Should -Be 'C:\test.json' $bucket | Should -BeNullOrEmpty $version | Should -BeNullOrEmpty $query = 'test.json' $app, $bucket, $version = parse_app $query $app | Should -Be 'test.json' $bucket | Should -BeNullOrEmpty $version | Should -BeNullOrEmpty $query = '.\test.json' $app, $bucket, $version = parse_app $query $app | Should -Be '.\test.json' $bucket | Should -BeNullOrEmpty $version | Should -BeNullOrEmpty $query = '..\test.json' $app, $bucket, $version = parse_app $query $app | Should -Be '..\test.json' $bucket | Should -BeNullOrEmpty $version | Should -BeNullOrEmpty $query = '\\share\test.json' $app, $bucket, $version = parse_app $query $app | Should -Be '\\share\test.json' $bucket | Should -BeNullOrEmpty $version | Should -BeNullOrEmpty $query = 'https://example.com/test.json' $app, $bucket, $version = parse_app $query $app | Should -Be 'https://example.com/test.json' $bucket | Should -BeNullOrEmpty $version | Should -BeNullOrEmpty $query = 'test' $app, $bucket, $version = parse_app $query $app | Should -Be 'test' $bucket | Should -BeNullOrEmpty $version | Should -BeNullOrEmpty $query = 'extras/enso' $app, $bucket, $version = parse_app $query $app | Should -Be 'enso' $bucket | Should -Be 'extras' $version | Should -BeNullOrEmpty $query = 'test-app' $app, $bucket, $version = parse_app $query $app | Should -Be 'test-app' $bucket | Should -BeNullOrEmpty $version | Should -BeNullOrEmpty $query = 'test-bucket/test-app' $app, $bucket, $version = parse_app $query $app | Should -Be 'test-app' $bucket | Should -Be 'test-bucket' $version | Should -BeNullOrEmpty $query = 'test-bucket/test-app@1.8.0' $app, $bucket, $version = parse_app $query $app | Should -Be 'test-app' $bucket | Should -Be 'test-bucket' $version | Should -Be '1.8.0' $query = 'test-bucket/test-app@1.8.0-rc2' $app, $bucket, $version = parse_app $query $app | Should -Be 'test-app' $bucket | Should -Be 'test-bucket' $version | Should -Be '1.8.0-rc2' $query = 'test-bucket/test_app' $app, $bucket, $version = parse_app $query $app | Should -Be 'test_app' $bucket | Should -Be 'test-bucket' $version | Should -BeNullOrEmpty $query = 'test-bucket/test_app@1.8.0' $app, $bucket, $version = parse_app $query $app | Should -Be 'test_app' $bucket | Should -Be 'test-bucket' $version | Should -Be '1.8.0' $query = 'test-bucket/test_app@1.8.0-rc2' $app, $bucket, $version = parse_app $query $app | Should -Be 'test_app' $bucket | Should -Be 'test-bucket' $version | Should -Be '1.8.0-rc2' } } Describe 'Format Architecture String' -Tag 'Scoop' { It 'should keep correct architectures' { Format-ArchitectureString '32bit' | Should -Be '32bit' Format-ArchitectureString '32' | Should -Be '32bit' Format-ArchitectureString 'x86' | Should -Be '32bit' Format-ArchitectureString 'X86' | Should -Be '32bit' Format-ArchitectureString 'i386' | Should -Be '32bit' Format-ArchitectureString '386' | Should -Be '32bit' Format-ArchitectureString 'i686' | Should -Be '32bit' Format-ArchitectureString '64bit' | Should -Be '64bit' Format-ArchitectureString '64' | Should -Be '64bit' Format-ArchitectureString 'x64' | Should -Be '64bit' Format-ArchitectureString 'X64' | Should -Be '64bit' Format-ArchitectureString 'amd64' | Should -Be '64bit' Format-ArchitectureString 'AMD64' | Should -Be '64bit' Format-ArchitectureString 'x86_64' | Should -Be '64bit' Format-ArchitectureString 'x86-64' | Should -Be '64bit' Format-ArchitectureString 'arm64' | Should -Be 'arm64' Format-ArchitectureString 'arm' | Should -Be 'arm64' Format-ArchitectureString 'aarch64' | Should -Be 'arm64' Format-ArchitectureString 'ARM64' | Should -Be 'arm64' Format-ArchitectureString 'ARM' | Should -Be 'arm64' Format-ArchitectureString 'AARCH64' | Should -Be 'arm64' } It 'should fallback to the default architecture on empty input' { Format-ArchitectureString '' | Should -Be $(Get-DefaultArchitecture) Format-ArchitectureString $null | Should -Be $(Get-DefaultArchitecture) } It 'should show an error with an invalid architecture' { { Format-ArchitectureString 'PPC' } | Should -Throw "Invalid architecture: 'ppc'" } } ================================================ FILE: test/Scoop-Decompress.Tests.ps1 ================================================ BeforeAll { . "$PSScriptRoot\Scoop-TestLib.ps1" . "$PSScriptRoot\..\lib\core.ps1" . "$PSScriptRoot\..\lib\decompress.ps1" . "$PSScriptRoot\..\lib\install.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" . "$PSScriptRoot\..\lib\versions.ps1" } Describe 'Decompression function' -Tag 'Scoop', 'Windows', 'Decompress' { BeforeAll { $working_dir = setup_working 'decompress' function test_extract($extract_fn, $from, $removal) { $to = (strip_ext $from) -replace '\.tar$', '' & $extract_fn ($from -replace '/', '\') ($to -replace '/', '\') -Removal:$removal -ExtractDir $args[0] return $to } } Context 'Decompression test cases should exist' { BeforeAll { $testcases = "$working_dir\TestCases.zip" } It 'Test cases should exist and hash should match' { $testcases | Should -Exist (Get-FileHash -Path $testcases -Algorithm SHA256).Hash.ToLower() | Should -Be '591072faabd419b77932b7023e5899b4e05c0bf8e6859ad367398e6bfe1eb203' } It 'Test cases should be extracted correctly' { { Microsoft.PowerShell.Archive\Expand-Archive -Path $testcases -DestinationPath $working_dir } | Should -Not -Throw } } Context '7zip extraction' { BeforeAll { if ($env:CI) { Mock Get-AppFilePath { (Get-Command 7z.exe).Path } } elseif (!(installed 7zip)) { scoop install 7zip } $test1 = "$working_dir\7ZipTest1.7z" $test2 = "$working_dir\7ZipTest2.tgz" $test3 = "$working_dir\7ZipTest3.tar.bz2" $test4 = "$working_dir\7ZipTest4.tar.gz" $test5_1 = "$working_dir\7ZipTest5.7z.001" $test5_2 = "$working_dir\7ZipTest5.7z.002" $test5_3 = "$working_dir\7ZipTest5.7z.003" $test6_1 = "$working_dir\7ZipTest6.part01.rar" $test6_2 = "$working_dir\7ZipTest6.part02.rar" $test6_3 = "$working_dir\7ZipTest6.part03.rar" $test7 = "$working_dir\NSISTest.exe" } AfterEach { Remove-Item -Path $to -Recurse -Force } It 'extract normal compressed file' { $to = test_extract 'Expand-7zipArchive' $test1 $to | Should -Exist "$to\empty" | Should -Exist (Get-ChildItem $to).Count | Should -Be 4 } It 'extract "extract_dir" correctly' { $to = test_extract 'Expand-7zipArchive' $test1 $false 'tmp' $to | Should -Exist "$to\empty" | Should -Exist (Get-ChildItem $to).Count | Should -Be 1 } It 'extract "extract_dir" with spaces correctly' { $to = test_extract 'Expand-7zipArchive' $test1 $false 'tmp 2' $to | Should -Exist "$to\empty" | Should -Exist (Get-ChildItem $to).Count | Should -Be 1 } It 'extract "extract_dir" with nested folder with same name' { $to = test_extract 'Expand-7zipArchive' $test1 $false 'keep\sub' $to | Should -Exist "$to\keep\empty" | Should -Exist (Get-ChildItem $to).Count | Should -Be 1 (Get-ChildItem "$to\keep").Count | Should -Be 1 } It 'extract nested compressed file' { # file ext: tgz $to = test_extract 'Expand-7zipArchive' $test2 $to | Should -Exist "$to\empty" | Should -Exist (Get-ChildItem $to).Count | Should -Be 1 # file ext: tar.bz2 $to = test_extract 'Expand-7zipArchive' $test3 $to | Should -Exist "$to\empty" | Should -Exist (Get-ChildItem $to).Count | Should -Be 1 } It 'extract nested compressed file with different inner name' { $to = test_extract 'Expand-7zipArchive' $test4 $to | Should -Exist "$to\empty" | Should -Exist (Get-ChildItem $to).Count | Should -Be 1 } It 'extract splited 7z archives (.001, .002, ...)' { $to = test_extract 'Expand-7zipArchive' $test5_1 $to | Should -Exist "$to\empty" | Should -Exist (Get-ChildItem $to).Count | Should -Be 1 } It 'extract splited RAR archives (.part01.rar, .part02.rar, ...)' { $to = test_extract 'Expand-7zipArchive' $test6_1 $to | Should -Exist "$to\dummy" | Should -Exist (Get-ChildItem $to).Count | Should -Be 1 } It 'extract NSIS installer' { $to = test_extract 'Expand-7zipArchive' $test7 $to | Should -Exist "$to\empty" | Should -Exist (Get-ChildItem $to).Count | Should -Be 1 } It 'self-extract NSIS installer' { $to = "$working_dir\NSIS Test" $null = Invoke-ExternalCommand -FilePath $test7 -ArgumentList @('/S', '/NCRC', "/D=$to") $to | Should -Exist "$to\empty" | Should -Exist (Get-ChildItem $to).Count | Should -Be 1 } It 'works with "-Removal" switch ($removal param)' { $test1 | Should -Exist $to = test_extract 'Expand-7zipArchive' $test1 $true $to | Should -Exist $test1 | Should -Not -Exist $test5_1 | Should -Exist $test5_2 | Should -Exist $test5_3 | Should -Exist $to = test_extract 'Expand-7zipArchive' $test5_1 $true $to | Should -Exist $test5_1 | Should -Not -Exist $test5_2 | Should -Not -Exist $test5_3 | Should -Not -Exist $test6_1 | Should -Exist $test6_2 | Should -Exist $test6_3 | Should -Exist $to = test_extract 'Expand-7zipArchive' $test6_1 $true $to | Should -Exist $test6_1 | Should -Not -Exist $test6_2 | Should -Not -Exist $test6_3 | Should -Not -Exist } } Context 'msi extraction' { BeforeAll { if ($env:CI) { Mock Get-AppFilePath { $env:SCOOP_LESSMSI_PATH } } elseif (!(installed lessmsi)) { scoop install lessmsi } Copy-Item "$working_dir\MSITest.msi" "$working_dir\MSI Test.msi" $test1 = "$working_dir\MSITest.msi" $test2 = "$working_dir\MSI Test.msi" $test3 = "$working_dir\MSITestNull.msi" } It 'extract normal MSI file using msiexec' { Mock get_config { $false } $to = test_extract 'Expand-MsiArchive' $test1 $to | Should -Exist "$to\MSITest\empty" | Should -Exist (Get-ChildItem "$to\MSITest").Count | Should -Be 1 } It 'extract normal MSI file with whitespace in path using msiexec' { Mock get_config { $false } $to = test_extract 'Expand-MsiArchive' $test2 $to | Should -Exist "$to\MSITest\empty" | Should -Exist (Get-ChildItem "$to\MSITest").Count | Should -Be 1 } It 'extract normal MSI file using lessmsi' { Mock get_config { $true } $to = test_extract 'Expand-MsiArchive' $test1 $to | Should -Exist } It 'extract normal MSI file with whitespace in path using lessmsi' { Mock get_config { $true } $to = test_extract 'Expand-MsiArchive' $test2 $to | Should -Exist } It 'extract empty MSI file using lessmsi' { Mock get_config { $true } $to = test_extract 'Expand-MsiArchive' $test3 $to | Should -Exist } It 'works with "-Removal" switch ($removal param)' { Mock get_config { $false } $test1 | Should -Exist test_extract 'Expand-MsiArchive' $test1 $true $test1 | Should -Not -Exist } } Context 'inno extraction' { BeforeAll { if ($env:CI) { Mock Get-AppFilePath { $env:SCOOP_INNOUNP_PATH } } elseif (!(installed innounp)) { scoop install innounp } $test = "$working_dir\InnoTest.exe" } It 'extract Inno Setup file' { $to = test_extract 'Expand-InnoArchive' $test $to | Should -Exist "$to\empty" | Should -Exist (Get-ChildItem $to).Count | Should -Be 1 } It 'works with "-Removal" switch ($removal param)' { $test | Should -Exist test_extract 'Expand-InnoArchive' $test $true $test | Should -Not -Exist } } Context 'zip extraction' { BeforeAll { $test = "$working_dir\ZipTest.zip" } It 'extract compressed file' { $to = test_extract 'Expand-ZipArchive' $test $to | Should -Exist "$to\empty" | Should -Exist (Get-ChildItem $to).Count | Should -Be 1 } It 'works with "-Removal" switch ($removal param)' { $test | Should -Exist test_extract 'Expand-ZipArchive' $test $true $test | Should -Not -Exist } } } ================================================ FILE: test/Scoop-Depends.Tests.ps1 ================================================ BeforeAll { . "$PSScriptRoot\Scoop-TestLib.ps1" . "$PSScriptRoot\..\lib\core.ps1" . "$PSScriptRoot\..\lib\depends.ps1" . "$PSScriptRoot\..\lib\buckets.ps1" . "$PSScriptRoot\..\lib\install.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" } Describe 'Package Dependencies' -Tag 'Scoop' { Context 'Requirement function' { It 'Test 7zip requirement' { Test-7zipRequirement -Uri 'test.xz' | Should -BeTrue Test-7zipRequirement -Uri 'test.bin' | Should -BeFalse Test-7zipRequirement -Uri @('test.xz', 'test.bin') | Should -BeTrue } It 'Test lessmsi requirement' { Mock get_config { $true } Test-LessmsiRequirement -Uri 'test.msi' | Should -BeTrue Test-LessmsiRequirement -Uri 'test.bin' | Should -BeFalse Test-LessmsiRequirement -Uri @('test.msi', 'test.bin') | Should -BeTrue } It 'Allow $Uri be $null' { Test-7zipRequirement -Uri $null | Should -BeFalse Test-LessmsiRequirement -Uri $null | Should -BeFalse } } Context 'InstallationHelper function' { BeforeAll { $working_dir = setup_working 'format/formatted' $manifest1 = parse_json (Join-Path $working_dir '3-array-with-single-and-multi.json') $manifest2 = parse_json (Join-Path $working_dir '4-script-block.json') Mock Test-HelperInstalled { $false } } It 'Get helpers from URL' { Mock get_config { $true } Get-InstallationHelper -Manifest $manifest1 -Architecture '32bit' | Should -Be @('lessmsi') } It 'Get helpers from script' { Mock get_config { $false } Get-InstallationHelper -Manifest $manifest2 -Architecture '32bit' | Should -Be @('7zip') } It 'Helpers reflect config changes' { Mock get_config { $false } -ParameterFilter { $name -eq 'USE_LESSMSI' } Mock get_config { $true } -ParameterFilter { $name -eq 'USE_EXTERNAL_7ZIP' } Get-InstallationHelper -Manifest $manifest1 -Architecture '32bit' | Should -BeNullOrEmpty Get-InstallationHelper -Manifest $manifest2 -Architecture '32bit' | Should -BeNullOrEmpty } It 'Not return installed helpers' { Mock get_config { $true } -ParameterFilter { $name -eq 'USE_LESSMSI' } Mock get_config { $false } -ParameterFilter { $name -eq 'USE_EXTERNAL_7ZIP' } Mock Test-HelperInstalled { $true }-ParameterFilter { $Helper -eq '7zip' } Mock Test-HelperInstalled { $false }-ParameterFilter { $Helper -eq 'Lessmsi' } Get-InstallationHelper -Manifest $manifest1 -Architecture '32bit' | Should -Be @('lessmsi') Get-InstallationHelper -Manifest $manifest2 -Architecture '32bit' | Should -BeNullOrEmpty Mock Test-HelperInstalled { $false }-ParameterFilter { $Helper -eq '7zip' } Mock Test-HelperInstalled { $true }-ParameterFilter { $Helper -eq 'Lessmsi' } Get-InstallationHelper -Manifest $manifest1 -Architecture '32bit' | Should -BeNullOrEmpty Get-InstallationHelper -Manifest $manifest2 -Architecture '32bit' | Should -Be @('7zip') } } Context 'Dependencies resolution' { BeforeAll { Mock Test-HelperInstalled { $false } Mock get_config { $true } -ParameterFilter { $name -eq 'USE_LESSMSI' } Mock get_config { $false } -ParameterFilter { $name -eq 'USE_EXTERNAL_7ZIP' } Mock Get-Manifest { 'lessmsi', @{}, $null, $null } -ParameterFilter { $app -eq 'lessmsi' } Mock Get-Manifest { '7zip', @{ url = 'test.msi' }, $null, $null } -ParameterFilter { $app -eq '7zip' } Mock Get-Manifest { 'innounp', @{}, $null, $null } -ParameterFilter { $app -eq 'innounp' } } It 'Resolve install dependencies' { Mock Get-Manifest { 'test', @{ url = 'test.7z' }, $null, $null } Get-Dependency -AppName 'test' -Architecture '32bit' | Should -Be @('lessmsi', '7zip', 'test') Mock Get-Manifest { 'test', @{ innosetup = $true }, $null, $null } Get-Dependency -AppName 'test' -Architecture '32bit' | Should -Be @('innounp', 'test') } It 'Resolve script dependencies' { Mock Get-Manifest { 'test', @{ pre_install = 'Expand-7zipArchive ' }, $null, $null } Get-Dependency -AppName 'test' -Architecture '32bit' | Should -Be @('lessmsi', '7zip', 'test') } It 'Resolve runtime dependencies' { Mock Get-Manifest { 'depends', @{}, $null, $null } -ParameterFilter { $app -eq 'depends' } Mock Get-Manifest { 'test', @{ depends = 'depends' }, $null, $null } Get-Dependency -AppName 'test' -Architecture '32bit' | Should -Be @('depends', 'test') } It 'Keep bucket name of app' { Mock Get-Manifest { 'depends', @{}, 'anotherbucket', $null } -ParameterFilter { $app -eq 'anotherbucket/depends' } Mock Get-Manifest { 'test', @{ depends = 'anotherbucket/depends' }, 'bucket', $null } Get-Dependency -AppName 'bucket/test' -Architecture '32bit' | Should -Be @('anotherbucket/depends', 'bucket/test') } } } ================================================ FILE: test/Scoop-Download.Tests.ps1 ================================================ BeforeAll { . "$PSScriptRoot\Scoop-TestLib.ps1" . "$PSScriptRoot\..\lib\core.ps1" . "$PSScriptRoot\..\lib\download.ps1" } Describe 'Test-Aria2Enabled' -Tag 'Scoop' { It 'should return true if aria2 is installed' { Mock Test-HelperInstalled { $true } Mock get_config { $true } Test-Aria2Enabled | Should -BeTrue } It 'should return false if aria2 is not installed' { Mock Test-HelperInstalled { $false } Mock get_config { $false } Test-Aria2Enabled | Should -BeFalse Mock Test-HelperInstalled { $false } Mock get_config { $true } Test-Aria2Enabled | Should -BeFalse Mock Test-HelperInstalled { $true } Mock get_config { $false } Test-Aria2Enabled | Should -BeFalse } } Describe 'url_filename' -Tag 'Scoop' { It 'should extract the real filename from an url' { url_filename 'http://example.org/foo.txt' | Should -Be 'foo.txt' url_filename 'http://example.org/foo.txt?var=123' | Should -Be 'foo.txt' } It 'can be tricked with a hash to override the real filename' { url_filename 'http://example.org/foo-v2.zip#/foo.zip' | Should -Be 'foo.zip' } } Describe 'url_remote_filename' -Tag 'Scoop' { It 'should extract the real filename from an url' { url_remote_filename 'http://example.org/foo.txt' | Should -Be 'foo.txt' url_remote_filename 'http://example.org/foo.txt?var=123' | Should -Be 'foo.txt' } It 'can not be tricked with a hash to override the real filename' { url_remote_filename 'http://example.org/foo-v2.zip#/foo.zip' | Should -Be 'foo-v2.zip' } } ================================================ FILE: test/Scoop-GetOpts.Tests.ps1 ================================================ BeforeAll { . "$PSScriptRoot\Scoop-TestLib.ps1" . "$PSScriptRoot\..\lib\getopt.ps1" } Describe 'getopt' -Tag 'Scoop' { It 'handle short option with required argument missing' { $null, $null, $err = getopt '-x' 'x:' '' $err | Should -Be 'Option -x requires an argument.' $null, $null, $err = getopt '-xy' 'x:y' '' $err | Should -Be 'Option -x requires an argument.' } It 'handle long option with required argument missing' { $null, $null, $err = getopt '--arb' '' 'arb=' $err | Should -Be 'Option --arb requires an argument.' } It 'handle space in quote' { $opt, $rem, $err = getopt '-x', 'space arg' 'x:' '' $err | Should -BeNullOrEmpty $opt.x | Should -Be 'space arg' } It 'handle unrecognized short option' { $null, $null, $err = getopt '-az' 'a' '' $err | Should -Be 'Option -z not recognized.' } It 'handle unrecognized long option' { $null, $null, $err = getopt '--non-exist' '' '' $err | Should -Be 'Option --non-exist not recognized.' $null, $null, $err = getopt '--global', '--another' 'abc:de:' 'global', 'one' $err | Should -Be 'Option --another not recognized.' } It 'remaining args returned' { $opt, $rem, $err = getopt '-g', 'rem' 'g' '' $err | Should -BeNullOrEmpty $opt.g | Should -BeTrue $rem | Should -Not -BeNullOrEmpty $rem.length | Should -Be 1 $rem[0] | Should -Be 'rem' } It 'get a long flag and a short option with argument' { $a = '--global -a 32bit test' -split ' ' $opt, $rem, $err = getopt $a 'ga:' 'global', 'arch=' $err | Should -BeNullOrEmpty $opt.global | Should -BeTrue $opt.a | Should -Be '32bit' } It 'handles regex characters' { $a = '-?' { $opt, $rem, $err = getopt $a 'ga:' 'global' 'arch=' } | Should -Not -Throw { $null, $null, $null = getopt $a '?:' 'help' | Should -Not -Throw } } It 'handles short option without required argument' { $null, $null, $err = getopt '-x' 'x' '' $err | Should -BeNullOrEmpty } It 'handles long option without required argument' { $opt, $null, $err = getopt '--long-arg' '' 'long-arg' $err | Should -BeNullOrEmpty $opt.'long-arg' | Should -BeTrue } It 'handles long option with required argument' { $opt, $null, $err = getopt '--long-arg', 'test' '' 'long-arg=' $err | Should -BeNullOrEmpty $opt.'long-arg' | Should -Be 'test' } It 'handles the option terminator' { $opt, $rem, $err = getopt '--long-arg', '--' '' 'long-arg' $err | Should -BeNullOrEmpty $opt.'long-arg' | Should -BeTrue $rem[0] | Should -BeNullOrEmpty $opt, $rem, $err = getopt '--long-arg', '--', '-x', '-y' 'xy' 'long-arg' $err | Should -BeNullOrEmpty $opt.'long-arg' | Should -BeTrue $opt.'x' | Should -BeNullOrEmpty $opt.'y' | Should -BeNullOrEmpty $rem[0] | Should -Be '-x' $rem[1] | Should -Be '-y' } } ================================================ FILE: test/Scoop-Install.Tests.ps1 ================================================ BeforeAll { . "$PSScriptRoot\Scoop-TestLib.ps1" . "$PSScriptRoot\..\lib\core.ps1" . "$PSScriptRoot\..\lib\system.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" . "$PSScriptRoot\..\lib\install.ps1" } Describe 'appname_from_url' -Tag 'Scoop' { It 'should extract the correct name' { appname_from_url 'https://example.org/directory/foobar.json' | Should -Be 'foobar' } } Describe 'is_in_dir' -Tag 'Scoop', 'Windows' { It 'should work correctly' { is_in_dir 'C:\test' 'C:\foo' | Should -BeFalse is_in_dir 'C:\test' 'C:\test\foo\baz.zip' | Should -BeTrue is_in_dir "$PSScriptRoot\..\" "$PSScriptRoot" | Should -BeFalse } } Describe 'env add and remove path' -Tag 'Scoop', 'Windows' { BeforeAll { # test data $manifest = @{ 'env_add_path' = @('foo', 'bar', '.', '..') } $testdir = Join-Path $PSScriptRoot 'path-test-directory' $global = $false } It 'should concat the correct path' { Mock Add-Path {} Mock Remove-Path {} # adding env_add_path $manifest $testdir $global Should -Invoke -CommandName Add-Path -Times 1 -ParameterFilter { $Path -like "$testdir\foo" } Should -Invoke -CommandName Add-Path -Times 1 -ParameterFilter { $Path -like "$testdir\bar" } Should -Invoke -CommandName Add-Path -Times 1 -ParameterFilter { $Path -like $testdir } Should -Invoke -CommandName Add-Path -Times 0 -ParameterFilter { $Path -like $PSScriptRoot } env_rm_path $manifest $testdir $global Should -Invoke -CommandName Remove-Path -Times 1 -ParameterFilter { $Path -like "$testdir\foo" } Should -Invoke -CommandName Remove-Path -Times 1 -ParameterFilter { $Path -like "$testdir\bar" } Should -Invoke -CommandName Remove-Path -Times 1 -ParameterFilter { $Path -like $testdir } Should -Invoke -CommandName Remove-Path -Times 0 -ParameterFilter { $Path -like $PSScriptRoot } } } Describe 'shim_def' -Tag 'Scoop' { It 'should use strings correctly' { $target, $name, $shimArgs = shim_def 'command.exe' $target | Should -Be 'command.exe' $name | Should -Be 'command' $shimArgs | Should -BeNullOrEmpty } It 'should expand the array correctly' { $target, $name, $shimArgs = shim_def @('foo.exe', 'bar') $target | Should -Be 'foo.exe' $name | Should -Be 'bar' $shimArgs | Should -BeNullOrEmpty $target, $name, $shimArgs = shim_def @('foo.exe', 'bar', '--test') $target | Should -Be 'foo.exe' $name | Should -Be 'bar' $shimArgs | Should -Be '--test' } } Describe 'persist_def' -Tag 'Scoop' { It 'parses string correctly' { $source, $target = persist_def 'test' $source | Should -Be 'test' $target | Should -Be 'test' } It 'should handle sub-folder' { $source, $target = persist_def 'foo/bar' $source | Should -Be 'foo/bar' $target | Should -Be 'foo/bar' } It 'should handle arrays' { # both specified $source, $target = persist_def @('foo', 'bar') $source | Should -Be 'foo' $target | Should -Be 'bar' # only first specified $source, $target = persist_def @('foo') $source | Should -Be 'foo' $target | Should -Be 'foo' # null value specified $source, $target = persist_def @('foo', $null) $source | Should -Be 'foo' $target | Should -Be 'foo' } } ================================================ FILE: test/Scoop-Manifest.Tests.ps1 ================================================ BeforeAll { . "$PSScriptRoot\..\lib\json.ps1" . "$PSScriptRoot\..\lib\manifest.ps1" } Describe 'JSON parse and beautify' -Tag 'Scoop' { Context 'Parse JSON' { It 'success with valid json' { { parse_json "$PSScriptRoot\fixtures\manifest\wget.json" } | Should -Not -Throw } It 'fails with invalid json' { { parse_json "$PSScriptRoot\fixtures\manifest\broken_wget.json" } | Should -Throw } } Context 'Beautify JSON' { BeforeDiscovery { $manifests = (Get-ChildItem "$PSScriptRoot\fixtures\format\formatted" -File -Filter '*.json').Name } BeforeAll { $format = "$PSScriptRoot\fixtures\format" } It '<_>' -ForEach $manifests { $pretty_json = (parse_json "$format\unformatted\$_") | ConvertToPrettyJson $correct = (Get-Content "$format\formatted\$_") -join "`r`n" $correct.CompareTo($pretty_json) | Should -Be 0 } } } Describe 'Handle ARM64 and correctly fallback' -Tag 'Scoop' { It 'Should return "arm64" if supported' { $manifest1 = @{ url = 'test'; architecture = @{ 'arm64' = @{ pre_install = 'test' } } } $manifest2 = @{ url = 'test'; pre_install = "'arm64'" } $manifest3 = @{ architecture = @{ 'arm64' = @{ url = 'test' } } } Get-SupportedArchitecture $manifest1 'arm64' | Should -Be 'arm64' Get-SupportedArchitecture $manifest2 'arm64' | Should -Be 'arm64' Get-SupportedArchitecture $manifest3 'arm64' | Should -Be 'arm64' } It 'Should return "64bit" if unsupported on Windows 11' { $WindowsBuild = 22000 $manifest1 = @{ url = 'test' } $manifest2 = @{ architecture = @{ '64bit' = @{ url = 'test' } } } Get-SupportedArchitecture $manifest1 'arm64' | Should -Be '64bit' Get-SupportedArchitecture $manifest2 'arm64' | Should -Be '64bit' } It 'Should return "32bit" if unsupported on Windows 10' { $WindowsBuild = 19044 $manifest2 = @{ url = 'test' } $manifest1 = @{ url = 'test'; architecture = @{ '64bit' = @{ pre_install = 'test' } } } $manifest3 = @{ architecture = @{ '64bit' = @{ url = 'test' } } } Get-SupportedArchitecture $manifest1 'arm64' | Should -Be '32bit' Get-SupportedArchitecture $manifest2 'arm64' | Should -Be '32bit' Get-SupportedArchitecture $manifest3 'arm64' | Should -BeNullOrEmpty } } Describe 'Manifest Validator' -Tag 'Validator' { # Could not use backslash '\' in Linux/macOS for .NET object 'Scoop.Validator' BeforeAll { Add-Type -Path "$PSScriptRoot\..\supporting\validator\bin\Scoop.Validator.dll" $schema = "$PSScriptRoot/../schema.json" } It 'Scoop.Validator is available' { ([System.Management.Automation.PSTypeName]'Scoop.Validator').Type | Should -Be 'Scoop.Validator' } It 'fails with broken schema' { $validator = New-Object Scoop.Validator("$PSScriptRoot/fixtures/manifest/broken_schema.json", $true) $validator.Validate("$PSScriptRoot/fixtures/manifest/wget.json") | Should -BeFalse $validator.Errors.Count | Should -Be 1 $validator.Errors | Select-Object -First 1 | Should -Match 'broken_schema.*(line 6).*(position 4)' } It 'fails with broken manifest' { $validator = New-Object Scoop.Validator($schema, $true) $validator.Validate("$PSScriptRoot/fixtures/manifest/broken_wget.json") | Should -BeFalse $validator.Errors.Count | Should -Be 1 $validator.Errors | Select-Object -First 1 | Should -Match 'broken_wget.*(line 5).*(position 4)' } It 'fails with invalid manifest' { $validator = New-Object Scoop.Validator($schema, $true) $validator.Validate("$PSScriptRoot/fixtures/manifest/invalid_wget.json") | Should -BeFalse $validator.Errors.Count | Should -Be 16 $validator.Errors | Select-Object -First 1 | Should -Match "Property 'randomproperty' has not been defined and the schema does not allow additional properties\." $validator.Errors | Select-Object -Last 1 | Should -Match 'Required properties are missing from object: version\.' } } ================================================ FILE: test/Scoop-TestLib.ps1 ================================================ # copies fixtures to a working directory function setup_working($name) { $fixtures = "$PSScriptRoot\fixtures\$name" if (!(Test-Path $fixtures)) { Write-Host "couldn't find fixtures for $name at $fixtures" -f red exit 1 } # reset working dir $working_dir = "$([IO.Path]::GetTempPath())ScoopTestFixtures\$name" if (Test-Path $working_dir) { Remove-Item -Recurse -Force $working_dir } # set up Copy-Item $fixtures -Destination $working_dir -Recurse return $working_dir } ================================================ FILE: test/Scoop-Versions.Tests.ps1 ================================================ BeforeAll { . "$PSScriptRoot\Scoop-TestLib.ps1" . "$PSScriptRoot\..\lib\versions.ps1" } Describe 'versions comparison' -Tag 'Scoop' { Context 'semver compliant versions' { It 'handles major.minor.patch progressing' { Compare-Version '0.1.0' '0.1.1' | Should -Be 1 Compare-Version '0.1.1' '0.2.0' | Should -Be 1 Compare-Version '0.2.0' '1.0.0' | Should -Be 1 } It 'handles pre-release versioning progression' { Compare-Version '0.4.0' '0.5.0-alpha.1' | Should -Be 1 Compare-Version '0.5.0-alpha.1' '0.5.0-alpha.2' | Should -Be 1 Compare-Version '0.5.0-alpha.2' '0.5.0-alpha.10' | Should -Be 1 Compare-Version '0.5.0-alpha.10' '0.5.0-beta' | Should -Be 1 Compare-Version '0.5.0-beta' '0.5.0-alpha.10' | Should -Be -1 Compare-Version '0.5.0-beta' '0.5.0-beta.0' | Should -Be 1 } It 'handles the pre-release tags in an alphabetic order' { Compare-Version '0.5.0-rc.1' '0.5.0-z' | Should -Be 1 Compare-Version '0.5.0-rc.1' '0.5.0-howdy' | Should -Be -1 Compare-Version '0.5.0-howdy' '0.5.0-rc.1' | Should -Be 1 } } Context 'semver semi-compliant versions' { It 'handles Windows-styled major.minor.patch.build progression' { Compare-Version '0.0.0.0' '0.0.0.1' | Should -Be 1 Compare-Version '0.0.0.1' '0.0.0.2' | Should -Be 1 Compare-Version '0.0.0.2' '0.0.1.0' | Should -Be 1 Compare-Version '0.0.1.0' '0.0.1.1' | Should -Be 1 Compare-Version '0.0.1.1' '0.0.1.2' | Should -Be 1 Compare-Version '0.0.1.2' '0.0.2.0' | Should -Be 1 Compare-Version '0.0.2.0' '0.1.0.0' | Should -Be 1 Compare-Version '0.1.0.0' '0.1.0.1' | Should -Be 1 Compare-Version '0.1.0.1' '0.1.0.2' | Should -Be 1 Compare-Version '0.1.0.2' '0.1.1.0' | Should -Be 1 Compare-Version '0.1.1.0' '0.1.1.1' | Should -Be 1 Compare-Version '0.1.1.1' '0.1.1.2' | Should -Be 1 Compare-Version '0.1.1.2' '0.2.0.0' | Should -Be 1 Compare-Version '0.2.0.0' '1.0.0.0' | Should -Be 1 } It 'handles partial semver version differences' { Compare-Version '1' '1.1' | Should -Be 1 Compare-Version '1' '1.0' | Should -Be 1 Compare-Version '1.1.0.0' '1.1' | Should -Be -1 Compare-Version '1.4' '1.3.0' | Should -Be -1 Compare-Version '1.4' '1.3.255.255' | Should -Be -1 Compare-Version '1.4' '1.4.4' | Should -Be 1 Compare-Version '1.1.1_8' '1.1.1' | Should -Be -1 Compare-Version '1.1.1_8' '1.1.1_9' | Should -Be 1 Compare-Version '1.1.1_10' '1.1.1_9' | Should -Be -1 Compare-Version '1.1.1b' '1.1.1a' | Should -Be -1 Compare-Version '1.1.1a' '1.1.1b' | Should -Be 1 Compare-Version '1.1a2' '1.1a3' | Should -Be 1 Compare-Version '1.1.1a10' '1.1.1b1' | Should -Be 1 } It 'handles dash-style versions' { Compare-Version '1.8.9' '1.8.5-1' | Should -Be -1 Compare-Version '7.0.4-9' '7.0.4-10' | Should -Be 1 Compare-Version '7.0.4-9' '7.0.4-8' | Should -Be -1 Compare-Version '2019-01-01' '2019-01-02' | Should -Be 1 Compare-Version '2019-01-02' '2019-01-01' | Should -Be -1 Compare-Version '2018-01-01' '2019-01-01' | Should -Be 1 Compare-Version '2019-01-01' '2018-01-01' | Should -Be -1 } It 'handles post-release tagging ("+")' { Compare-Version '1' '1+hotfix.0' | Should -Be 1 Compare-Version '1.0.0' '1.0.0+hotfix.0' | Should -Be 1 Compare-Version '1.0.0+hotfix.0' '1.0.0+hotfix.1' | Should -Be 1 Compare-Version '1.0.0+hotfix.1' '1.0.1' | Should -Be 1 Compare-Version '1.0.0+1.1' '1.0.0+1' | Should -Be -1 } } Context 'other misc versions' { It 'handles plain text string' { Compare-Version 'latest' '20150405' | Should -Be -1 Compare-Version '0.5alpha' '0.5' | Should -Be 1 Compare-Version '0.5' '0.5Beta' | Should -Be -1 Compare-Version '0.4' '0.5Beta' | Should -Be 1 } It 'handles empty string' { Compare-Version '7.0.4-9' '' | Should -Be -1 } It 'handles equal versions' { function get_config { $null } Compare-Version '12.0' '12.0' | Should -Be 0 Compare-Version '7.0.4-9' '7.0.4-9' | Should -Be 0 Compare-Version 'nightly-20190801' 'nightly' | Should -Be 0 Compare-Version 'nightly-20190801' 'nightly-20200801' | Should -Be 0 } It "handles nightly versions with 'update_nightly'" { function get_config { $true } Mock Get-Date { '20200801' } Compare-Version 'nightly-20200801' 'nightly' | Should -Be 0 Compare-Version 'nightly-20200730' 'nightly' | Should -Be 1 Compare-Version 'nightly-20200730' 'nightly-20200801' | Should -Be 1 Compare-Version 'nightly-20200802' 'nightly' | Should -Be -1 Compare-Version 'nightly-20200802' 'nightly-20200801' | Should -Be -1 } } } ================================================ FILE: test/bin/init.ps1 ================================================ #Requires -Version 5.1 Write-Output "PowerShell: $($PSVersionTable.PSVersion)" Write-Output 'Check and install testsuite dependencies ...' if (Get-InstalledModule -Name Pester -MinimumVersion 5.2 -MaximumVersion 5.99 -ErrorAction SilentlyContinue) { Write-Output 'Pester 5 is already installed.' } else { Write-Output 'Installing Pester 5 ...' Install-Module -Repository PSGallery -Scope CurrentUser -Force -Name Pester -MinimumVersion 5.2 -MaximumVersion 5.99 -SkipPublisherCheck } if (Get-InstalledModule -Name PSScriptAnalyzer -MinimumVersion 1.17 -ErrorAction SilentlyContinue) { Write-Output 'PSScriptAnalyzer is already installed.' } else { Write-Output 'Installing PSScriptAnalyzer ...' Install-Module -Repository PSGallery -Scope CurrentUser -Force -Name PSScriptAnalyzer -SkipPublisherCheck } if (Get-InstalledModule -Name BuildHelpers -MinimumVersion 2.0 -ErrorAction SilentlyContinue) { Write-Output 'BuildHelpers is already installed.' } else { Write-Output 'Installing BuildHelpers ...' Install-Module -Repository PSGallery -Scope CurrentUser -Force -Name BuildHelpers -SkipPublisherCheck } ================================================ FILE: test/bin/test.ps1 ================================================ #Requires -Version 5.1 #Requires -Modules @{ ModuleName = 'BuildHelpers'; ModuleVersion = '2.0.1' } #Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.2.0' } #Requires -Modules @{ ModuleName = 'PSScriptAnalyzer'; ModuleVersion = '1.17.1' } param( [String] $TestPath = (Convert-Path "$PSScriptRoot\..") ) $pesterConfig = New-PesterConfiguration -Hashtable @{ Run = @{ Path = $TestPath PassThru = $true } Output = @{ Verbosity = 'Detailed' } } $excludes = @() if ($IsLinux -or $IsMacOS) { Write-Warning 'Skipping Windows-only tests on Linux/macOS' $excludes += 'Windows' } if ($env:CI -eq $true) { Write-Host "Load 'BuildHelpers' environment variables ..." Set-BuildEnvironment -Force # Check if tests are called from the Core itself, if so, adding excludes if ($TestPath -eq (Convert-Path "$PSScriptRoot\..")) { if ($env:BHCommitMessage -match '!linter') { Write-Warning "Skipping code linting per commit flag '!linter'" $excludes += 'Linter' } $changedScripts = (Get-GitChangedFile -Include '*.ps1', '*.psd1', '*.psm1' -Commit $env:BHCommitHash) if (!$changedScripts) { Write-Warning "Skipping tests and code linting for PowerShell scripts because they didn't change" $excludes += 'Linter' $excludes += 'Scoop' } if (!($changedScripts -like '*decompress.ps1') -and !($changedScripts -like '*Decompress.Tests.ps1')) { Write-Warning "Skipping tests and code linting for decompress.ps1 files because it didn't change" $excludes += 'Decompress' } if ('Decompress' -notin $excludes -and 'Windows' -notin $excludes) { Write-Host 'Install decompress dependencies ...' Write-Host (7z.exe | Select-String -Pattern '7-Zip').ToString() $env:SCOOP_HELPERS_PATH = 'C:\projects\helpers' if (!(Test-Path $env:SCOOP_HELPERS_PATH)) { New-Item -ItemType Directory -Path $env:SCOOP_HELPERS_PATH | Out-Null } $env:SCOOP_LESSMSI_PATH = "$env:SCOOP_HELPERS_PATH\lessmsi\lessmsi.exe" if (!(Test-Path $env:SCOOP_LESSMSI_PATH)) { $source = 'https://github.com/activescott/lessmsi/releases/download/v1.10.0/lessmsi-v1.10.0.zip' $destination = "$env:SCOOP_HELPERS_PATH\lessmsi.zip" Invoke-WebRequest -Uri $source -OutFile $destination & 7z.exe x "$env:SCOOP_HELPERS_PATH\lessmsi.zip" -o"$env:SCOOP_HELPERS_PATH\lessmsi" -y | Out-Null } $env:SCOOP_INNOUNP_PATH = "$env:SCOOP_HELPERS_PATH\innounp\innounp.exe" if (!(Test-Path $env:SCOOP_INNOUNP_PATH)) { $source = 'https://raw.githubusercontent.com/ScoopInstaller/Binary/master/innounp/innounp050.rar' $destination = "$env:SCOOP_HELPERS_PATH\innounp.rar" Invoke-WebRequest -Uri $source -OutFile $destination & 7z.exe x "$env:SCOOP_HELPERS_PATH\innounp.rar" -o"$env:SCOOP_HELPERS_PATH\innounp" -y | Out-Null } } } # Display CI environment variables $buildVariables = (Get-ChildItem -Path 'Env:').Where({ $_.Name -match '^(?:BH|CI(?:_|$)|APPVEYOR|GITHUB_|RUNNER_|SCOOP_)' }) $details = $buildVariables | Where-Object -FilterScript { $_.Name -notmatch 'EMAIL' } | Sort-Object -Property 'Name' | Format-Table -AutoSize -Property 'Name', 'Value' | Out-String Write-Host 'CI variables:' Write-Host $details -ForegroundColor DarkGray } if ($excludes.Length -gt 0) { $pesterConfig.Filter.ExcludeTag = $excludes } if ($env:BHBuildSystem -eq 'AppVeyor') { # AppVeyor $resultsXml = "$PSScriptRoot\TestResults.xml" $pesterConfig.TestResult.Enabled = $true $pesterConfig.TestResult.OutputPath = $resultsXml $result = Invoke-Pester -Configuration $pesterConfig Add-TestResultToAppveyor -TestFile $resultsXml } else { # GitHub Actions / Local $result = Invoke-Pester -Configuration $pesterConfig } exit $result.FailedCount ================================================ FILE: test/fixtures/format/formatted/1-easy.json ================================================ { "bin": "single" } ================================================ FILE: test/fixtures/format/formatted/2-whitespaces-mess.json ================================================ { "version": "0.5.18", "url": "https://whatever", "hash": "whatever", "architecture": { "64bit": { "installer": { "script": [ "Do something", "cosi" ] } } } } ================================================ FILE: test/fixtures/format/formatted/3-array-with-single-and-multi.json ================================================ { "homepage": "http://www.7-zip.org/", "description": "A multi-format file archiver with high compression ratios", "license": { "identifier": "LGPL-2.0-only,BSD-3-Clause", "url": "https://www.7-zip.org/license.txt" }, "version": "18.05", "architecture": { "64bit": { "url": "https://7-zip.org/a/7z1805-x64.msi", "hash": "898c1ca0015183fe2ba7d55cacf0a1dea35e873bf3f8090f362a6288c6ef08d7" }, "32bit": { "url": "https://7-zip.org/a/7z1805.msi", "hash": "c554238bee18a03d736525e06d9258c9ecf7f64ead7c6b0d1eb04db2c0de30d0" } }, "extract_dir": "Files/7-Zip", "bin": [ "single", [ "7z.exe", "cosi" ], [ "7z.exe", "cosi", "param", "icon" ], [ "7z.exe", "empty", "", "" ], "singtwo" ], "checkver": "Download 7-Zip ([\\d.]+)", "autoupdate": { "architecture": { "64bit": { "url": "https://7-zip.org/a/7z$cleanVersion-x64.msi" }, "32bit": { "url": "https://7-zip.org/a/7z$cleanVersion.msi" } } }, "shortcuts": [ [ "7zFM.exe", "7-Zip" ], [ "name with spaces.exe", "Shortcut with spaces in name" ] ] } ================================================ FILE: test/fixtures/format/formatted/4-script-block.json ================================================ { "version": "1.0.6", "description": "Rambox Pro. Free, Open Source and Cross Platform messaging and emailing app that combines common web applications into one.", "homepage": "https://rambox.pro/", "url": "https://github.com/ramboxapp/download/releases/download/v1.0.6/RamboxPro-1.0.6-win.exe#/cosi.7z", "hash": "sha512:f4a1b5e12ae15c9a1339fef56b0522b6619d6c23b0ab806f128841c2ba7ce9d9c997fea81f5bc4a24988aed672a4415ff353542535dc7869b5e496f2f1e1efff", "extract_dir": "\\$PLUGINSDIR", "pre_install": "Get-ChildItem \"$dir\" -Exclude 'app-64.7z', 'app-32.7z' | Remove-Item -Force -Recurse", "architecture": { "64bit": { "installer": { "script": "Expand-7zipArchive \"$dir\\app-64.7z\" \"$dir\"" } }, "32bit": { "installer": { "script": "Expand-7zipArchive \"$dir\\app-32.7z\" \"$dir\"" } } }, "post_install": "Remove-Item \"$dir\\app-64.7z\", \"$dir\\app-32.7z\"", "shortcuts": [ [ "RamboxPro.exe", "RamboxPro" ] ], "checkver": { "github": "https://github.com/ramboxapp/download/" }, "autoupdate": { "url": "https://github.com/ramboxapp/download/releases/download/v$version/RamboxPro-$version-win.exe#/cosi.7z", "hash": { "url": "https://github.com/ramboxapp/download/releases/download/v$version/latest.yml", "find": "sha512:\\s+(.*)" } } } ================================================ FILE: test/fixtures/format/unformatted/1-easy.json ================================================ { "bin": ["single"]} ================================================ FILE: test/fixtures/format/unformatted/2-whitespaces-mess.json ================================================ { "version": "0.5.18", "url": "https://whatever", "hash": "whatever", "architecture": { "64bit": { "installer": { "script": [ "Do something" , "cosi" ] } } } } ================================================ FILE: test/fixtures/format/unformatted/3-array-with-single-and-multi.json ================================================ { "homepage": "http://www.7-zip.org/", "description": "A multi-format file archiver with high compression ratios", "license": { "identifier": "LGPL-2.0-only,BSD-3-Clause", "url": "https://www.7-zip.org/license.txt" }, "version": "18.05", "architecture": { "64bit": { "url": "https://7-zip.org/a/7z1805-x64.msi", "hash": [ "898c1ca0015183fe2ba7d55cacf0a1dea35e873bf3f8090f362a6288c6ef08d7" ] }, "32bit": { "url": "https://7-zip.org/a/7z1805.msi", "hash": "c554238bee18a03d736525e06d9258c9ecf7f64ead7c6b0d1eb04db2c0de30d0" } }, "extract_dir": "Files/7-Zip", "bin": [ [ "single" ], [ "7z.exe", "cosi" ], [ "7z.exe", "cosi", "param", "icon" ], [ "7z.exe", "empty", "", "" ], [ "singtwo" ] ], "checkver": "Download 7-Zip ([\\d.]+)", "autoupdate": { "architecture": { "64bit": { "url": "https://7-zip.org/a/7z$cleanVersion-x64.msi" }, "32bit": { "url": "https://7-zip.org/a/7z$cleanVersion.msi" } } }, "shortcuts": [ [ "7zFM.exe", "7-Zip" ], ["name with spaces.exe", "Shortcut with spaces in name"] ]} ================================================ FILE: test/fixtures/format/unformatted/4-script-block.json ================================================ { "version": "1.0.6", "description": "Rambox Pro. Free, Open Source and Cross Platform messaging and emailing app that combines common web applications into one.", "homepage": "https://rambox.pro/", "url": "https://github.com/ramboxapp/download/releases/download/v1.0.6/RamboxPro-1.0.6-win.exe#/cosi.7z", "hash": "sha512:f4a1b5e12ae15c9a1339fef56b0522b6619d6c23b0ab806f128841c2ba7ce9d9c997fea81f5bc4a24988aed672a4415ff353542535dc7869b5e496f2f1e1efff", "extract_dir": "\\$PLUGINSDIR", "pre_install": ["Get-ChildItem \"$dir\" -Exclude 'app-64.7z', 'app-32.7z' | Remove-Item -Force -Recurse"], "architecture": { "64bit": { "installer": { "script": [ "Expand-7zipArchive \"$dir\\app-64.7z\" \"$dir\"" ] } }, "32bit": { "installer": { "script": [ "Expand-7zipArchive \"$dir\\app-32.7z\" \"$dir\"" ] } } }, "post_install": ["Remove-Item \"$dir\\app-64.7z\", \"$dir\\app-32.7z\""], "shortcuts": [ [ "RamboxPro.exe", "RamboxPro" ] ], "checkver": { "github": "https://github.com/ramboxapp/download/" }, "autoupdate": { "url": "https://github.com/ramboxapp/download/releases/download/v$version/RamboxPro-$version-win.exe#/cosi.7z", "hash": { "url": "https://github.com/ramboxapp/download/releases/download/v$version/latest.yml", "find": "sha512:\\s+(.*)" } } } ================================================ FILE: test/fixtures/is_directory/i_am_a_directory/.gitkeep ================================================ need some content to not fail tests ================================================ FILE: test/fixtures/is_directory/i_am_a_file.txt ================================================ dummy content ================================================ FILE: test/fixtures/manifest/broken_schema.json ================================================ { "$id": "http://scoop.sh/draft/schema#", "$schema": "http://scoop.sh/draft/schema#", "title": "scoop app manifest schema", "type": "object" "properties": { "version": { "type": "string" } } } ================================================ FILE: test/fixtures/manifest/broken_wget.json ================================================ { "homepage": "https://eternallybored.org/misc/wget/", "license": "GPL3", "version": "1.16.3" "architecture": { "64bit": { "url": [ "https://eternallybored.org/misc/wget/wget-1.16.3-win64.zip", "http://curl.haxx.se/ca/cacert.pem" ], "hash": [ "85e5393ffd473f7bec40b57637fd09b6808df86c06f846b6885b261a8acac8c5", "" ] }, "32bit": { "url": [ "https://eternallybored.org/misc/wget/wget-1.16.3-win32.zip", "http://curl.haxx.se/ca/cacert.pem" ], "hash": [ "2ef82af3070abfdaf3862baff0bffdcb3c91c8d75e2f02c8720d90adb9d7a8f7", "" ] } }, "bin": "wget.exe", "post_install": "\"ca_certificate=$dir\\cacert.pem\" | out-file $dir\\wget.ini -encoding default" } ================================================ FILE: test/fixtures/manifest/invalid_wget.json ================================================ { "homepage": "https://eternallybored.org/misc/wget/", "randomproperty": "should fail", "license": "GPL3", "architecture": { "64bit": { "url": [ "https://eternallybored.org/misc/wget/wget-$version-win64.zip", "http://curl.haxx.se/ca/cacert.pem" ], "hash": [ "85e5393ffd473f7bec40b57637fd09b6808df86c06f846b6885b261a8acac8c5", "" ] }, "32bit": { "url": [ "https://eternallybored.org/misc/wget/wget-$version-win32.zip", "http://curl.haxx.se/ca/cacert.pem" ], "hash": [ "2ef82af3070abfdaf3862baff0bffdcb3c91c8d75e2f02c8720d90adb9d7a8f7", "" ] } }, "bin": "wget.exe", "post_install": "\"ca_certificate=$dir\\cacert.pem\" | out-file $dir\\wget.ini -encoding default" } ================================================ FILE: test/fixtures/manifest/wget.json ================================================ { "homepage": "https://eternallybored.org/misc/wget/", "license": "GPL3", "version": "1.16.3", "architecture": { "64bit": { "url": [ "https://eternallybored.org/misc/wget/wget-1.16.3-win64.zip", "http://curl.haxx.se/ca/cacert.pem" ], "hash": [ "85e5393ffd473f7bec40b57637fd09b6808df86c06f846b6885b261a8acac8c5", "" ] }, "32bit": { "url": [ "https://eternallybored.org/misc/wget/wget-1.16.3-win32.zip", "http://curl.haxx.se/ca/cacert.pem" ], "hash": [ "2ef82af3070abfdaf3862baff0bffdcb3c91c8d75e2f02c8720d90adb9d7a8f7", "" ] } }, "bin": "wget.exe", "post_install": "\"ca_certificate=$dir\\cacert.pem\" | out-file $dir\\wget.ini -encoding default" } ================================================ FILE: test/fixtures/movedir/user/_tmp/subdir/test.txt ================================================ this is the one ================================================ FILE: test/fixtures/movedir/user/_tmp/test.txt ================================================ testing ================================================ FILE: test/fixtures/movedir/user with 'quote/_tmp/subdir/test.txt ================================================ this is the one ================================================ FILE: test/fixtures/movedir/user with 'quote/_tmp/test.txt ================================================ testing ================================================ FILE: test/fixtures/movedir/user with space/_tmp/subdir/test.txt ================================================ this is the one ================================================ FILE: test/fixtures/movedir/user with space/_tmp/test.txt ================================================ testing ================================================ FILE: test/fixtures/shim/shim-test.ps1 ================================================ 'Hello, world!' ================================================ FILE: test/fixtures/shim/user with 'quote/shim-test.ps1 ================================================ 'Hello, world!'