mirror of
https://github.com/QwenLM/qwen-code.git
synced 2026-07-09 17:19:02 +00:00
feat(installer): add standalone hosted install and uninstall flow (#3828)
* feat(installer): add standalone archive installation * fix(installer): harden standalone archive installs * fix(installer): address standalone review findings * chore(installer): clarify review followups * fix(installer): stabilize standalone script checks * chore(installer): remove internal planning docs * chore(installer): simplify standalone release review fixes * test(installer): add Windows batch install smoke * test(installer): fix Windows batch smoke quoting * test(installer): preserve Windows cmd quotes * fix(installer): use robust Windows checksum hashing * ci: narrow installer debug matrix * fix(installer): address standalone review hardening * fix(installer): avoid Windows validation parse errors * fix(installer): simplify Windows option validation * fix(installer): harden standalone review fixes * feat(installer): publish release installer assets * fix(installer): address release asset review feedback * fix(installer): avoid prerelease installer asset links * test(installer): isolate standalone dist fixture * feat(installer): add hosted install release alias * chore: no changes - code review requested Agent-Logs-Url: https://github.com/QwenLM/qwen-code/sessions/38467aec-15b9-4b76-9139-0b2cfe40477a * fix(installer): pin versioned installer assets * fix: parallelize Node.js binary downloads in standalone release build Use Promise.all instead of sequential for...of+await for the 5 independent Node.js runtime downloads, reducing CI release build time by ~4-5x. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> * fix(installer): address release asset review followups * refactor(installer): share release CLI parsing * fix(installer): address release asset review followups - sh: reject CR/LF in archive entry names before the literal `..` glob so a `..\r` entry cannot bypass path validation. - bat: prefer Tls12+Tls13 in PowerShell helpers, fall back to Tls12 alone on older .NET Framework where the Tls13 enum is missing. - bat: document the implicit `:ValidateOptions` dependency next to the qwen.cmd wrapper writer so loosening the validator stays a conscious choice. - build-standalone-release: surface the `xz-utils` host requirement for Linux Node downloads in `--help`. - release-script-utils: support `--key=value` form in `parseCliArgs`. - tests: cover the new CRLF message, TLS string, and `--key=value` parsing; register process-level signal/exit handlers in `ensureMinimalDist` so a crashed test still restores `dist/`. * fix(installer): unblock Windows CI for standalone install path Three CI failures and a few review followups in one pass. - ensureMinimalDist places its dist/ backup beside dist/ instead of under os.tmpdir(). On Windows GitHub runners the workspace lives on D: while os.tmpdir() is on C:, so renameSync raised EXDEV for every test that needed to swap dist/ in. - create-standalone-package.js and the matching test fixture build win-x64 zips with [IO.Compression.ZipFile]::CreateFromDirectory. Compress-Archive emits backslash entry names that the .bat installer's path-traversal guard then rejected, so every freshly built archive failed the standalone install path on Windows. - :ValidateArchiveContents normalizes entry separators to '/' before checking for '..', absolute paths, and drive prefixes - archives from any Windows zip tool still install while real traversal entries remain rejected. - createWindowsTraversalStandaloneArchive runs PowerShell via -File instead of a single -Command line; the joined-with-'; ' form had a function definition the runner's PowerShell refused to parse. Drive-by review followups: - replaceRequired uses replaceAll so a future duplicate placeholder cannot silently keep the trailing copy as 'latest'. - :ValidateOptions runs the unsafe-character check on SOURCE alongside the other variables. - build-installation-assets.js drops a dead INSTALLATION_ASSETS re-export; consumers already import from release-asset-config.js. - .gitignore covers the new sibling .qwen-dist-backup-* directory. * fix(installer): address release asset review findings * fix(installer): keep installer entrypoint hosted * fix(installer): reject stale hosted assets * fix(installer): refine hosted asset staging * fix(installer): tighten hosted default-version check, flag legacy URL - Replace the loose `latest` fragment check with per-format regex patterns in HOSTED_INSTALLER_DEFAULT_VERSION_PATTERNS so an unrelated occurrence of `latest` (comment, help text) cannot satisfy the staging guard. The patterns still tolerate whitespace variation, only the default-version assignment itself must be intact. - Add a "Hosted endpoint status" callout in INSTALLATION_GUIDE.md before the curl examples. The documented `--version` flow does not work against the OSS URL today because it currently serves the legacy NVM-based installer; the callout points users at a local checkout until the next release sync. - Tests: drop `latest` from the fragments equality assertion, add positive and negative regex coverage, add a failure-path case for sources whose default version is not `latest`, and pin the new guide markers so the callout cannot silently disappear. * feat(installer): verify installation release assets Adds `npm run verify:installation-release` and wires it into the release workflow after `Build Standalone Archives`, so a broken release directory fails CI before publishing. Local mode (`--dir PATH`) checks: - All five `qwen-code-{platform}.{ext}` standalone archives exist. - `SHA256SUMS` covers exactly those five — missing or unexpected entries fail. - Each archive's actual SHA256 matches its `SHA256SUMS` entry. Remote mode (`--base-url URL`) checks: - `SHA256SUMS` is downloadable, parseable, and contains exactly the expected archive entries. - Each archive URL is reachable via HEAD, with a 1-byte ranged GET fallback for hosts that disable HEAD. Hosted installer scripts (`install-qwen.sh` / `install-qwen.bat`) are intentionally out of scope here — they are served from the hosted endpoint prepared by `package:hosted-installation` (PR #3853), not from the GitHub Release surface this verifier targets. * fix(installer): tighten verifier base-url + clarify test helper Three small refinements from the second review pass: - normalizeHttpsBaseUrl rejects everything except https, since real release URLs are always HTTPS. Accepting http previously would let an operator silently target a stale or attacker-controlled mirror. - Drop EXPECTED_RELEASE_ASSET_NAMES from the public exports; it was only used internally for the verification log line. - Rename the test helper standaloneChecksumContent to placeholderChecksumContent and document that the hashes in its output are placeholders — the remote verifier does not download archives or compare hashes, it only validates that SHA256SUMS lists the expected names and that each archive URL is reachable. The non-https rejection test now also covers `http://` in addition to the existing `file://` case. * fix(installer): address standalone review follow-ups * fix(installer): repair Windows installer tests * fix(release): tighten standalone asset checks * fix(installer): stabilize Windows managed install checks * test(installer): relax Windows installer timeout * fix(test): escape release asset regex * test(cli): avoid POSIX node path in relaunch test * fix(installer): align npm fallback node gate with engines * test(installer): allow Windows archive validation more time * fix(installer): remove stale node 20 installer references * docs(installer): clarify hosted endpoint sync requirement * refactor(installer): reuse standaloneArchiveName in release verifier The verify-installation-release script was duplicating the archive name derivation logic with a hardcoded ternary instead of reusing the standaloneArchiveName helper from build-standalone-release. Export the helper and import it so the extension mapping lives in one place. * fix(scripts): address release verifier review feedback * feat(installer): add standalone archive installer with multi-platform release workflow - Add standalone archive installer (bat/sh) that downloads platform binaries from GitHub/Aliyun without requiring Node.js or npm on the target machine - Add fork-friendly release-test workflow for manual GitHub Release creation covering all 5 platforms (darwin-arm64/x64, linux-arm64/x64, win-x64) - Add OSS upload/mirror tools for staging and release distribution - Update .gitignore to exclude generated build artifacts (release-staging/, hosted-staging/) - Fix Windows PowerShell test command in copy-release-to-latest tool * feat(installer): support QWEN_INSTALL_GITHUB_REPO env var for custom repo * chore(installer): exclude local-only staging tools from PR The tools/ directory contained personal staging-OSS upload helpers (upload-staging, upload-release-mirror, copy-release-to-latest, test-upload-one) that should not ship in the public PR. They reference a personal staging bucket and only exist to validate the installer end-to-end before production release. Removes them from git tracking via `git rm --cached` (files stay on disk for the author's local use) and adds /tools/ to root .gitignore so they cannot be re-added accidentally. No runtime / installer code change. Production CI on ubuntu-latest is unaffected. * fix(installer): enforce CRLF line endings for .bat files via gitattributes cmd.exe requires CRLF in batch scripts; the global eol=lf was causing every line to be misparsed on Windows, producing errors like 'QWEN_VALIDATE_METHOD=detect is not recognized as a command'. * fix(installer): store .bat files with CRLF in git blob for raw GitHub downloads GitHub raw file serving bypasses gitattributes eol conversion and serves blob bytes directly, so eol=crlf alone was not enough. Use -text to disable normalization and commit with actual CRLF so raw downloads work on Windows. * fix(installer): follow HTTP redirects in UrlExists and RaceMirrorHead probes GitHub release asset URLs return HTTP 302 to objects.githubusercontent.com. [Net.WebRequest] with HEAD does not auto-redirect by default, so the existence check and mirror-race probe both incorrectly reported the file as missing. Set AllowAutoRedirect=true on HttpWebRequest instances. * fix(installer): surface download errors and add MaximumRedirection 10 * feat(installer): add hosted install-qwen.ps1 shim for irm|iex one-liner The previous Windows quick-install one-liner used `Invoke-WebRequest -OutFile (Join-Path $env:TEMP 'install-qwen.bat'); & (Join-Path …)`. When pasted into a narrow terminal, line wrap could land on `-OutFile`, orphaning the parameter from its value and producing the "missing argument for OutFile" failure followed by a "file not found" when the second `&` ran. PowerShell's line continuation rules cannot resolve this for parameter-name-at-EOL. Add `install-qwen.ps1` as a thin hosted entrypoint that downloads `install-qwen.bat` into TEMP, runs it, and cleans up. Documented one-liner becomes the standard pattern used by bun, uv, scoop, deno, pnpm: powershell -ExecutionPolicy Bypass -c "irm <url>/install-qwen.ps1 | iex" The `.bat` remains the source of truth for installer behavior; `.ps1` is just the modern hosted entrypoint. Version pinning via `$env:QWEN_INSTALL_VERSION` flows through unchanged. Stored with `*.ps1 -text` so CRLF survives both GitHub raw and OSS uploads, matching the existing `.bat` handling. * fix(installer): stage direct hosted install scripts * chore(installer): trim hosted release diff scope * chore(installer): narrow hosted release diff * feat(installer): restore hosted PowerShell entrypoint * chore(installer): stage standalone hosted entrypoints * fix(installer): address hosted installer review followups * fix(installer): stabilize Windows installer tests * fix(installer): make Windows option validation readable * feat(installer): wire Aliyun OSS sync, address review followups - Add Aliyun OSS sync steps to release workflow: package hosted assets, install pinned ossutil, configure credentials, upload versioned and latest paths, and verify upload via verify:installation-release plus curl probes against the hosted installer endpoint. - Document required production-release environment secrets and bucket variables in INSTALLATION_GUIDE.md. - Restructure hosted endpoint guidance to lead with the pre-sync warning, splitting "Run today" (local checkout) from "After the OSS sync" (hosted one-liners) so users no longer copy a one-liner that silently installs latest. - Distinguish mirror auto-selection timeout from successful selection in install-qwen-standalone.sh and install-qwen-standalone.bat: emit a "timed out; defaulting to github" log instead of pretending the HEAD probe picked github. - Support QWEN_INSTALLER_BAT_URL override (https only) in the PowerShell shim so staging mirrors can be exercised without forking the file. - Strip a leading UTF-8 BOM in verify-installation-release.js parseSha256Sums so BOM-prefixed SHA256SUMS reports a useful "Missing checksum entry" error instead of "Malformed SHA256SUMS line 1". - Add tests for verifier HEAD→Range fallback, partial-failure formatting, all-failure wording, and BOM tolerance. * ci(installer): add temporary OSS smoke test * fix(installer): make OSS release assets public-readable * chore(installer): remove temporary OSS smoke workflow * fix(installer): address hosted installer review gaps * feat(installer): refactor argument parsing and utility functions for release scripts * fix(installer): harden hosted release script checks * fix(installer): suppress PowerShell progress bar in hosted entrypoint shim Add $ProgressPreference = 'SilentlyContinue' to the .ps1 wrapper so Invoke-WebRequest downloads don't render a progress bar when invoked via the irm | iex one-liner. * fix(installer): suppress PowerShell progress bar in bat installer downloads Add $ProgressPreference = 'SilentlyContinue' to DownloadFile so the full-screen progress UI does not appear during archive downloads in interactive PowerShell sessions, consistent with the .ps1 shim. * fix(installer): use curl.exe -# progress bar in Windows downloads Prefer curl.exe with -# (hash-mark progress bar) for archive and installer downloads on Windows 10+. Falls back to Invoke-WebRequest (which shows its own progress bar) when curl.exe is unavailable. Matches the approach used by code-server (curl -#fL) and bun.sh (curl.exe -#SfLo). * fix(installer): suppress progress bars for small downloads and Expand-Archive - .ps1: replace curl.exe -# with silent mode, suppress Invoke-WebRequest progress bar; save/restore $global:ProgressPreference - .bat: add $ProgressPreference = 'SilentlyContinue' before Expand-Archive to prevent full-screen extraction progress UI - .sh: remove --progress-bar / --show-progress from download_file, always use silent curl/wget * fix(installer): auto-backup non-qwen directories and simplify output - ensure_managed_install_dir / :EnsureManagedInstallDir now back up non-qwen directories instead of refusing to install, so users upgrading from npm or old installers don't hit a hard error - Simplify header/footer output: remove banner bars, verbose INFO lines, and redundant "Installation completed!" message - Match bun.sh / code-server style: minimal, to the point * fix(installer): revert Expand-Archive progress suppression in bat The inline $ProgressPreference = 'SilentlyContinue' caused a cmd.exe parsing error ("此时不应有 >") on Chinese Windows. Revert to the original Expand-Archive invocation. * fix(installer): fix cmd.exe parsing error in backup fallback code The %s in the for /f fallback command string was interpreted as a variable reference by cmd.exe, causing "此时不应有 >" on Chinese Windows. Replace with a safe fallback and re-enable Expand-Archive progress suppression. * fix(installer): always persist install bin to user PATH Previously MaybeUpdateUserPath was only called when shadow qwen executables were detected. When no shadow was found, the PATH update was skipped entirely, leaving the user without qwen on PATH after restarting their terminal. Now always persist the bin directory to PATH (unless --no-modify-path is set), regardless of whether other qwen installations exist. * fix(installer): persist PATH to current terminal session on Windows Use the `endlocal & set` trick (same as bun/Rust installers) to export the install bin directory from the setlocal scope to the current cmd session. qwen is now usable immediately without restarting the terminal. * docs(installer): document cmd.exe one-liner for immediate PATH availability Add curl-based one-liner for cmd.exe users. Running the .bat directly in the current cmd session makes `qwen` available immediately via the `endlocal & set` trick. The `powershell -c "irm | iex"` path creates a child process so PATH changes cannot propagate to the parent. * feat(installer): make qwen usable immediately from PowerShell after install - .ps1: detect parent process, update current session PATH, and for cmd.exe parents emit a `set PATH=...` command - .bat: skip final instructions when called from PowerShell to avoid duplicate "Run: qwen" output * fix(installer): remove non-functional doskey approach for cmd parent doskey /exename from a child PowerShell process cannot modify the parent cmd.exe session. Replace with a simple set PATH=... command that the user can copy-paste. * fix(installer): make Windows standalone shim available in cmd * feat(installer): add standalone uninstall scripts * fix(uninstall): match shell-quoted paths when removing the wrapper The installer's write_unix_wrapper shell-quotes the binary path, so paths containing single quotes (or other shell metacharacters) appear as shell-quoted strings in the generated wrapper file. The uninstall script's literal grep -qF missed these, leaving the wrapper orphaned. Add shell_quote to the uninstall script and match against both the raw and shell-quoted forms before removing the wrapper. * fix(installer): update download commands to use progress indicators for curl and wget * fix(installer): resolve Aliyun latest via version pointer * fix(installer): cleanup mirror probe temp dirs * fix(installer): harden standalone release fallback * fix(installer): address standalone review feedback * style(installer): align standalone install output * fix(installer): print standalone uninstall commands * fix(installer): address release review follow-ups * fix(installer): harden Windows target detection * test(installer): stabilize Windows fake tool path * fix(installer): allow explicit Windows curl path * test(installer): use cmd fake curl on Windows * test(installer): cover Windows fake curl helper * test(installer): inject Windows arch overrides in cmd * test(cli): wait for prompt suggestion render * test(cli): revert prompt suggestion wait tweak * fix(installer): harden hosted release publishing * fix(installer): harden Windows latest pointer parsing * fix(installer): bound Windows download timeouts * fix(installer): bound hosted installer probes * fix(release): make ossutil download configurable * fix(installer): address hosted release review feedback * test(installer): keep dist backup on same filesystem * fix(installer): address remaining review feedback on PR #3828 - Remove REQUIRE_CHECKSUM dead code, always hard-fail on checksum issues - Add JSDoc to HOSTED_INSTALLER_BEHAVIOR_PATTERNS explaining its purpose - Add credential cleanup trap for ossutilconfig in release workflow - Add 3-attempt retry with exponential backoff for OSS uploads - Tighten findstr SOURCE regex to require leading letter * fix(release): correct OSS credentials lifetime and mirror probe fallback - release.yml: remove `trap EXIT` inside the Configure step; it deleted ${RUNNER_TEMP}/.ossutilconfig as soon as the configure shell exited, so every subsequent step (publish/sync/verify) lost the credentials. Move credential cleanup to a final `if: always()` step at the job tail. - install-qwen-standalone.sh: drop the predictable PID-based mktemp -d fallback in race_mirror_head; if mktemp fails, return "github" instead of using /tmp/qwen-mirror.$$ which a local attacker could pre-create to bias mirror selection. * fix(installer): address review feedback round 2 Workflow: - Move 'Publish Aliyun OSS Latest VERSION' to run after the hosted installer assets are uploaded and verified, so the latest/VERSION pointer only flips once every release artifact is in place. Previously a hosted-sync failure could leave the pointer ahead of the actual installer scripts. upload-aliyun-oss-assets.js: - Replace `spawnSync('sleep', ...)` retry backoff with an Atomics.wait-based cross-platform sleep so retries also work on Windows runners. install-qwen-standalone.bat: - :DetectTarget no longer emits TARGET=win-arm64 because RELEASE_TARGETS has no win-arm64 archive; ARM64 hosts now fall through to the unsupported-arch branch and (in detect mode) get the npm fallback instead of a 404. - Add QWEN_INSTALL_CURL_EXE to :ValidateRawEnvironmentOptions so this curl override is checked for shell metacharacters like every other knob. - Replace `call echo %%i>>...` with plain `echo %%i>>...` when capturing pre-install qwen.cmd paths; `call` triggered an extra parse pass that could interpret &/|/<,>/etc. inside a directory name as command separators. - Add `--retry 2` to curl.exe downloads (`:DownloadFile` / `:DownloadFileQuiet`) to match the shell installer. - Include expected vs actual hash in the checksum-mismatch error message. install-qwen-standalone.ps1: - Stage the downloaded installer at a cryptographically random temp path (`qwen-installer-<random>.bat`) so a same-user attacker cannot pre-stage a malicious .bat at a predictable path and race the verify/execute window. - Atomically install the current-session cmd shim by writing to a sibling `.new` temp file then renaming, so a partial write cannot leave a half-written shim on PATH. - Add `--retry 2` to the curl.exe download path. - Include expected vs actual hash in the checksum-mismatch error message. install-qwen-standalone.sh: - Include expected vs actual hash in the checksum-mismatch error message. uninstall-qwen-standalone.ps1: - Accept `-Purge` and `-Help` parameters; previously every CLI flag was silently dropped, so users running with `-Purge` got no purge and no error. `-Purge` maps to `QWEN_UNINSTALL_PURGE=1`. uninstall-qwen-standalone.sh: - `remove_install_wrapper` additionally requires the wrapper file to start with a `#!` shebang before it deletes it; a user-authored script that just happens to mention the install path now stays untouched. verify-installation-release.js, build-hosted-installation-assets.js: - Include expected vs actual hash in the checksum-mismatch error messages. scripts/tests/install-script.test.js: - Update assertions for the new error wording, the curl `--retry 2` flag, the dropped ARM64 detection, and the new release-step ordering. * fix(installer): address review feedback round 3 Workflow: - Configure Aliyun OSS Credentials: write the ossutil config file directly with restricted umask instead of invoking `ossutil config -k <secret>`. Passing the access-key secret via argv made it visible in /proc/<pid>/cmdline for the lifetime of that step; writing the INI file in-process keeps the secret out of the process table. upload-aliyun-oss-assets.js: - Upload assets in parallel with `Promise.all` + async `spawn` instead of a sequential `spawnSync` loop. Each asset keeps its own retry budget; failures are aggregated so one flaky upload does not mask a separate failure. - Replace the bespoke `Atomics.wait` retry sleep with `timers/promises#setTimeout` now that the loop is async. INSTALLATION_GUIDE.md: - Drop the misleading "instead of overwriting the global installation/ entrypoint objects" sentence; the workflow has always also refreshed the global versionless objects so curl|bash links keep resolving without a version segment. Document the rollback story instead. * test(installer): add parseUploadArgs unit tests and align verify derivation - scripts/tests/upload-aliyun-oss-assets.test.js: cover --help short-circuit, required-option validation (--bucket/--config/--prefix/empty assets), unknown options, missing option values, and trailing-slash prefix normalization. - scripts/verify-installation-release.js: switch the win-only zip branch from `startsWith('win-')` to the strict `=== 'win-x64'` check used by build-standalone-release.js, and add a comment recording that the two derivations must stay aligned. Without this the helpers would diverge the moment a non-x64 win target gets added. * test(installer): add uploadAssets integration tests with fake ossutil Add two integration tests that route a temp-directory ossutil shim onto PATH so uploadAssets actually spawns the real binary with the real cp argv: - happy-path test asserts the destination URI, `-c <config>`, `--acl public-read`, and per-asset cp invocations land for both inputs. - failure-path test asserts non-zero ossutil exits surface as an aggregate `asset uploads failed` error after the retry budget runs out. * revert(installer): drop over-engineered ossutil/upload changes Roll back two changes from a1ef8697b/0a5d308c9 that were not justified by the actual threat model or release-pipeline needs: - .github/workflows/release.yml: restore the supported `ossutil config -k` invocation. The earlier switch to writing the .ossutilconfig INI file in-process was meant to keep the access-key out of /proc/<pid>/cmdline, but GitHub-hosted runners are single-tenant ephemeral VMs where no other user can read that namespace. The benefit was theoretical; the cost was taking on a brittle dependency on ossutil's undocumented config format. - scripts/upload-aliyun-oss-assets.js: revert the uploadAssets parallel rewrite (Promise.all + spawn + setTimeout) back to the original sync spawnSync loop with retry. Release-time uploads of ~6 small files do not need parallelism, and the async refactor changed the public contract (sync→async) for no real wall-clock win. Kept from those commits: - The cleanup `if: always()` step that removes RUNNER_TEMP/.ossutilconfig at the end of the publish job. - The cross-platform sleepSync(ms) helper, since `spawnSync('sleep', ...)` still does not work on Windows runners. - The INSTALLATION_GUIDE.md doc fix. - All other round-2 fixes. Test assertions updated for the restored sync uploadAssets contract. * test(installer): cover Windows release script regressions * test(release): avoid Windows shim lookup in oss upload tests * test(installer): use stable fake Aliyun version on Windows * fix(installer): parse Aliyun latest version in batch * fix(installer): validate Aliyun latest version without findstr * fix(installer): normalize Aliyun latest version via PowerShell * fix(installer): avoid captured PowerShell output in batch latest parsing * fix(installer): normalize Aliyun latest pointer from file * test(installer): fix fake Windows curl output parsing * fix(installer): print checksum path on miss, gate hardcoded version pin in ps1 [skip ci] Address two narrow follow-ups from PR #3828 review: - build-hosted-installation-assets.js: add a HOSTED_INSTALLER_FORBIDDEN_PATTERNS guard for install-qwen-standalone.ps1. The ps1 shim has no VERSION variable of its own (it forwards @args to the .bat), so the existing default-version positive-match patterns don't apply. The new guard fails the build if a $env:QWEN_INSTALL_VERSION assignment or a --version flag prepended to the forwarded argument list ever lands in the shim. Patterns are line-anchored with /m so the documented usage examples in the header docstring stay valid. Two vitest cases cover the reject and allow paths. - install-qwen-standalone.sh / .bat: include the searched checksum-file path in the "SHA256SUMS not found" error. Operators triaging --archive failures could not tell from the prior message whether the fallback path (next to the archive) or the remote URL was being looked up. Existing test assertions updated to match the new wording. Local validation: npm run test:scripts -> 160 passed | 9 skipped (was 158 | 9). * fix: stamp release version in hosted installers and add Zip Slip protection [skip ci] 1. The hosted installation asset build now accepts --version and stamps it into the copied .sh/.bat installers so they default to the tagged release version instead of 'latest'. The release workflow passes the version. 2. install-qwen-with-source.bat now validates archive entries before calling Expand-Archive, rejecting paths with '..', leading '/', drive-rooted paths, empty names, or control characters — matching the protection already present in install-qwen-standalone.bat and the .sh installer. * fix(installer): add SOURCE to PowerShell unsafe-character validation [skip ci] The SOURCE variable is user-provided and used in path operations but was not included in the :ValidateOptions unsafe-character check. Add it alongside the other validated variables. * fix: correct copyright year 2025 -> 2026 in new files [skip ci] --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Shaojin Wen <shaojin.wensj@alibaba-inc.com> Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com> Co-authored-by: yiliang114 <effortyiliang@gmail.com>
This commit is contained in:
parent
b58fe19c3a
commit
d59c9e7b77
16 changed files with 8012 additions and 141 deletions
3
.gitattributes
vendored
3
.gitattributes
vendored
|
|
@ -9,6 +9,9 @@
|
|||
*.bash eol=lf
|
||||
Makefile eol=lf
|
||||
|
||||
# Windows cmd.exe expects batch installers to be checked out with CRLF.
|
||||
scripts/installation/install-qwen-standalone.bat text eol=crlf
|
||||
|
||||
# Explicitly declare binary file types to prevent Git from attempting to
|
||||
# normalize their line endings.
|
||||
*.png binary
|
||||
|
|
|
|||
199
.github/workflows/release.yml
vendored
199
.github/workflows/release.yml
vendored
|
|
@ -57,7 +57,7 @@ jobs:
|
|||
|
||||
steps:
|
||||
- name: 'Checkout'
|
||||
uses: 'actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd' # v6.0.2
|
||||
uses: 'actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd' # v6.0.2
|
||||
with:
|
||||
ref: '${{ github.event.inputs.ref || github.sha }}'
|
||||
fetch-depth: 0
|
||||
|
|
@ -89,7 +89,7 @@ jobs:
|
|||
echo "is_dry_run=${is_dry_run}" >> "${GITHUB_OUTPUT}"
|
||||
|
||||
- name: 'Setup Node.js'
|
||||
uses: 'actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e' # v6.4.0
|
||||
uses: 'actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e' # v6.4.0
|
||||
with:
|
||||
node-version-file: '.nvmrc'
|
||||
cache: 'npm'
|
||||
|
|
@ -153,13 +153,13 @@ jobs:
|
|||
|
||||
steps:
|
||||
- name: 'Checkout'
|
||||
uses: 'actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd' # v6.0.2
|
||||
uses: 'actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd' # v6.0.2
|
||||
with:
|
||||
ref: '${{ github.event.inputs.ref || github.sha }}'
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 'Setup Node.js'
|
||||
uses: 'actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e' # v6.4.0
|
||||
uses: 'actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e' # v6.4.0
|
||||
with:
|
||||
node-version-file: '.nvmrc'
|
||||
cache: 'npm'
|
||||
|
|
@ -206,13 +206,13 @@ jobs:
|
|||
|
||||
steps:
|
||||
- name: 'Checkout'
|
||||
uses: 'actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd' # v6.0.2
|
||||
uses: 'actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd' # v6.0.2
|
||||
with:
|
||||
ref: '${{ github.event.inputs.ref || github.sha }}'
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 'Setup Node.js'
|
||||
uses: 'actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e' # v6.4.0
|
||||
uses: 'actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e' # v6.4.0
|
||||
with:
|
||||
node-version-file: '.nvmrc'
|
||||
cache: 'npm'
|
||||
|
|
@ -247,13 +247,13 @@ jobs:
|
|||
|
||||
steps:
|
||||
- name: 'Checkout'
|
||||
uses: 'actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd' # v6.0.2
|
||||
uses: 'actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd' # v6.0.2
|
||||
with:
|
||||
ref: '${{ github.event.inputs.ref || github.sha }}'
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 'Setup Node.js'
|
||||
uses: 'actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e' # v6.4.0
|
||||
uses: 'actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e' # v6.4.0
|
||||
with:
|
||||
node-version-file: '.nvmrc'
|
||||
cache: 'npm'
|
||||
|
|
@ -317,13 +317,13 @@ jobs:
|
|||
|
||||
steps:
|
||||
- name: 'Checkout'
|
||||
uses: 'actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd' # v6.0.2
|
||||
uses: 'actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd' # v6.0.2
|
||||
with:
|
||||
ref: '${{ github.event.inputs.ref || github.sha }}'
|
||||
fetch-depth: 0
|
||||
|
||||
- name: 'Setup Node.js'
|
||||
uses: 'actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e' # v6.4.0
|
||||
uses: 'actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e' # v6.4.0
|
||||
with:
|
||||
node-version-file: '.nvmrc'
|
||||
cache: 'npm'
|
||||
|
|
@ -386,6 +386,63 @@ jobs:
|
|||
RELEASE_VERSION: '${{ needs.prepare.outputs.release_version }}'
|
||||
run: 'npm run package:standalone:release -- --version "${RELEASE_VERSION}" --out-dir dist/standalone'
|
||||
|
||||
- name: 'Verify Installation Release Assets'
|
||||
run: 'npm run verify:installation-release -- --dir dist/standalone'
|
||||
|
||||
- name: 'Package Hosted Installation Assets'
|
||||
env:
|
||||
RELEASE_VERSION: '${{ needs.prepare.outputs.release_version }}'
|
||||
run: 'npm run package:hosted-installation -- --out-dir dist/installation --version "${RELEASE_VERSION}"'
|
||||
|
||||
- name: 'Install ossutil'
|
||||
if: |-
|
||||
${{ needs.prepare.outputs.is_dry_run == 'false' }}
|
||||
env:
|
||||
OSSUTIL_URL: "${{ vars.OSSUTIL_URL || 'https://gosspublic.alicdn.com/ossutil/1.7.19/ossutil-v1.7.19-linux-amd64.zip' }}"
|
||||
OSSUTIL_SHA256: "${{ vars.OSSUTIL_SHA256 || 'dcc512e4a893e16bbee63bc769339d8e56b21744fd83c8212a9d8baf28767343' }}"
|
||||
run: |-
|
||||
set -euo pipefail
|
||||
|
||||
tmp_dir="$(mktemp -d)"
|
||||
curl -fsSL --connect-timeout 15 --max-time 300 "${OSSUTIL_URL}" -o "${tmp_dir}/ossutil.zip"
|
||||
echo "${OSSUTIL_SHA256} ${tmp_dir}/ossutil.zip" | sha256sum -c -
|
||||
unzip -q "${tmp_dir}/ossutil.zip" -d "${tmp_dir}"
|
||||
|
||||
ossutil_path="$(find "${tmp_dir}" -type f \( -name 'ossutil' -o -name 'ossutil64' \) -print -quit)"
|
||||
if [[ -z "${ossutil_path}" ]]; then
|
||||
echo "::error::ossutil binary not found in downloaded archive"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
chmod +x "${ossutil_path}"
|
||||
mkdir -p "${HOME}/.local/bin"
|
||||
install -m 0755 "${ossutil_path}" "${HOME}/.local/bin/ossutil"
|
||||
echo "${HOME}/.local/bin" >> "${GITHUB_PATH}"
|
||||
rm -rf "${tmp_dir}"
|
||||
"${HOME}/.local/bin/ossutil" >/dev/null
|
||||
|
||||
- name: 'Configure Aliyun OSS Credentials'
|
||||
if: |-
|
||||
${{ needs.prepare.outputs.is_dry_run == 'false' }}
|
||||
env:
|
||||
ALIYUN_OSS_ACCESS_KEY_ID: '${{ secrets.ALIYUN_OSS_ACCESS_KEY_ID }}'
|
||||
ALIYUN_OSS_ACCESS_KEY_SECRET: '${{ secrets.ALIYUN_OSS_ACCESS_KEY_SECRET }}'
|
||||
ALIYUN_OSS_ENDPOINT: "${{ vars.ALIYUN_OSS_ENDPOINT || 'https://oss-cn-hangzhou.aliyuncs.com' }}"
|
||||
run: |-
|
||||
set -euo pipefail
|
||||
|
||||
if [[ -z "${ALIYUN_OSS_ACCESS_KEY_ID}" || -z "${ALIYUN_OSS_ACCESS_KEY_SECRET}" ]]; then
|
||||
echo "::error::Missing Aliyun OSS credentials. Set ALIYUN_OSS_ACCESS_KEY_ID and ALIYUN_OSS_ACCESS_KEY_SECRET in the production-release environment secrets."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
ossutil config \
|
||||
-e "${ALIYUN_OSS_ENDPOINT}" \
|
||||
-i "${ALIYUN_OSS_ACCESS_KEY_ID}" \
|
||||
-k "${ALIYUN_OSS_ACCESS_KEY_SECRET}" \
|
||||
-L EN \
|
||||
-c "${RUNNER_TEMP}/.ossutilconfig"
|
||||
|
||||
- name: 'Publish @qwen-code/qwen-code'
|
||||
working-directory: 'dist'
|
||||
run: |-
|
||||
|
|
@ -411,21 +468,139 @@ jobs:
|
|||
IS_NIGHTLY: '${{ needs.prepare.outputs.is_nightly }}'
|
||||
IS_PREVIEW: '${{ needs.prepare.outputs.is_preview }}'
|
||||
run: |-
|
||||
set -euo pipefail
|
||||
|
||||
PRERELEASE_FLAG=""
|
||||
if [[ "${IS_NIGHTLY}" == "true" || "${IS_PREVIEW}" == "true" ]]; then
|
||||
PRERELEASE_FLAG="--prerelease"
|
||||
fi
|
||||
|
||||
mapfile -t release_assets < <(node scripts/verify-installation-release.js --dir dist/standalone --list-release-asset-paths)
|
||||
|
||||
gh release create "${RELEASE_TAG}" \
|
||||
dist/cli.js \
|
||||
dist/standalone/qwen-code-* \
|
||||
dist/standalone/SHA256SUMS \
|
||||
"${release_assets[@]}" \
|
||||
--target "${RELEASE_BRANCH}" \
|
||||
--title "Release ${RELEASE_TAG}" \
|
||||
--notes-start-tag "${PREVIOUS_RELEASE_TAG}" \
|
||||
--generate-notes \
|
||||
${PRERELEASE_FLAG}
|
||||
|
||||
- name: 'Sync Release Assets to Aliyun OSS'
|
||||
if: |-
|
||||
${{ needs.prepare.outputs.is_dry_run == 'false' }}
|
||||
env:
|
||||
ALIYUN_OSS_BUCKET: "${{ vars.ALIYUN_OSS_BUCKET || 'qwen-code-assets' }}"
|
||||
RELEASE_TAG: '${{ needs.prepare.outputs.release_tag }}'
|
||||
run: |-
|
||||
set -euo pipefail
|
||||
|
||||
mapfile -t release_assets < <(node scripts/verify-installation-release.js --dir dist/standalone --list-release-asset-paths)
|
||||
node scripts/upload-aliyun-oss-assets.js \
|
||||
--bucket "${ALIYUN_OSS_BUCKET}" \
|
||||
--config "${RUNNER_TEMP}/.ossutilconfig" \
|
||||
--prefix "releases/qwen-code/${RELEASE_TAG}" \
|
||||
"${release_assets[@]}"
|
||||
|
||||
- name: 'Verify Aliyun OSS Release Assets'
|
||||
if: |-
|
||||
${{ needs.prepare.outputs.is_dry_run == 'false' }}
|
||||
env:
|
||||
ALIYUN_OSS_PUBLIC_BASE_URL: "${{ vars.ALIYUN_OSS_PUBLIC_BASE_URL || 'https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com' }}"
|
||||
RELEASE_TAG: '${{ needs.prepare.outputs.release_tag }}'
|
||||
run: |-
|
||||
set -euo pipefail
|
||||
|
||||
npm run verify:installation-release -- --base-url "${ALIYUN_OSS_PUBLIC_BASE_URL}/releases/qwen-code/${RELEASE_TAG}"
|
||||
|
||||
- name: 'Sync Hosted Installation Assets to Aliyun OSS'
|
||||
if: |-
|
||||
${{ needs.prepare.outputs.is_dry_run == 'false' && needs.prepare.outputs.is_nightly == 'false' && needs.prepare.outputs.is_preview == 'false' }}
|
||||
env:
|
||||
ALIYUN_OSS_BUCKET: "${{ vars.ALIYUN_OSS_BUCKET || 'qwen-code-assets' }}"
|
||||
RELEASE_TAG: '${{ needs.prepare.outputs.release_tag }}'
|
||||
run: |-
|
||||
set -euo pipefail
|
||||
|
||||
hosted_assets=(
|
||||
dist/installation/install-qwen-standalone.sh
|
||||
dist/installation/install-qwen-standalone.ps1
|
||||
dist/installation/install-qwen-standalone.bat
|
||||
dist/installation/uninstall-qwen-standalone.sh
|
||||
dist/installation/uninstall-qwen-standalone.ps1
|
||||
dist/installation/SHA256SUMS
|
||||
)
|
||||
node scripts/upload-aliyun-oss-assets.js \
|
||||
--bucket "${ALIYUN_OSS_BUCKET}" \
|
||||
--config "${RUNNER_TEMP}/.ossutilconfig" \
|
||||
--prefix "installation/${RELEASE_TAG}" \
|
||||
"${hosted_assets[@]}"
|
||||
node scripts/upload-aliyun-oss-assets.js \
|
||||
--bucket "${ALIYUN_OSS_BUCKET}" \
|
||||
--config "${RUNNER_TEMP}/.ossutilconfig" \
|
||||
--prefix "installation" \
|
||||
"${hosted_assets[@]}"
|
||||
|
||||
- name: 'Verify Aliyun OSS Hosted Installation Assets'
|
||||
if: |-
|
||||
${{ needs.prepare.outputs.is_dry_run == 'false' && needs.prepare.outputs.is_nightly == 'false' && needs.prepare.outputs.is_preview == 'false' }}
|
||||
env:
|
||||
ALIYUN_OSS_PUBLIC_BASE_URL: "${{ vars.ALIYUN_OSS_PUBLIC_BASE_URL || 'https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com' }}"
|
||||
RELEASE_TAG: '${{ needs.prepare.outputs.release_tag }}'
|
||||
run: |-
|
||||
set -euo pipefail
|
||||
|
||||
hosted_tmp_dir="$(mktemp -d)"
|
||||
trap 'rm -rf "${hosted_tmp_dir}"' EXIT
|
||||
mkdir -p "${hosted_tmp_dir}/versioned" "${hosted_tmp_dir}/global"
|
||||
for asset in install-qwen-standalone.sh install-qwen-standalone.ps1 install-qwen-standalone.bat uninstall-qwen-standalone.sh uninstall-qwen-standalone.ps1 SHA256SUMS; do
|
||||
url="${ALIYUN_OSS_PUBLIC_BASE_URL}/installation/${RELEASE_TAG}/${asset}"
|
||||
global_url="${ALIYUN_OSS_PUBLIC_BASE_URL}/installation/${asset}"
|
||||
curl -fsSL --connect-timeout 15 --max-time 300 "${url}" -o "${hosted_tmp_dir}/versioned/${asset}"
|
||||
curl -fsSL --connect-timeout 15 --max-time 300 "${global_url}" -o "${hosted_tmp_dir}/global/${asset}"
|
||||
done
|
||||
cmp -s "dist/installation/SHA256SUMS" "${hosted_tmp_dir}/versioned/SHA256SUMS" || {
|
||||
echo "::error::Hosted installation SHA256SUMS does not match local dist/installation/SHA256SUMS"
|
||||
diff -u "dist/installation/SHA256SUMS" "${hosted_tmp_dir}/versioned/SHA256SUMS" || true
|
||||
exit 1
|
||||
}
|
||||
cmp -s "dist/installation/SHA256SUMS" "${hosted_tmp_dir}/global/SHA256SUMS" || {
|
||||
echo "::error::Global hosted installation SHA256SUMS does not match local dist/installation/SHA256SUMS"
|
||||
diff -u "dist/installation/SHA256SUMS" "${hosted_tmp_dir}/global/SHA256SUMS" || true
|
||||
exit 1
|
||||
}
|
||||
(cd "${hosted_tmp_dir}/versioned" && sha256sum -c SHA256SUMS)
|
||||
(cd "${hosted_tmp_dir}/global" && sha256sum -c SHA256SUMS)
|
||||
|
||||
- name: 'Publish Aliyun OSS Latest VERSION'
|
||||
# Run last so the `latest/VERSION` pointer only flips after every
|
||||
# release asset and hosted installer object has been uploaded and
|
||||
# verified. If any earlier step fails, the pointer keeps referring
|
||||
# to the previously-good release.
|
||||
if: |-
|
||||
${{ needs.prepare.outputs.is_dry_run == 'false' && needs.prepare.outputs.is_nightly == 'false' && needs.prepare.outputs.is_preview == 'false' }}
|
||||
env:
|
||||
ALIYUN_OSS_BUCKET: "${{ vars.ALIYUN_OSS_BUCKET || 'qwen-code-assets' }}"
|
||||
ALIYUN_OSS_PUBLIC_BASE_URL: "${{ vars.ALIYUN_OSS_PUBLIC_BASE_URL || 'https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com' }}"
|
||||
RELEASE_TAG: '${{ needs.prepare.outputs.release_tag }}'
|
||||
run: |-
|
||||
set -euo pipefail
|
||||
|
||||
printf '%s\n' "${RELEASE_TAG}" > "${RUNNER_TEMP}/qwen-code-latest-version"
|
||||
ossutil cp "${RUNNER_TEMP}/qwen-code-latest-version" "oss://${ALIYUN_OSS_BUCKET}/releases/qwen-code/latest/VERSION" -c "${RUNNER_TEMP}/.ossutilconfig" -f --acl public-read
|
||||
|
||||
latest_version="$(curl -fsSL --connect-timeout 15 --max-time 300 "${ALIYUN_OSS_PUBLIC_BASE_URL}/releases/qwen-code/latest/VERSION" | tr -d '[:space:]')"
|
||||
if [[ "${latest_version}" != "${RELEASE_TAG}" ]]; then
|
||||
echo "::error::Aliyun latest VERSION points to ${latest_version}, expected ${RELEASE_TAG}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: 'Cleanup Aliyun OSS Credentials'
|
||||
if: |-
|
||||
${{ always() && needs.prepare.outputs.is_dry_run == 'false' }}
|
||||
run: |-
|
||||
rm -f "${RUNNER_TEMP}/.ossutilconfig"
|
||||
|
||||
- name: 'Create PR to merge release branch into main'
|
||||
if: |-
|
||||
${{ needs.prepare.outputs.is_dry_run == 'false' && needs.prepare.outputs.is_nightly == 'false' && needs.prepare.outputs.is_preview == 'false' }}
|
||||
|
|
|
|||
|
|
@ -65,8 +65,10 @@
|
|||
"preflight": "npm run clean && npm ci && npm run format && npm run lint:ci && npm run build && npm run typecheck && npm run test:ci",
|
||||
"prepare": "husky && npm run build && npm run bundle",
|
||||
"prepare:package": "node scripts/prepare-package.js",
|
||||
"package:hosted-installation": "node scripts/build-hosted-installation-assets.js",
|
||||
"package:standalone": "node scripts/create-standalone-package.js",
|
||||
"package:standalone:release": "node scripts/build-standalone-release.js",
|
||||
"verify:installation-release": "node scripts/verify-installation-release.js",
|
||||
"release:version": "node scripts/version.js",
|
||||
"telemetry": "node scripts/telemetry.js",
|
||||
"check:lockfile": "node scripts/check-lockfile.js",
|
||||
|
|
|
|||
350
scripts/build-hosted-installation-assets.js
Normal file
350
scripts/build-hosted-installation-assets.js
Normal file
|
|
@ -0,0 +1,350 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Qwen Team
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
fail,
|
||||
isMainModule,
|
||||
parseArgs,
|
||||
parseSha256Sums,
|
||||
sha256File,
|
||||
} from './release-script-utils.js';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const rootDir = path.resolve(__dirname, '..');
|
||||
|
||||
const HOSTED_INSTALLATION_ASSETS = [
|
||||
{
|
||||
sourcePath: ['scripts', 'installation', 'install-qwen-standalone.sh'],
|
||||
output: 'install-qwen-standalone.sh',
|
||||
mode: 0o755,
|
||||
},
|
||||
{
|
||||
sourcePath: ['scripts', 'installation', 'install-qwen-standalone.bat'],
|
||||
output: 'install-qwen-standalone.bat',
|
||||
lineEndings: 'crlf',
|
||||
},
|
||||
{
|
||||
sourcePath: ['scripts', 'installation', 'install-qwen-standalone.ps1'],
|
||||
output: 'install-qwen-standalone.ps1',
|
||||
},
|
||||
{
|
||||
sourcePath: ['scripts', 'installation', 'uninstall-qwen-standalone.sh'],
|
||||
output: 'uninstall-qwen-standalone.sh',
|
||||
mode: 0o755,
|
||||
},
|
||||
{
|
||||
sourcePath: ['scripts', 'installation', 'uninstall-qwen-standalone.ps1'],
|
||||
output: 'uninstall-qwen-standalone.ps1',
|
||||
},
|
||||
];
|
||||
const HOSTED_INSTALLATION_ASSET_NAMES = HOSTED_INSTALLATION_ASSETS.map(
|
||||
({ output }) => output,
|
||||
);
|
||||
/** Regex guards that verify each installer script contains required behaviors.
|
||||
* Build fails if a pattern is missing, preventing broken entrypoints from shipping. */
|
||||
const HOSTED_INSTALLER_BEHAVIOR_PATTERNS = {
|
||||
'install-qwen-standalone.sh': [
|
||||
{
|
||||
name: 'QWEN_INSTALL_VERSION',
|
||||
pattern: /QWEN_INSTALL_VERSION/,
|
||||
},
|
||||
{
|
||||
name: '--version parser',
|
||||
pattern: /--version\)|--version=\*\)/,
|
||||
},
|
||||
],
|
||||
'install-qwen-standalone.bat': [
|
||||
{
|
||||
name: 'QWEN_INSTALL_VERSION',
|
||||
pattern: /QWEN_INSTALL_VERSION/,
|
||||
},
|
||||
{
|
||||
name: '--version parser',
|
||||
pattern: /ARG_KEY!"=="--version"|"%~1"=="--version"/,
|
||||
},
|
||||
],
|
||||
'install-qwen-standalone.ps1': [
|
||||
{
|
||||
name: 'argument forwarding',
|
||||
pattern: /& \$qwenInstallerPath @args/,
|
||||
},
|
||||
{
|
||||
name: 'SHA256SUMS verification',
|
||||
pattern: /SHA256SUMS/,
|
||||
},
|
||||
{
|
||||
name: 'bat checksum verification',
|
||||
pattern: /Get-FileHash/,
|
||||
},
|
||||
{
|
||||
name: 'QWEN_INSTALL_VERSION documentation',
|
||||
pattern: /QWEN_INSTALL_VERSION/,
|
||||
},
|
||||
],
|
||||
'uninstall-qwen-standalone.sh': [
|
||||
{
|
||||
name: 'standalone directory guard',
|
||||
pattern: /is_qwen_standalone_install_dir/,
|
||||
},
|
||||
{
|
||||
name: 'PATH cleanup',
|
||||
pattern: /remove_shell_path_entry/,
|
||||
},
|
||||
{
|
||||
name: 'config preservation',
|
||||
pattern: /QWEN_UNINSTALL_PURGE/,
|
||||
},
|
||||
],
|
||||
'uninstall-qwen-standalone.ps1': [
|
||||
{
|
||||
name: 'standalone directory guard',
|
||||
pattern: /Test-QwenStandaloneInstallDir/,
|
||||
},
|
||||
{
|
||||
name: 'PATH cleanup',
|
||||
pattern: /Remove-UserPathEntry/,
|
||||
},
|
||||
{
|
||||
name: 'current cmd shim cleanup',
|
||||
pattern: /Remove-CurrentCmdPathShim/,
|
||||
},
|
||||
{
|
||||
name: 'config preservation',
|
||||
pattern: /QWEN_UNINSTALL_PURGE/,
|
||||
},
|
||||
],
|
||||
};
|
||||
// Narrow regexes that pin the default-version assignment to `latest`.
|
||||
// Substring matching alone would let the word "latest" leak in via comments
|
||||
// or help text even when the actual default has been changed. The patterns
|
||||
// allow whitespace flexibility but require the literal default value.
|
||||
const HOSTED_INSTALLER_DEFAULT_VERSION_PATTERNS = {
|
||||
'install-qwen-standalone.sh':
|
||||
/VERSION\s*=\s*"\$\{QWEN_INSTALL_VERSION:-latest\}"/,
|
||||
'install-qwen-standalone.bat': /set\s+"VERSION=latest"/,
|
||||
};
|
||||
// install-qwen-standalone.ps1 is a shim that downloads the .bat and forwards
|
||||
// `@args` unchanged, so it has no VERSION variable to default-pin. Guard the
|
||||
// shim instead with forbidden-content patterns: any attempt to hardcode a
|
||||
// specific version (either by assigning $env:QWEN_INSTALL_VERSION or by
|
||||
// prepending --version to the forwarded argument list) fails the build.
|
||||
// Patterns are matched per non-comment line (PowerShell line comments start
|
||||
// with `#`) so the usage examples in the header docstring keep working.
|
||||
const HOSTED_INSTALLER_FORBIDDEN_PATTERNS = {
|
||||
'install-qwen-standalone.ps1': [
|
||||
{
|
||||
name: 'no hardcoded QWEN_INSTALL_VERSION assignment',
|
||||
pattern: /^\s*\$env:QWEN_INSTALL_VERSION\s*=/m,
|
||||
},
|
||||
{
|
||||
name: 'no hardcoded --version prepended to forwarded args',
|
||||
pattern:
|
||||
/^\s*&\s+\$qwenInstallerPath\s+(?:'--version'|"--version"|--version)/m,
|
||||
},
|
||||
],
|
||||
};
|
||||
// SHA256SUMS is allowed in an existing output directory because every staging
|
||||
// run rewrites it from scratch after copying the hosted installer assets.
|
||||
const HOSTED_INSTALLATION_OUTPUT_NAMES = new Set([
|
||||
...HOSTED_INSTALLATION_ASSET_NAMES,
|
||||
'SHA256SUMS',
|
||||
]);
|
||||
|
||||
const ARG_DEFS = {
|
||||
'--out-dir': { key: 'outDir', type: 'value' },
|
||||
'--version': { key: 'version', type: 'value' },
|
||||
};
|
||||
|
||||
if (isMainModule(import.meta.url)) {
|
||||
try {
|
||||
await main();
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : error);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv.slice(2), ARG_DEFS);
|
||||
if (args.help) {
|
||||
printUsage();
|
||||
return;
|
||||
}
|
||||
|
||||
const outDir = path.resolve(
|
||||
args.outDir || path.join(rootDir, 'dist', 'installation'),
|
||||
);
|
||||
await buildHostedInstallationAssets(outDir, { version: args.version });
|
||||
}
|
||||
|
||||
function printUsage() {
|
||||
console.log(`Usage: npm run package:hosted-installation -- [options]
|
||||
|
||||
Stages hosted installer entrypoint assets for CDN/OSS upload.
|
||||
|
||||
Options:
|
||||
--out-dir PATH Output directory. Defaults to dist/installation.
|
||||
--version VERSION Stamp the release version into copied installers so
|
||||
they default to installing that version instead of
|
||||
'latest'. Should match the release tag (e.g. v1.2.3).
|
||||
-h, --help Show this help message.
|
||||
`);
|
||||
}
|
||||
|
||||
async function buildHostedInstallationAssets(outDir, options = {}) {
|
||||
const root = options.root || rootDir;
|
||||
const version = options.version || undefined;
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
assertNoUnexpectedHostedFiles(outDir);
|
||||
|
||||
for (const asset of HOSTED_INSTALLATION_ASSETS) {
|
||||
const source = path.join(root, ...asset.sourcePath);
|
||||
if (!fs.existsSync(source)) {
|
||||
fail(`Hosted installer source asset not found: ${source}`);
|
||||
}
|
||||
assertHostedInstallerSource(source, asset.output);
|
||||
|
||||
const destination = path.join(outDir, asset.output);
|
||||
copyHostedInstallationAsset(source, destination, asset);
|
||||
if (version) {
|
||||
stampVersionInAsset(destination, asset.output, version);
|
||||
}
|
||||
if (asset.mode !== undefined) {
|
||||
fs.chmodSync(destination, asset.mode);
|
||||
}
|
||||
}
|
||||
|
||||
await writeHostedSha256Sums(outDir);
|
||||
await assertHostedInstallationAssetChecksums(outDir);
|
||||
}
|
||||
|
||||
function assertNoUnexpectedHostedFiles(outDir) {
|
||||
const unexpected = fs
|
||||
.readdirSync(outDir)
|
||||
.filter((entryName) => !HOSTED_INSTALLATION_OUTPUT_NAMES.has(entryName))
|
||||
.sort();
|
||||
|
||||
if (unexpected.length > 0) {
|
||||
fail(`Unexpected hosted installer asset: ${unexpected.join(', ')}`);
|
||||
}
|
||||
}
|
||||
|
||||
function copyHostedInstallationAsset(source, destination, asset) {
|
||||
if (asset.lineEndings === 'crlf') {
|
||||
const contents = fs.readFileSync(source, 'utf8');
|
||||
fs.writeFileSync(destination, contents.replace(/\r?\n/g, '\r\n'));
|
||||
return;
|
||||
}
|
||||
|
||||
fs.copyFileSync(source, destination);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the default 'latest' version in a copied installer asset with the
|
||||
* given release version so the hosted installer installs the tagged version.
|
||||
*
|
||||
* @param {string} filePath - Path to the copied asset on disk.
|
||||
* @param {string} assetName - Logical asset name (e.g. 'install-qwen-standalone.sh').
|
||||
* @param {string} version - Release version to stamp (e.g. 'v1.2.3' or '1.2.3').
|
||||
*/
|
||||
function stampVersionInAsset(filePath, assetName, version) {
|
||||
const replacements = {
|
||||
'install-qwen-standalone.sh': {
|
||||
from: 'VERSION="${QWEN_INSTALL_VERSION:-latest}"',
|
||||
to: `VERSION="\${QWEN_INSTALL_VERSION:-${version}}"`,
|
||||
},
|
||||
'install-qwen-standalone.bat': {
|
||||
from: 'set "VERSION=latest"',
|
||||
to: `set "VERSION=${version}"`,
|
||||
},
|
||||
};
|
||||
|
||||
const replacement = replacements[assetName];
|
||||
if (!replacement) {
|
||||
return;
|
||||
}
|
||||
|
||||
let contents = fs.readFileSync(filePath, 'utf8');
|
||||
if (!contents.includes(replacement.from)) {
|
||||
fail(
|
||||
`Cannot stamp version in ${assetName}: expected default version pattern not found`,
|
||||
);
|
||||
}
|
||||
contents = contents.replace(replacement.from, replacement.to);
|
||||
fs.writeFileSync(filePath, contents);
|
||||
}
|
||||
|
||||
function assertHostedInstallerSource(source, output) {
|
||||
const contents = fs.readFileSync(source, 'utf8');
|
||||
const missing = (HOSTED_INSTALLER_BEHAVIOR_PATTERNS[output] || [])
|
||||
.filter(({ pattern }) => !pattern.test(contents))
|
||||
.map(({ name }) => name);
|
||||
if (missing.length > 0) {
|
||||
fail(
|
||||
`${output} is missing hosted installer behavior: ${missing.join(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
const defaultPattern = HOSTED_INSTALLER_DEFAULT_VERSION_PATTERNS[output];
|
||||
if (defaultPattern && !defaultPattern.test(contents)) {
|
||||
fail(
|
||||
`${output} default install version must be 'latest' for the hosted entrypoint`,
|
||||
);
|
||||
}
|
||||
|
||||
const forbidden = (HOSTED_INSTALLER_FORBIDDEN_PATTERNS[output] || []).filter(
|
||||
({ pattern }) => pattern.test(contents),
|
||||
);
|
||||
if (forbidden.length > 0) {
|
||||
fail(
|
||||
`${output} must not contain: ${forbidden.map(({ name }) => name).join(', ')}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function writeHostedSha256Sums(outDir) {
|
||||
const lines = [];
|
||||
const assets = [...HOSTED_INSTALLATION_ASSETS].sort((left, right) =>
|
||||
left.output.localeCompare(right.output),
|
||||
);
|
||||
for (const { output } of assets) {
|
||||
const hash = await sha256File(path.join(outDir, output));
|
||||
lines.push(`${hash} ${output}`);
|
||||
}
|
||||
fs.writeFileSync(path.join(outDir, 'SHA256SUMS'), `${lines.join('\n')}\n`);
|
||||
}
|
||||
|
||||
async function assertHostedInstallationAssetChecksums(outDir) {
|
||||
const checksumsPath = path.join(outDir, 'SHA256SUMS');
|
||||
const checksums = parseSha256Sums(fs.readFileSync(checksumsPath, 'utf8'));
|
||||
|
||||
for (const { output } of HOSTED_INSTALLATION_ASSETS) {
|
||||
const expected = checksums.get(output);
|
||||
if (!expected) {
|
||||
fail(`Missing checksum entry for ${output}`);
|
||||
}
|
||||
|
||||
const actual = await sha256File(path.join(outDir, output));
|
||||
if (actual !== expected) {
|
||||
fail(
|
||||
`Checksum mismatch for ${output}: expected ${expected}, got ${actual}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
HOSTED_INSTALLATION_ASSETS,
|
||||
HOSTED_INSTALLATION_ASSET_NAMES,
|
||||
assertHostedInstallationAssetChecksums,
|
||||
buildHostedInstallationAssets,
|
||||
};
|
||||
|
|
@ -10,20 +10,23 @@ The installers are intentionally lightweight:
|
|||
|
||||
- They try a standalone archive first by default.
|
||||
- They do not install Node.js, NVM, or any other Node version manager.
|
||||
- They do not edit npm config or shell profiles.
|
||||
- They do not edit npm config. Standalone installs may update the shell profile
|
||||
or user PATH so the generated `qwen` shim is discoverable.
|
||||
- They do not start `qwen` automatically after installation.
|
||||
- They store source information in `~/.qwen/source.json` or
|
||||
`%USERPROFILE%\.qwen\source.json` when `--source` is provided.
|
||||
|
||||
Standalone archives include a private Node.js runtime, so users do not need a
|
||||
local Node.js installation on the standalone path. Node.js 20 or newer and npm
|
||||
local Node.js installation on the standalone path. Node.js 22 or newer and npm
|
||||
are only required when the installer falls back to npm or when
|
||||
`--method npm` is used.
|
||||
|
||||
## Installation Scripts
|
||||
|
||||
- Linux/macOS: `install-qwen-with-source.sh`
|
||||
- Windows: `install-qwen-with-source.bat`
|
||||
- Linux/macOS: `install-qwen-standalone.sh`
|
||||
- Windows: `install-qwen-standalone.ps1`
|
||||
- Linux/macOS uninstall: `uninstall-qwen-standalone.sh`
|
||||
- Windows uninstall: `uninstall-qwen-standalone.ps1`
|
||||
|
||||
## Release Artifacts
|
||||
|
||||
|
|
@ -36,6 +39,70 @@ GitHub releases publish these standalone archives:
|
|||
- `qwen-code-win-x64.zip`
|
||||
- `SHA256SUMS`
|
||||
|
||||
The new standalone-first installer scripts (`install-qwen-standalone.sh`,
|
||||
`install-qwen-standalone.ps1`) are not republished per release. They are served
|
||||
from a hosted installation endpoint and accept `--version` to pin a specific
|
||||
standalone release. The `standalone` suffix intentionally avoids overwriting the
|
||||
existing production `install-qwen.sh` / `install-qwen.bat` OSS objects during
|
||||
the staged rollout.
|
||||
|
||||
Public installation documentation intentionally continues to use the existing
|
||||
production installer in this PR. Update README and other public quick-install
|
||||
instructions in a follow-up after the standalone-suffixed hosted installers and
|
||||
release archive sync have been validated in production.
|
||||
|
||||
Hosted installer assets are staged separately from GitHub Release archives:
|
||||
|
||||
- `install-qwen-standalone.sh` is the Linux/macOS hosted entrypoint.
|
||||
- `install-qwen-standalone.ps1` is the Windows hosted entrypoint for `irm | iex`.
|
||||
- `install-qwen-standalone.bat` is the Windows installer implementation used by
|
||||
`install-qwen-standalone.ps1` and can also be downloaded and run directly.
|
||||
- `uninstall-qwen-standalone.sh` removes Linux/macOS standalone installs.
|
||||
- `uninstall-qwen-standalone.ps1` removes Windows standalone installs.
|
||||
|
||||
The global standalone-suffixed OSS entrypoints are maintained under
|
||||
`installation/install-qwen-standalone.sh`,
|
||||
`installation/install-qwen-standalone.ps1`,
|
||||
`installation/install-qwen-standalone.bat`,
|
||||
`installation/uninstall-qwen-standalone.sh`, and
|
||||
`installation/uninstall-qwen-standalone.ps1`.
|
||||
|
||||
Build them with:
|
||||
|
||||
```bash
|
||||
npm run package:hosted-installation -- --out-dir dist/installation
|
||||
```
|
||||
|
||||
The staged `install-qwen-standalone.sh`, `install-qwen-standalone.ps1`,
|
||||
`install-qwen-standalone.bat`, `uninstall-qwen-standalone.sh`, and
|
||||
`uninstall-qwen-standalone.ps1` files map to the standalone-suffixed hosted URLs
|
||||
shown above. The staging command also writes `SHA256SUMS` for upload
|
||||
verification. During a non-dry-run stable release, the publish workflow uploads
|
||||
a byte-for-byte snapshot to `installation/vX.Y.Z/` for audit and rollback, and
|
||||
also refreshes the global `installation/` entrypoint objects so `curl | bash`
|
||||
links keep resolving without a version segment. The versioned snapshot lets you
|
||||
roll back by repointing the global objects to a previous tag if a regression is
|
||||
caught after publish. The hosted
|
||||
installers intentionally default to `latest`; on Aliyun OSS this means reading
|
||||
`releases/qwen-code/latest/VERSION` first, then downloading the matching
|
||||
versioned release directory. Use `--version` or `QWEN_INSTALL_VERSION` to pin a
|
||||
standalone release directly.
|
||||
|
||||
Configure the `production-release` GitHub environment with these required
|
||||
secrets before enabling OSS sync:
|
||||
|
||||
- `ALIYUN_OSS_ACCESS_KEY_ID`
|
||||
- `ALIYUN_OSS_ACCESS_KEY_SECRET`
|
||||
|
||||
The workflow defaults to the production OSS bucket and Hangzhou endpoint. Set
|
||||
these GitHub Actions variables only when the bucket, endpoint, or public base
|
||||
URL changes:
|
||||
|
||||
- `ALIYUN_OSS_BUCKET` (default: `qwen-code-assets`)
|
||||
- `ALIYUN_OSS_ENDPOINT` (default: `https://oss-cn-hangzhou.aliyuncs.com`)
|
||||
- `ALIYUN_OSS_PUBLIC_BASE_URL` (default:
|
||||
`https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com`)
|
||||
|
||||
Archive layout:
|
||||
|
||||
```text
|
||||
|
|
@ -62,13 +129,13 @@ The default method is `detect`:
|
|||
You can force a method:
|
||||
|
||||
```bash
|
||||
bash install-qwen-with-source.sh --method standalone
|
||||
bash install-qwen-with-source.sh --method npm
|
||||
bash install-qwen-standalone.sh --method standalone
|
||||
bash install-qwen-standalone.sh --method npm
|
||||
```
|
||||
|
||||
```bat
|
||||
install-qwen-with-source.bat --method standalone
|
||||
install-qwen-with-source.bat --method npm
|
||||
install-qwen-standalone.bat --method standalone
|
||||
install-qwen-standalone.bat --method npm
|
||||
```
|
||||
|
||||
## Optional Native Modules
|
||||
|
|
@ -86,20 +153,20 @@ modules for the current machine.
|
|||
|
||||
```bash
|
||||
# Default: standalone archive with npm fallback
|
||||
bash install-qwen-with-source.sh
|
||||
bash install-qwen-standalone.sh
|
||||
|
||||
# Record a source value
|
||||
bash install-qwen-with-source.sh --source github
|
||||
bash install-qwen-standalone.sh --source github
|
||||
|
||||
# Use npm explicitly
|
||||
bash install-qwen-with-source.sh --method npm --registry https://registry.npmjs.org
|
||||
bash install-qwen-standalone.sh --method npm --registry https://registry.npmjs.org
|
||||
|
||||
# Use the Aliyun standalone mirror
|
||||
bash install-qwen-with-source.sh --mirror aliyun
|
||||
bash install-qwen-standalone.sh --mirror aliyun
|
||||
|
||||
# Install an offline archive
|
||||
# SHA256SUMS must be in the same directory.
|
||||
bash install-qwen-with-source.sh --archive ./qwen-code-linux-x64.tar.gz
|
||||
bash install-qwen-standalone.sh --archive ./qwen-code-linux-x64.tar.gz
|
||||
```
|
||||
|
||||
Standalone installs to:
|
||||
|
|
@ -110,24 +177,35 @@ Standalone installs to:
|
|||
Override with `QWEN_INSTALL_ROOT`, `QWEN_INSTALL_LIB_PARENT`,
|
||||
`QWEN_INSTALL_LIB_DIR`, or `QWEN_INSTALL_BIN_DIR` when needed.
|
||||
|
||||
Uninstall a standalone Linux/macOS install:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/uninstall-qwen-standalone.sh | bash
|
||||
```
|
||||
|
||||
The uninstaller removes only the standalone runtime, generated `qwen` wrapper,
|
||||
and installer-managed shell PATH block. It preserves `~/.qwen` by default. Set
|
||||
`QWEN_UNINSTALL_PURGE=1` to remove `~/.qwen/source.json`; other config and auth
|
||||
files are still preserved.
|
||||
|
||||
## Windows Usage
|
||||
|
||||
```bat
|
||||
REM Default: standalone archive with npm fallback
|
||||
install-qwen-with-source.bat
|
||||
install-qwen-standalone.bat
|
||||
|
||||
REM Record a source value
|
||||
install-qwen-with-source.bat --source github
|
||||
install-qwen-standalone.bat --source github
|
||||
|
||||
REM Use npm explicitly
|
||||
install-qwen-with-source.bat --method npm --registry https://registry.npmjs.org
|
||||
install-qwen-standalone.bat --method npm --registry https://registry.npmjs.org
|
||||
|
||||
REM Use the Aliyun standalone mirror
|
||||
install-qwen-with-source.bat --mirror aliyun
|
||||
install-qwen-standalone.bat --mirror aliyun
|
||||
|
||||
REM Install an offline archive
|
||||
REM SHA256SUMS must be in the same directory.
|
||||
install-qwen-with-source.bat --archive qwen-code-win-x64.zip
|
||||
install-qwen-standalone.bat --archive qwen-code-win-x64.zip
|
||||
```
|
||||
|
||||
Standalone installs to:
|
||||
|
|
@ -140,6 +218,18 @@ Override with `QWEN_INSTALL_ROOT`, `QWEN_INSTALL_LIB_DIR`, or
|
|||
|
||||
Restart the terminal if `qwen` is not immediately available on PATH.
|
||||
|
||||
Uninstall a standalone Windows install:
|
||||
|
||||
```bat
|
||||
powershell -ExecutionPolicy Bypass -c "irm https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/uninstall-qwen-standalone.ps1 | iex"
|
||||
```
|
||||
|
||||
The uninstaller removes only the standalone runtime, generated `qwen.cmd`
|
||||
wrapper, user PATH entry, and the current-session `cmd.exe` shim created by the
|
||||
hosted PowerShell installer. It preserves `%USERPROFILE%\.qwen` by default. Set
|
||||
`QWEN_UNINSTALL_PURGE=1` to remove `%USERPROFILE%\.qwen\source.json`; other
|
||||
config and auth files are still preserved.
|
||||
|
||||
## Mirrors and Overrides
|
||||
|
||||
Options:
|
||||
|
|
@ -165,9 +255,12 @@ Use `--base-url` for private mirrors. The URL must contain
|
|||
`qwen-code-<target>` archives and `SHA256SUMS` in the same directory. Custom
|
||||
base URLs must use `https://`.
|
||||
|
||||
For Aliyun OSS/CDN, release publishing must upload byte-identical artifacts to
|
||||
both the versioned directory, for example `v0.16.0/`, and the `latest/`
|
||||
directory used by the default installer path.
|
||||
For Aliyun OSS/CDN, release publishing uploads byte-identical artifacts to the
|
||||
versioned directory, for example `releases/qwen-code/vX.Y.Z/`. Stable releases
|
||||
also update the small `releases/qwen-code/latest/VERSION` pointer used by the
|
||||
default installer path. The installer reads that pointer and then downloads the
|
||||
versioned archive plus the versioned `SHA256SUMS`; nightly and preview releases
|
||||
do not update the pointer.
|
||||
|
||||
## Supported Source Values
|
||||
|
||||
|
|
@ -199,7 +292,7 @@ unreadable source files are ignored.
|
|||
|
||||
## Manual Installation
|
||||
|
||||
If source tracking is not needed and Node.js 20 or newer is already available:
|
||||
If source tracking is not needed and Node.js 22 or newer is already available:
|
||||
|
||||
```bash
|
||||
npm install -g @qwen-code/qwen-code@latest
|
||||
|
|
@ -220,7 +313,7 @@ fails so that automation can detect the missing artifact.
|
|||
|
||||
### Node.js Missing or Too Old
|
||||
|
||||
This only blocks npm installation. Install or activate Node.js 20 or newer, then
|
||||
This only blocks npm installation. Install or activate Node.js 22 or newer, then
|
||||
rerun the installer with `--method npm` or let `detect` fall back again.
|
||||
|
||||
### npm Missing
|
||||
|
|
|
|||
1323
scripts/installation/install-qwen-standalone.bat
Normal file
1323
scripts/installation/install-qwen-standalone.bat
Normal file
File diff suppressed because it is too large
Load diff
415
scripts/installation/install-qwen-standalone.ps1
Normal file
415
scripts/installation/install-qwen-standalone.ps1
Normal file
|
|
@ -0,0 +1,415 @@
|
|||
# Qwen Code Windows hosted PowerShell entrypoint.
|
||||
# Pairs with install-qwen-standalone.bat: this shim downloads the .bat into TEMP,
|
||||
# verifies its checksum, and runs it with forwarded arguments.
|
||||
#
|
||||
# PowerShell (runs in current session, qwen available immediately):
|
||||
# irm https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen-standalone.ps1 | iex
|
||||
#
|
||||
# cmd.exe (runs in current session, qwen available immediately):
|
||||
# curl -fsSL https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen-standalone.bat -o %TEMP%\install-qwen.bat && %TEMP%\install-qwen.bat
|
||||
#
|
||||
# To pin a specific release, set $env:QWEN_INSTALL_VERSION before invoking,
|
||||
# e.g. $env:QWEN_INSTALL_VERSION = 'vX.Y.Z'. This is equivalent to passing
|
||||
# --version vX.Y.Z to install-qwen-standalone.bat directly.
|
||||
#
|
||||
# To point this shim at a non-production hosted endpoint (staging buckets,
|
||||
# private mirrors), set $env:QWEN_INSTALLER_BAT_URL to the alternate .bat URL.
|
||||
# The override is required to be HTTPS so a misconfigured value can't silently
|
||||
# downgrade the download channel. The downstream .bat continues to honor
|
||||
# QWEN_INSTALL_BASE_URL for archive resolution.
|
||||
#
|
||||
# By default the matching SHA256SUMS file is read from the same hosted
|
||||
# directory as the .bat. Set $env:QWEN_INSTALLER_CHECKSUMS_URL to override it
|
||||
# when testing a custom installer endpoint.
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
function Download-File {
|
||||
param([string]$Url, [string]$OutFile)
|
||||
$prevProgressPreference = $global:ProgressPreference
|
||||
$global:ProgressPreference = 'SilentlyContinue'
|
||||
try {
|
||||
if (Get-Command curl.exe -ErrorAction SilentlyContinue) {
|
||||
curl.exe --connect-timeout 15 --max-time 300 --retry 2 -sSfLo $OutFile $Url
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "curl.exe download failed (exit code $LASTEXITCODE)"
|
||||
}
|
||||
return
|
||||
}
|
||||
Invoke-WebRequest -Uri $Url -OutFile $OutFile -UseBasicParsing -MaximumRedirection 10 -TimeoutSec 300
|
||||
} finally {
|
||||
$global:ProgressPreference = $prevProgressPreference
|
||||
}
|
||||
}
|
||||
|
||||
function Get-QwenInstallBase {
|
||||
if (-not [string]::IsNullOrEmpty($env:QWEN_INSTALL_ROOT)) {
|
||||
return $env:QWEN_INSTALL_ROOT
|
||||
}
|
||||
|
||||
if (-not [string]::IsNullOrEmpty($env:LOCALAPPDATA)) {
|
||||
return Join-Path $env:LOCALAPPDATA 'qwen-code'
|
||||
}
|
||||
|
||||
return Join-Path (Join-Path $env:USERPROFILE 'AppData\Local') 'qwen-code'
|
||||
}
|
||||
|
||||
function Get-QwenInstallBinDir {
|
||||
if (-not [string]::IsNullOrEmpty($env:QWEN_INSTALL_BIN_DIR)) {
|
||||
return $env:QWEN_INSTALL_BIN_DIR
|
||||
}
|
||||
|
||||
return Join-Path (Get-QwenInstallBase) 'bin'
|
||||
}
|
||||
|
||||
function Get-CurrentCmdShimStatePath {
|
||||
return Join-Path (Get-QwenInstallBase) 'current-cmd-shim.txt'
|
||||
}
|
||||
|
||||
function Save-CurrentCmdPathShim {
|
||||
param([string]$ShimPath)
|
||||
|
||||
if ([string]::IsNullOrEmpty($ShimPath)) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
$statePath = Get-CurrentCmdShimStatePath
|
||||
New-Item -ItemType Directory -Path (Split-Path -Parent $statePath) -Force | Out-Null
|
||||
[IO.File]::WriteAllText($statePath, $ShimPath, [Text.UTF8Encoding]::new($false))
|
||||
} catch {
|
||||
# Best-effort cleanup hint only. The installer still works if this fails.
|
||||
}
|
||||
}
|
||||
|
||||
function Update-CurrentSessionPath {
|
||||
param([string]$BinDir)
|
||||
|
||||
if ([string]::IsNullOrEmpty($BinDir)) {
|
||||
return
|
||||
}
|
||||
|
||||
$entries = @($env:Path -split ';' | Where-Object { -not [string]::IsNullOrEmpty($_) })
|
||||
foreach ($entry in $entries) {
|
||||
if ([string]::Equals($entry, $BinDir, [StringComparison]::OrdinalIgnoreCase)) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
$env:Path = (@($BinDir) + $entries) -join ';'
|
||||
}
|
||||
|
||||
function Get-ParentProcessName {
|
||||
try {
|
||||
$current = Get-CimInstance Win32_Process -Filter "ProcessId = $PID" -ErrorAction Stop
|
||||
if ($null -eq $current -or $null -eq $current.ParentProcessId) {
|
||||
return $null
|
||||
}
|
||||
$parent = Get-CimInstance Win32_Process -Filter "ProcessId = $($current.ParentProcessId)" -ErrorAction Stop
|
||||
if ($null -eq $parent) {
|
||||
return $null
|
||||
}
|
||||
return $parent.Name
|
||||
} catch {
|
||||
return $null
|
||||
}
|
||||
}
|
||||
|
||||
function Get-NormalizedPath {
|
||||
param([string]$PathValue)
|
||||
|
||||
if ([string]::IsNullOrEmpty($PathValue)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$trimmed = $PathValue.Trim().Trim('"')
|
||||
if ([string]::IsNullOrEmpty($trimmed)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
try {
|
||||
return [IO.Path]::GetFullPath($trimmed).TrimEnd('\')
|
||||
} catch {
|
||||
return $trimmed.TrimEnd('\')
|
||||
}
|
||||
}
|
||||
|
||||
function Test-PathContainsDirectory {
|
||||
param([string]$PathValue, [string]$Directory)
|
||||
|
||||
$target = Get-NormalizedPath -PathValue $Directory
|
||||
if ([string]::IsNullOrEmpty($target)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
foreach ($entry in @($PathValue -split ';')) {
|
||||
$normalizedEntry = Get-NormalizedPath -PathValue $entry
|
||||
if ([string]::Equals($normalizedEntry, $target, [StringComparison]::OrdinalIgnoreCase)) {
|
||||
return $true
|
||||
}
|
||||
}
|
||||
|
||||
return $false
|
||||
}
|
||||
|
||||
function Test-WritableDirectory {
|
||||
param([string]$Directory)
|
||||
|
||||
if ([string]::IsNullOrEmpty($Directory)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath $Directory -PathType Container)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
$probe = Join-Path $Directory ('.qwen-write-test-' + [IO.Path]::GetRandomFileName())
|
||||
try {
|
||||
[IO.File]::WriteAllText($probe, '')
|
||||
Remove-Item -LiteralPath $probe -Force -ErrorAction SilentlyContinue
|
||||
return $true
|
||||
} catch {
|
||||
Remove-Item -LiteralPath $probe -Force -ErrorAction SilentlyContinue
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
function Add-PathCandidate {
|
||||
param(
|
||||
[System.Collections.Generic.List[string]]$Candidates,
|
||||
[string]$Directory
|
||||
)
|
||||
|
||||
$normalizedDirectory = Get-NormalizedPath -PathValue $Directory
|
||||
if ([string]::IsNullOrEmpty($normalizedDirectory)) {
|
||||
return
|
||||
}
|
||||
|
||||
foreach ($candidate in $Candidates) {
|
||||
$normalizedCandidate = Get-NormalizedPath -PathValue $candidate
|
||||
if ([string]::Equals($normalizedCandidate, $normalizedDirectory, [StringComparison]::OrdinalIgnoreCase)) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
[void]$Candidates.Add($Directory.Trim().Trim('"'))
|
||||
}
|
||||
|
||||
function Test-SystemManagedPathDirectory {
|
||||
param([string]$Directory)
|
||||
|
||||
$normalizedDirectory = Get-NormalizedPath -PathValue $Directory
|
||||
return (
|
||||
-not [string]::IsNullOrEmpty($normalizedDirectory) -and
|
||||
$normalizedDirectory -match '\\Microsoft\\WindowsApps$'
|
||||
)
|
||||
}
|
||||
|
||||
function Install-CurrentCmdPathShim {
|
||||
param([string]$QwenCommand, [string]$PathValue)
|
||||
|
||||
$pathEntries = @($PathValue -split ';' | Where-Object { -not [string]::IsNullOrEmpty($_) })
|
||||
$candidates = [System.Collections.Generic.List[string]]::new()
|
||||
$preferredDirectories = @()
|
||||
|
||||
if (-not [string]::IsNullOrEmpty($env:APPDATA)) {
|
||||
$preferredDirectories += Join-Path $env:APPDATA 'npm'
|
||||
}
|
||||
if (-not [string]::IsNullOrEmpty($env:USERPROFILE)) {
|
||||
$preferredDirectories += Join-Path $env:USERPROFILE '.bun\bin'
|
||||
}
|
||||
|
||||
foreach ($preferredDirectory in $preferredDirectories) {
|
||||
$preferredNormalized = Get-NormalizedPath -PathValue $preferredDirectory
|
||||
foreach ($entry in $pathEntries) {
|
||||
$entryNormalized = Get-NormalizedPath -PathValue $entry
|
||||
if ([string]::Equals($entryNormalized, $preferredNormalized, [StringComparison]::OrdinalIgnoreCase)) {
|
||||
Add-PathCandidate -Candidates $candidates -Directory $entry
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$userRoot = Get-NormalizedPath -PathValue $env:USERPROFILE
|
||||
foreach ($entry in $pathEntries) {
|
||||
if (Test-SystemManagedPathDirectory -Directory $entry) {
|
||||
continue
|
||||
}
|
||||
$entryNormalized = Get-NormalizedPath -PathValue $entry
|
||||
if (
|
||||
-not [string]::IsNullOrEmpty($userRoot) -and
|
||||
-not [string]::IsNullOrEmpty($entryNormalized) -and
|
||||
$entryNormalized.StartsWith($userRoot, [StringComparison]::OrdinalIgnoreCase)
|
||||
) {
|
||||
Add-PathCandidate -Candidates $candidates -Directory $entry
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($candidate in $candidates) {
|
||||
if (-not (Test-WritableDirectory -Directory $candidate)) {
|
||||
continue
|
||||
}
|
||||
|
||||
$shimPath = Join-Path $candidate 'qwen.cmd'
|
||||
if (Test-Path -LiteralPath $shimPath -PathType Leaf) {
|
||||
$existingShim = Get-Content -LiteralPath $shimPath -Raw -ErrorAction SilentlyContinue
|
||||
if ($existingShim -notmatch 'Qwen Code current-session shim') {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
$shim = "@echo off`r`nREM Qwen Code current-session shim. Generated by install-qwen-standalone.ps1.`r`ncall `"$QwenCommand`" %*`r`n"
|
||||
# Write to a sibling temp file first, then atomically rename so a partial
|
||||
# write (process killed, disk full) cannot leave a half-written shim on
|
||||
# PATH.
|
||||
$shimTempPath = "$shimPath.new"
|
||||
[IO.File]::WriteAllText($shimTempPath, $shim, [Text.UTF8Encoding]::new($false))
|
||||
Move-Item -LiteralPath $shimTempPath -Destination $shimPath -Force
|
||||
Save-CurrentCmdPathShim -ShimPath $shimPath
|
||||
return $shimPath
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
function Update-CurrentShell {
|
||||
$qwenInstallBinDir = Get-QwenInstallBinDir
|
||||
$qwenCommandPath = Join-Path $qwenInstallBinDir 'qwen.cmd'
|
||||
if (-not (Test-Path -LiteralPath $qwenCommandPath -PathType Leaf)) {
|
||||
return
|
||||
}
|
||||
|
||||
if ($env:QWEN_NO_MODIFY_PATH -eq '1') {
|
||||
Write-Output "Run: ${qwenCommandPath}"
|
||||
Write-Output "INFO: QWEN_NO_MODIFY_PATH=1; skipping current-session PATH refresh."
|
||||
return
|
||||
}
|
||||
|
||||
$inheritedPath = $env:Path
|
||||
Update-CurrentSessionPath -BinDir $qwenInstallBinDir
|
||||
|
||||
Write-Output "Run: qwen"
|
||||
$parentProcessName = Get-ParentProcessName
|
||||
if ($parentProcessName -ieq 'cmd.exe') {
|
||||
if (Test-PathContainsDirectory -PathValue $inheritedPath -Directory $qwenInstallBinDir) {
|
||||
Write-Output "qwen is ready to use after this installer command returns."
|
||||
return
|
||||
}
|
||||
|
||||
$shimPath = Install-CurrentCmdPathShim -QwenCommand $qwenCommandPath -PathValue $inheritedPath
|
||||
if (-not [string]::IsNullOrEmpty($shimPath)) {
|
||||
Write-Output "INFO: Added qwen.cmd to a directory already on this cmd.exe PATH:"
|
||||
Write-Output "INFO: ${shimPath}"
|
||||
Write-Output "qwen is ready to use after this installer command returns."
|
||||
return
|
||||
}
|
||||
|
||||
Write-Output "WARNING: Windows does not allow this PowerShell child process to update the parent cmd.exe PATH directly."
|
||||
Write-Output "Or, for this cmd.exe window, run:"
|
||||
Write-Output " set `"PATH=${qwenInstallBinDir};%PATH%`""
|
||||
return
|
||||
}
|
||||
|
||||
Write-Output "qwen is ready to use in this PowerShell session."
|
||||
}
|
||||
|
||||
$qwenDefaultInstallerUrl = 'https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/install-qwen-standalone.bat'
|
||||
$qwenDefaultChecksumsUrl = 'https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/SHA256SUMS'
|
||||
if ([string]::IsNullOrEmpty($env:QWEN_INSTALLER_BAT_URL)) {
|
||||
$qwenInstallerUrl = $qwenDefaultInstallerUrl
|
||||
} else {
|
||||
if ($env:QWEN_INSTALLER_BAT_URL -notmatch '^https://') {
|
||||
Write-Error "QWEN_INSTALLER_BAT_URL must start with https://"
|
||||
exit 1
|
||||
}
|
||||
$qwenInstallerUrl = $env:QWEN_INSTALLER_BAT_URL
|
||||
}
|
||||
|
||||
if ([string]::IsNullOrEmpty($env:QWEN_INSTALLER_CHECKSUMS_URL)) {
|
||||
if ($qwenInstallerUrl -eq $qwenDefaultInstallerUrl) {
|
||||
$qwenChecksumsUrl = $qwenDefaultChecksumsUrl
|
||||
} else {
|
||||
$qwenChecksumsUrl = [Uri]::new([Uri]$qwenInstallerUrl, 'SHA256SUMS').AbsoluteUri
|
||||
}
|
||||
} else {
|
||||
if ($env:QWEN_INSTALLER_CHECKSUMS_URL -notmatch '^https://') {
|
||||
Write-Error "QWEN_INSTALLER_CHECKSUMS_URL must start with https://"
|
||||
exit 1
|
||||
}
|
||||
$qwenChecksumsUrl = $env:QWEN_INSTALLER_CHECKSUMS_URL
|
||||
}
|
||||
|
||||
$qwenInstallerName = [IO.Path]::GetFileName(([Uri]$qwenInstallerUrl).AbsolutePath)
|
||||
if ([string]::IsNullOrEmpty($qwenInstallerName)) {
|
||||
$qwenInstallerName = 'install-qwen-standalone.bat'
|
||||
}
|
||||
if ([string]::IsNullOrEmpty($env:TEMP)) {
|
||||
Write-Error "TEMP environment variable is not set. Please set TEMP to a writable directory."
|
||||
exit 1
|
||||
}
|
||||
# Use a cryptographically random staging filename so a same-user attacker cannot
|
||||
# pre-stage a malicious .bat at a predictable path and race the verify/execute
|
||||
# window between Get-FileHash and `& $qwenInstallerPath`.
|
||||
$qwenStagingSuffix = [IO.Path]::GetRandomFileName()
|
||||
$qwenInstallerPath = Join-Path $env:TEMP "qwen-installer-$qwenStagingSuffix.bat"
|
||||
$qwenChecksumsPath = Join-Path $env:TEMP "qwen-installation-SHA256SUMS-$qwenStagingSuffix"
|
||||
|
||||
try {
|
||||
Download-File -Url $qwenInstallerUrl -OutFile $qwenInstallerPath
|
||||
} catch {
|
||||
Write-Error "Failed to download Qwen Code installer from ${qwenInstallerUrl}: $($_.Exception.Message)"
|
||||
exit 1
|
||||
}
|
||||
|
||||
try {
|
||||
Download-File -Url $qwenChecksumsUrl -OutFile $qwenChecksumsPath
|
||||
} catch {
|
||||
Remove-Item -LiteralPath $qwenInstallerPath -Force -ErrorAction SilentlyContinue
|
||||
Write-Error "Failed to download Qwen Code installer checksums from ${qwenChecksumsUrl}: $($_.Exception.Message)"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$qwenExpectedHash = $null
|
||||
foreach ($qwenChecksumLine in Get-Content -LiteralPath $qwenChecksumsPath) {
|
||||
if ($qwenChecksumLine -match '^([0-9a-fA-F]{64})\s+\*?(.+)$') {
|
||||
if ($Matches[2] -eq $qwenInstallerName) {
|
||||
$qwenExpectedHash = $Matches[1].ToLowerInvariant()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if ([string]::IsNullOrEmpty($qwenExpectedHash)) {
|
||||
Remove-Item -LiteralPath $qwenInstallerPath -Force -ErrorAction SilentlyContinue
|
||||
Remove-Item -LiteralPath $qwenChecksumsPath -Force -ErrorAction SilentlyContinue
|
||||
Write-Error "Checksum entry for ${qwenInstallerName} not found in ${qwenChecksumsUrl}"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$qwenActualHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $qwenInstallerPath).Hash.ToLowerInvariant()
|
||||
if ($qwenActualHash -ne $qwenExpectedHash) {
|
||||
Remove-Item -LiteralPath $qwenInstallerPath -Force -ErrorAction SilentlyContinue
|
||||
Remove-Item -LiteralPath $qwenChecksumsPath -Force -ErrorAction SilentlyContinue
|
||||
Write-Error "Checksum mismatch for ${qwenInstallerName}: expected ${qwenExpectedHash}, got ${qwenActualHash}."
|
||||
exit 1
|
||||
}
|
||||
|
||||
$qwenInstallerExitCode = 0
|
||||
$qwenPreviousParentPowerShell = $env:QWEN_INSTALLER_PARENT_POWERSHELL
|
||||
try {
|
||||
$env:QWEN_INSTALLER_PARENT_POWERSHELL = '1'
|
||||
& $qwenInstallerPath @args
|
||||
$qwenInstallerExitCode = $LASTEXITCODE
|
||||
} finally {
|
||||
if ($null -eq $qwenPreviousParentPowerShell) {
|
||||
Remove-Item Env:\QWEN_INSTALLER_PARENT_POWERSHELL -ErrorAction SilentlyContinue
|
||||
} else {
|
||||
$env:QWEN_INSTALLER_PARENT_POWERSHELL = $qwenPreviousParentPowerShell
|
||||
}
|
||||
Remove-Item -LiteralPath $qwenInstallerPath -Force -ErrorAction SilentlyContinue
|
||||
Remove-Item -LiteralPath $qwenChecksumsPath -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
if ($qwenInstallerExitCode -ne 0) {
|
||||
exit $qwenInstallerExitCode
|
||||
}
|
||||
|
||||
Update-CurrentShell
|
||||
1467
scripts/installation/install-qwen-standalone.sh
Executable file
1467
scripts/installation/install-qwen-standalone.sh
Executable file
File diff suppressed because it is too large
Load diff
|
|
@ -221,7 +221,8 @@ set "QWEN_VALIDATE_NPM_REGISTRY=!NPM_REGISTRY!"
|
|||
set "QWEN_VALIDATE_INSTALL_BASE=!INSTALL_BASE!"
|
||||
set "QWEN_VALIDATE_INSTALL_DIR=!INSTALL_DIR!"
|
||||
set "QWEN_VALIDATE_INSTALL_BIN_DIR=!INSTALL_BIN_DIR!"
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -Command "$unsafe = [char[]](10,13,33,34,37,38,60,62,94,96,124); foreach ($name in 'METHOD','MIRROR','BASE_URL','ARCHIVE_PATH','VERSION','NPM_REGISTRY','INSTALL_BASE','INSTALL_DIR','INSTALL_BIN_DIR') { $value = [Environment]::GetEnvironmentVariable('QWEN_VALIDATE_' + $name); if ($null -ne $value -and $value.IndexOfAny($unsafe) -ge 0) { exit 1 } }"
|
||||
set "QWEN_VALIDATE_SOURCE=!SOURCE!"
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -Command "$unsafe = [char[]](10,13,33,34,37,38,60,62,94,96,124); foreach ($name in 'METHOD','MIRROR','BASE_URL','ARCHIVE_PATH','VERSION','NPM_REGISTRY','INSTALL_BASE','INSTALL_DIR','INSTALL_BIN_DIR','SOURCE') { $value = [Environment]::GetEnvironmentVariable('QWEN_VALIDATE_' + $name); if ($null -ne $value -and $value.IndexOfAny($unsafe) -ge 0) { exit 1 } }"
|
||||
set "PS_STATUS=%ERRORLEVEL%"
|
||||
set "QWEN_VALIDATE_METHOD="
|
||||
set "QWEN_VALIDATE_MIRROR="
|
||||
|
|
@ -232,6 +233,7 @@ set "QWEN_VALIDATE_NPM_REGISTRY="
|
|||
set "QWEN_VALIDATE_INSTALL_BASE="
|
||||
set "QWEN_VALIDATE_INSTALL_DIR="
|
||||
set "QWEN_VALIDATE_INSTALL_BIN_DIR="
|
||||
set "QWEN_VALIDATE_SOURCE="
|
||||
if %PS_STATUS% NEQ 0 (
|
||||
echo ERROR: installer options contain unsafe command characters.
|
||||
exit /b 1
|
||||
|
|
@ -509,6 +511,11 @@ if !ERRORLEVEL! NEQ 0 (
|
|||
REM Extract into a temporary directory, then validate required entry points.
|
||||
set "EXTRACT_DIR=!TEMP_DIR!\extract"
|
||||
mkdir "!EXTRACT_DIR!" >nul 2>&1
|
||||
call :ValidateArchiveContents "!ARCHIVE_FILE!"
|
||||
if !ERRORLEVEL! NEQ 0 (
|
||||
if exist "!TEMP_DIR!" rmdir /S /Q "!TEMP_DIR!" >nul 2>&1
|
||||
exit /b 1
|
||||
)
|
||||
set "QWEN_ARCHIVE_FILE=!ARCHIVE_FILE!"
|
||||
set "QWEN_EXTRACT_DIR=!EXTRACT_DIR!"
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -Command "Expand-Archive -LiteralPath $env:QWEN_ARCHIVE_FILE -DestinationPath $env:QWEN_EXTRACT_DIR -Force"
|
||||
|
|
@ -620,6 +627,26 @@ echo SUCCESS: Qwen Code standalone archive installed successfully.
|
|||
echo INFO: Installed to !INSTALL_DIR!
|
||||
exit /b 0
|
||||
|
||||
:ValidateArchiveContents
|
||||
set "QWEN_ARCHIVE_FILE=%~1"
|
||||
REM Enumerate archive entries and reject any with path traversal indicators:
|
||||
REM empty names, leading '/', drive-rooted paths, '..' segments, or control chars.
|
||||
REM This prevents Zip Slip attacks before extraction.
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference = 'Stop'; $archive = $null; try { Add-Type -AssemblyName System.IO.Compression.FileSystem; $archive = [IO.Compression.ZipFile]::OpenRead($env:QWEN_ARCHIVE_FILE); foreach ($entry in $archive.Entries) { $raw = $entry.FullName; if ($raw.IndexOfAny([char[]](10,13)) -ge 0) { [Console]::Error.WriteLine('Archive contains unsafe path with control character: ' + $raw); exit 1 }; $name = $raw -replace '\\', '/'; while ($name.StartsWith('./')) { $name = $name.Substring(2) }; if ($name -eq '' -or $name.StartsWith('/') -or $name -match '^[A-Za-z]:' -or $name -match '(^|/)\.\.(/|$)') { [Console]::Error.WriteLine('Archive contains unsafe path: ' + $entry.FullName); exit 1 } } } catch { [Console]::Error.WriteLine($_.Exception.Message); exit 2 } finally { if ($null -ne $archive) { $archive.Dispose() } }"
|
||||
set "PS_STATUS=%ERRORLEVEL%"
|
||||
set "QWEN_ARCHIVE_FILE="
|
||||
if %PS_STATUS% EQU 0 exit /b 0
|
||||
if %PS_STATUS% EQU 1 (
|
||||
echo ERROR: Archive contains unsafe path entries.
|
||||
exit /b 1
|
||||
)
|
||||
if %PS_STATUS% EQU 2 (
|
||||
echo ERROR: Archive could not be inspected before extraction.
|
||||
exit /b 1
|
||||
)
|
||||
echo ERROR: Archive validation failed before extraction.
|
||||
exit /b %PS_STATUS%
|
||||
|
||||
:RejectArchiveLinks
|
||||
set "QWEN_EXTRACT_DIR=%~1"
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -Command "$item = Get-ChildItem -LiteralPath $env:QWEN_EXTRACT_DIR -Recurse -Force | Where-Object { ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0 } | Select-Object -First 1; if ($item) { exit 1 }"
|
||||
|
|
|
|||
372
scripts/installation/uninstall-qwen-standalone.ps1
Normal file
372
scripts/installation/uninstall-qwen-standalone.ps1
Normal file
|
|
@ -0,0 +1,372 @@
|
|||
# Qwen Code standalone uninstaller.
|
||||
# Removes files owned by install-qwen-standalone.bat/.ps1 and preserves user
|
||||
# config by default.
|
||||
#
|
||||
# Usage:
|
||||
# powershell -ExecutionPolicy Bypass -c "irm https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/installation/uninstall-qwen-standalone.ps1 | iex"
|
||||
#
|
||||
# Set $env:QWEN_UNINSTALL_PURGE = '1' (or pass -Purge) to also remove the
|
||||
# installer source marker at %USERPROFILE%\.qwen\source.json. Other Qwen Code
|
||||
# config and auth files are preserved.
|
||||
|
||||
param(
|
||||
[switch]$Purge,
|
||||
[switch]$Help
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
if ($Help) {
|
||||
Write-Output @"
|
||||
Qwen Code standalone uninstaller.
|
||||
|
||||
Usage:
|
||||
uninstall-qwen-standalone.ps1 [-Purge] [-Help]
|
||||
|
||||
Options:
|
||||
-Purge Also remove %USERPROFILE%\.qwen\source.json (same as
|
||||
QWEN_UNINSTALL_PURGE=1).
|
||||
-Help Show this message and exit.
|
||||
"@
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Purge) {
|
||||
$env:QWEN_UNINSTALL_PURGE = '1'
|
||||
}
|
||||
|
||||
function Write-Info {
|
||||
param([string]$Message)
|
||||
Write-Output "INFO: $Message"
|
||||
}
|
||||
|
||||
function Write-Success {
|
||||
param([string]$Message)
|
||||
Write-Output "SUCCESS: $Message"
|
||||
}
|
||||
|
||||
function Write-WarningMessage {
|
||||
param([string]$Message)
|
||||
Write-Output "WARNING: $Message"
|
||||
}
|
||||
|
||||
function Get-QwenInstallBase {
|
||||
if (-not [string]::IsNullOrEmpty($env:QWEN_INSTALL_ROOT)) {
|
||||
return $env:QWEN_INSTALL_ROOT
|
||||
}
|
||||
|
||||
if (-not [string]::IsNullOrEmpty($env:LOCALAPPDATA)) {
|
||||
return Join-Path $env:LOCALAPPDATA 'qwen-code'
|
||||
}
|
||||
|
||||
return Join-Path (Join-Path $env:USERPROFILE 'AppData\Local') 'qwen-code'
|
||||
}
|
||||
|
||||
function Get-QwenInstallDir {
|
||||
if (-not [string]::IsNullOrEmpty($env:QWEN_INSTALL_LIB_DIR)) {
|
||||
return $env:QWEN_INSTALL_LIB_DIR
|
||||
}
|
||||
|
||||
return Join-Path (Get-QwenInstallBase) 'qwen-code'
|
||||
}
|
||||
|
||||
function Get-QwenInstallBinDir {
|
||||
if (-not [string]::IsNullOrEmpty($env:QWEN_INSTALL_BIN_DIR)) {
|
||||
return $env:QWEN_INSTALL_BIN_DIR
|
||||
}
|
||||
|
||||
return Join-Path (Get-QwenInstallBase) 'bin'
|
||||
}
|
||||
|
||||
function Get-CurrentCmdShimStatePath {
|
||||
return Join-Path (Get-QwenInstallBase) 'current-cmd-shim.txt'
|
||||
}
|
||||
|
||||
function Get-NormalizedPath {
|
||||
param([string]$PathValue)
|
||||
|
||||
if ([string]::IsNullOrEmpty($PathValue)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$trimmed = $PathValue.Trim().Trim('"')
|
||||
if ([string]::IsNullOrEmpty($trimmed)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
try {
|
||||
return [IO.Path]::GetFullPath($trimmed).TrimEnd('\')
|
||||
} catch {
|
||||
return $trimmed.TrimEnd('\')
|
||||
}
|
||||
}
|
||||
|
||||
function Test-PathMatches {
|
||||
param([string]$Left, [string]$Right)
|
||||
|
||||
$leftPath = Get-NormalizedPath -PathValue $Left
|
||||
$rightPath = Get-NormalizedPath -PathValue $Right
|
||||
if ([string]::IsNullOrEmpty($leftPath) -or [string]::IsNullOrEmpty($rightPath)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
return [string]::Equals($leftPath, $rightPath, [StringComparison]::OrdinalIgnoreCase)
|
||||
}
|
||||
|
||||
function Test-QwenStandaloneInstallDir {
|
||||
param([string]$InstallDir)
|
||||
|
||||
if (-not (Test-Path -LiteralPath $InstallDir -PathType Container)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
$manifestPath = Join-Path $InstallDir 'manifest.json'
|
||||
if (-not (Test-Path -LiteralPath $manifestPath -PathType Leaf)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
try {
|
||||
$manifest = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json
|
||||
} catch {
|
||||
return $false
|
||||
}
|
||||
|
||||
if ($manifest.name -ne '@qwen-code/qwen-code') {
|
||||
return $false
|
||||
}
|
||||
|
||||
if ([string]$manifest.target -notmatch '^win-(x64|arm64)$') {
|
||||
return $false
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $InstallDir 'bin\qwen.cmd') -PathType Leaf)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $InstallDir 'node\node.exe') -PathType Leaf)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
return $true
|
||||
}
|
||||
|
||||
function Remove-UserPathEntry {
|
||||
param([string]$BinDir)
|
||||
|
||||
$target = Get-NormalizedPath -PathValue $BinDir
|
||||
if ([string]::IsNullOrEmpty($target)) {
|
||||
return
|
||||
}
|
||||
|
||||
$userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
|
||||
if ([string]::IsNullOrEmpty($userPath)) {
|
||||
return
|
||||
}
|
||||
|
||||
$kept = New-Object System.Collections.Generic.List[string]
|
||||
$removed = $false
|
||||
foreach ($entry in @($userPath -split ';')) {
|
||||
if ([string]::IsNullOrEmpty($entry)) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (Test-PathMatches -Left $entry -Right $target) {
|
||||
$removed = $true
|
||||
continue
|
||||
}
|
||||
|
||||
[void]$kept.Add($entry)
|
||||
}
|
||||
|
||||
if ($removed) {
|
||||
[Environment]::SetEnvironmentVariable('Path', ($kept -join ';'), 'User')
|
||||
Write-Success "Removed $BinDir from user PATH."
|
||||
}
|
||||
|
||||
$current = New-Object System.Collections.Generic.List[string]
|
||||
foreach ($entry in @($env:Path -split ';')) {
|
||||
if ([string]::IsNullOrEmpty($entry)) {
|
||||
continue
|
||||
}
|
||||
if (-not (Test-PathMatches -Left $entry -Right $target)) {
|
||||
[void]$current.Add($entry)
|
||||
}
|
||||
}
|
||||
$env:Path = $current -join ';'
|
||||
}
|
||||
|
||||
function Add-PathCandidate {
|
||||
param(
|
||||
[System.Collections.Generic.List[string]]$Candidates,
|
||||
[string]$Directory
|
||||
)
|
||||
|
||||
$normalizedDirectory = Get-NormalizedPath -PathValue $Directory
|
||||
if ([string]::IsNullOrEmpty($normalizedDirectory)) {
|
||||
return
|
||||
}
|
||||
|
||||
foreach ($candidate in $Candidates) {
|
||||
$normalizedCandidate = Get-NormalizedPath -PathValue $candidate
|
||||
if ([string]::Equals($normalizedCandidate, $normalizedDirectory, [StringComparison]::OrdinalIgnoreCase)) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
[void]$Candidates.Add($Directory.Trim().Trim('"'))
|
||||
}
|
||||
|
||||
function Remove-CurrentCmdPathShimFile {
|
||||
param([string]$ShimPath)
|
||||
|
||||
if ([string]::IsNullOrEmpty($ShimPath)) {
|
||||
return
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath $ShimPath -PathType Leaf)) {
|
||||
return
|
||||
}
|
||||
|
||||
$existingShim = Get-Content -LiteralPath $ShimPath -Raw -ErrorAction SilentlyContinue
|
||||
if ($existingShim -notmatch 'Qwen Code current-session shim') {
|
||||
return
|
||||
}
|
||||
|
||||
Remove-Item -LiteralPath $ShimPath -Force -ErrorAction SilentlyContinue
|
||||
Write-Success "Removed current cmd.exe qwen shim: $ShimPath"
|
||||
}
|
||||
|
||||
function Remove-RecordedCurrentCmdPathShim {
|
||||
$statePath = Get-CurrentCmdShimStatePath
|
||||
if (-not (Test-Path -LiteralPath $statePath -PathType Leaf)) {
|
||||
return
|
||||
}
|
||||
|
||||
foreach ($shimPath in Get-Content -LiteralPath $statePath -ErrorAction SilentlyContinue) {
|
||||
Remove-CurrentCmdPathShimFile -ShimPath $shimPath
|
||||
}
|
||||
|
||||
Remove-Item -LiteralPath $statePath -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
function Remove-CurrentCmdPathShim {
|
||||
Remove-RecordedCurrentCmdPathShim
|
||||
|
||||
$candidates = [System.Collections.Generic.List[string]]::new()
|
||||
foreach ($entry in @($env:Path -split ';')) {
|
||||
if (-not [string]::IsNullOrEmpty($entry)) {
|
||||
Add-PathCandidate -Candidates $candidates -Directory $entry
|
||||
}
|
||||
}
|
||||
|
||||
if (-not [string]::IsNullOrEmpty($env:LOCALAPPDATA)) {
|
||||
Add-PathCandidate -Candidates $candidates -Directory (Join-Path $env:LOCALAPPDATA 'Microsoft\WindowsApps')
|
||||
}
|
||||
if (-not [string]::IsNullOrEmpty($env:APPDATA)) {
|
||||
Add-PathCandidate -Candidates $candidates -Directory (Join-Path $env:APPDATA 'npm')
|
||||
}
|
||||
if (-not [string]::IsNullOrEmpty($env:USERPROFILE)) {
|
||||
Add-PathCandidate -Candidates $candidates -Directory (Join-Path $env:USERPROFILE '.bun\bin')
|
||||
}
|
||||
|
||||
foreach ($candidate in $candidates) {
|
||||
$shimPath = Join-Path $candidate 'qwen.cmd'
|
||||
Remove-CurrentCmdPathShimFile -ShimPath $shimPath
|
||||
}
|
||||
}
|
||||
|
||||
function Remove-InstallWrapper {
|
||||
param([string]$InstallDir, [string]$BinDir)
|
||||
|
||||
$wrapperPath = Join-Path $BinDir 'qwen.cmd'
|
||||
if (-not (Test-Path -LiteralPath $wrapperPath -PathType Leaf)) {
|
||||
return
|
||||
}
|
||||
|
||||
$wrapper = Get-Content -LiteralPath $wrapperPath -Raw -ErrorAction SilentlyContinue
|
||||
$targetCommand = Join-Path (Join-Path $InstallDir 'bin') 'qwen.cmd'
|
||||
if (
|
||||
$wrapper -notmatch [regex]::Escape($targetCommand) -and
|
||||
$wrapper -notmatch 'Qwen Code current-session shim'
|
||||
) {
|
||||
Write-WarningMessage "$wrapperPath does not point at this standalone install; skipping."
|
||||
return
|
||||
}
|
||||
|
||||
Remove-Item -LiteralPath $wrapperPath -Force
|
||||
Write-Success "Removed $wrapperPath"
|
||||
}
|
||||
|
||||
function Remove-EmptyDirectory {
|
||||
param([string]$Directory)
|
||||
|
||||
if ([string]::IsNullOrEmpty($Directory)) {
|
||||
return
|
||||
}
|
||||
|
||||
if (-not (Test-Path -LiteralPath $Directory -PathType Container)) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
Remove-Item -LiteralPath $Directory -Force -ErrorAction Stop
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
function Remove-SourceMarker {
|
||||
if ([string]::IsNullOrEmpty($env:USERPROFILE)) {
|
||||
return
|
||||
}
|
||||
|
||||
$qwenDir = Join-Path $env:USERPROFILE '.qwen'
|
||||
$sourceJson = Join-Path $qwenDir 'source.json'
|
||||
|
||||
if ($env:QWEN_UNINSTALL_PURGE -ne '1') {
|
||||
Write-Info "Preserving $qwenDir (set QWEN_UNINSTALL_PURGE=1 to remove source.json)."
|
||||
return
|
||||
}
|
||||
|
||||
if (Test-Path -LiteralPath $sourceJson -PathType Leaf) {
|
||||
Remove-Item -LiteralPath $sourceJson -Force
|
||||
Write-Success "Removed $sourceJson"
|
||||
}
|
||||
|
||||
Remove-EmptyDirectory -Directory $qwenDir
|
||||
}
|
||||
|
||||
Write-Output "Qwen Code Standalone Uninstaller"
|
||||
Write-Output ""
|
||||
|
||||
$installBase = Get-QwenInstallBase
|
||||
$installDir = Get-QwenInstallDir
|
||||
$installBinDir = Get-QwenInstallBinDir
|
||||
$installWasManaged = Test-QwenStandaloneInstallDir -InstallDir $installDir
|
||||
|
||||
if ($installWasManaged) {
|
||||
Remove-CurrentCmdPathShim
|
||||
Remove-Item -LiteralPath $installDir -Recurse -Force
|
||||
Write-Success "Removed $installDir"
|
||||
} elseif (Test-Path -LiteralPath $installDir) {
|
||||
Write-WarningMessage "$installDir exists but is not a Qwen Code standalone install; skipping."
|
||||
} else {
|
||||
Write-Info "No standalone runtime found at $installDir."
|
||||
}
|
||||
|
||||
if ($installWasManaged) {
|
||||
Remove-InstallWrapper -InstallDir $installDir -BinDir $installBinDir
|
||||
} else {
|
||||
Write-Info "Leaving $(Join-Path $installBinDir 'qwen.cmd') unchanged because no managed standalone runtime was removed."
|
||||
}
|
||||
|
||||
Remove-UserPathEntry -BinDir $installBinDir
|
||||
Remove-SourceMarker
|
||||
if ([string]::IsNullOrEmpty($env:QWEN_INSTALL_BIN_DIR)) {
|
||||
Remove-EmptyDirectory -Directory $installBinDir
|
||||
}
|
||||
if ([string]::IsNullOrEmpty($env:QWEN_INSTALL_ROOT)) {
|
||||
Remove-EmptyDirectory -Directory $installBase
|
||||
}
|
||||
|
||||
Write-Success "Qwen Code standalone install removed."
|
||||
312
scripts/installation/uninstall-qwen-standalone.sh
Executable file
312
scripts/installation/uninstall-qwen-standalone.sh
Executable file
|
|
@ -0,0 +1,312 @@
|
|||
#!/usr/bin/env bash
|
||||
|
||||
# Qwen Code standalone uninstaller.
|
||||
# Removes files owned by install-qwen-standalone.sh and preserves user config.
|
||||
|
||||
if [ -z "${BASH_VERSION}" ] && [ -z "${__QWEN_UNINSTALL_REEXEC:-}" ]; then
|
||||
if command -v bash >/dev/null 2>&1; then
|
||||
if [ -f "${0}" ]; then
|
||||
export __QWEN_UNINSTALL_REEXEC=1
|
||||
exec bash -- "${0}" "$@"
|
||||
fi
|
||||
|
||||
echo "Error: This script requires bash. Run the uninstaller with: curl ... | bash"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Error: This script requires bash. Please install bash first."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
set -eo pipefail
|
||||
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m'
|
||||
|
||||
log_info() {
|
||||
printf '%bINFO:%b %s\n' "${BLUE}" "${NC}" "$1"
|
||||
}
|
||||
|
||||
log_success() {
|
||||
printf '%bSUCCESS:%b %s\n' "${GREEN}" "${NC}" "$1"
|
||||
}
|
||||
|
||||
log_warning() {
|
||||
printf '%bWARNING:%b %s\n' "${YELLOW}" "${NC}" "$1"
|
||||
}
|
||||
|
||||
log_error() {
|
||||
printf '%bERROR:%b %s\n' "${RED}" "${NC}" "$1" >&2
|
||||
}
|
||||
|
||||
print_usage() {
|
||||
cat <<EOF
|
||||
Qwen Code Standalone Uninstaller
|
||||
|
||||
Usage: $0 [OPTIONS]
|
||||
|
||||
Options:
|
||||
--purge Also remove the installer source marker at ~/.qwen/source.json.
|
||||
Other Qwen Code config and auth files are preserved.
|
||||
-h, --help Show this help message.
|
||||
|
||||
Environment:
|
||||
QWEN_INSTALL_ROOT Install root. Defaults to ~/.local.
|
||||
QWEN_INSTALL_LIB_DIR Standalone runtime directory.
|
||||
QWEN_INSTALL_BIN_DIR Wrapper directory.
|
||||
QWEN_UNINSTALL_PURGE=1 Same as --purge.
|
||||
EOF
|
||||
}
|
||||
|
||||
PURGE="${QWEN_UNINSTALL_PURGE:-0}"
|
||||
|
||||
if [[ -z "${HOME:-}" && -z "${QWEN_INSTALL_ROOT:-}" ]]; then
|
||||
log_error "HOME is not set. Set QWEN_INSTALL_ROOT to the standalone install root."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
INSTALL_ROOT="${QWEN_INSTALL_ROOT:-${HOME}/.local}"
|
||||
if [[ -n "${QWEN_INSTALL_LIB_DIR:-}" ]]; then
|
||||
INSTALL_LIB_DIR="${QWEN_INSTALL_LIB_DIR}"
|
||||
INSTALL_LIB_PARENT="$(dirname "${INSTALL_LIB_DIR}")"
|
||||
else
|
||||
INSTALL_LIB_PARENT="${QWEN_INSTALL_LIB_PARENT:-${INSTALL_ROOT}/lib}"
|
||||
INSTALL_LIB_DIR="${INSTALL_LIB_PARENT}/qwen-code"
|
||||
fi
|
||||
INSTALL_BIN_DIR="${QWEN_INSTALL_BIN_DIR:-${INSTALL_ROOT}/bin}"
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--purge)
|
||||
PURGE=1
|
||||
shift
|
||||
;;
|
||||
-h|--help)
|
||||
print_usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
log_error "Unknown option: $1"
|
||||
echo ""
|
||||
print_usage
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
validate_install_path() {
|
||||
local value="$1"
|
||||
local option_name="$2"
|
||||
|
||||
if [[ -z "${value}" ]]; then
|
||||
log_error "${option_name} must not be empty."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case "${value}" in
|
||||
*$'\n'*|*$'\r'*)
|
||||
log_error "${option_name} must not contain newlines."
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
if [[ "${value}" != /* ]]; then
|
||||
log_error "${option_name} must be an absolute path."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
validate_options() {
|
||||
validate_install_path "${INSTALL_ROOT}" "QWEN_INSTALL_ROOT"
|
||||
validate_install_path "${INSTALL_LIB_PARENT}" "QWEN_INSTALL_LIB_PARENT"
|
||||
validate_install_path "${INSTALL_LIB_DIR}" "QWEN_INSTALL_LIB_DIR"
|
||||
validate_install_path "${INSTALL_BIN_DIR}" "QWEN_INSTALL_BIN_DIR"
|
||||
}
|
||||
|
||||
is_qwen_standalone_install_dir() {
|
||||
local install_dir="$1"
|
||||
local manifest_path="${install_dir}/manifest.json"
|
||||
|
||||
[[ -d "${install_dir}" ]] || return 1
|
||||
[[ -f "${manifest_path}" ]] || return 1
|
||||
grep -Eq '"name"[[:space:]]*:[[:space:]]*"@qwen-code/qwen-code"' "${manifest_path}" 2>/dev/null || return 1
|
||||
grep -Eq '"target"[[:space:]]*:[[:space:]]*"(darwin|linux)-(arm64|x64)"' "${manifest_path}" 2>/dev/null || return 1
|
||||
[[ -f "${install_dir}/bin/qwen" && ! -L "${install_dir}/bin/qwen" && -x "${install_dir}/bin/qwen" ]] || return 1
|
||||
[[ -f "${install_dir}/node/bin/node" && ! -L "${install_dir}/node/bin/node" && -x "${install_dir}/node/bin/node" ]] || return 1
|
||||
}
|
||||
|
||||
shell_quote() {
|
||||
printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"
|
||||
}
|
||||
|
||||
remove_install_wrapper() {
|
||||
local wrapper_path="${INSTALL_BIN_DIR}/qwen"
|
||||
local qwen_bin="${INSTALL_LIB_DIR}/bin/qwen"
|
||||
|
||||
if [[ ! -e "${wrapper_path}" ]]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [[ ! -f "${wrapper_path}" || -L "${wrapper_path}" ]]; then
|
||||
log_warning "${wrapper_path} exists but is not an install-owned wrapper; skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# The installer writes the path through shell_quote, so the wrapper may
|
||||
# contain the raw path (no special chars) or the single-quoted form
|
||||
# (paths with spaces, quotes, or other shell metacharacters).
|
||||
local quoted_qwen_bin
|
||||
quoted_qwen_bin=$(shell_quote "${qwen_bin}")
|
||||
if ! grep -qF "${qwen_bin}" "${wrapper_path}" 2>/dev/null &&
|
||||
! grep -qF "${quoted_qwen_bin}" "${wrapper_path}" 2>/dev/null; then
|
||||
log_warning "${wrapper_path} does not point at this standalone install; skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Defense in depth: only delete files that look like the installer-generated
|
||||
# wrapper (shebang on first line). A user-authored script that happens to
|
||||
# mention the install path stays untouched.
|
||||
if ! head -n 1 "${wrapper_path}" 2>/dev/null | grep -q '^#!'; then
|
||||
log_warning "${wrapper_path} mentions this install but is not a shell wrapper; skipping."
|
||||
return 0
|
||||
fi
|
||||
|
||||
rm -f "${wrapper_path}"
|
||||
log_success "Removed ${wrapper_path}"
|
||||
}
|
||||
|
||||
remove_shell_path_entry() {
|
||||
local begin_marker="# Qwen Code PATH block begin"
|
||||
local end_marker="# Qwen Code PATH block end"
|
||||
local legacy_marker="# Added by qwen-code installer (multi-qwen shadow fix)"
|
||||
local rc_files=()
|
||||
local rc_file
|
||||
|
||||
[[ -n "${HOME:-}" ]] || return 0
|
||||
rc_files+=("${HOME}/.zshrc")
|
||||
rc_files+=("${HOME}/.bashrc")
|
||||
rc_files+=("${HOME}/.bash_profile")
|
||||
rc_files+=("${HOME}/.profile")
|
||||
rc_files+=("${HOME}/.config/fish/config.fish")
|
||||
|
||||
for rc_file in "${rc_files[@]}"; do
|
||||
[[ -f "${rc_file}" ]] || continue
|
||||
grep -qF "${begin_marker}" "${rc_file}" 2>/dev/null ||
|
||||
grep -qF "${legacy_marker}" "${rc_file}" 2>/dev/null ||
|
||||
continue
|
||||
|
||||
local temp_file
|
||||
temp_file=$(mktemp "${rc_file}.qwen-uninstall.XXXXXX") || {
|
||||
log_warning "Could not create temp file for ${rc_file}; leaving PATH entry unchanged."
|
||||
continue
|
||||
}
|
||||
|
||||
awk -v begin_marker="${begin_marker}" \
|
||||
-v end_marker="${end_marker}" \
|
||||
-v legacy_marker="${legacy_marker}" '
|
||||
function reset_block( i) {
|
||||
for (i = 1; i <= block_count; i++) {
|
||||
delete block[i]
|
||||
}
|
||||
block_count = 0
|
||||
in_block = 0
|
||||
}
|
||||
function flush_block( i) {
|
||||
for (i = 1; i <= block_count; i++) {
|
||||
print block[i]
|
||||
}
|
||||
reset_block()
|
||||
}
|
||||
index($0, begin_marker) {
|
||||
if (in_block) {
|
||||
flush_block()
|
||||
}
|
||||
in_block = 1
|
||||
block_count = 1
|
||||
block[block_count] = $0
|
||||
next
|
||||
}
|
||||
in_block {
|
||||
block_count++
|
||||
block[block_count] = $0
|
||||
if (index($0, end_marker)) {
|
||||
reset_block()
|
||||
}
|
||||
next
|
||||
}
|
||||
index($0, legacy_marker) { check_next = 1; next }
|
||||
check_next == 1 {
|
||||
check_next = 0
|
||||
if ($0 ~ /^[[:space:]]*export PATH=/ ||
|
||||
$0 ~ /^[[:space:]]*set -gx PATH /) {
|
||||
next
|
||||
}
|
||||
}
|
||||
{ print }
|
||||
END {
|
||||
if (in_block) {
|
||||
flush_block()
|
||||
}
|
||||
}
|
||||
' "${rc_file}" > "${temp_file}" && mv "${temp_file}" "${rc_file}" || {
|
||||
rm -f "${temp_file}"
|
||||
log_warning "Could not remove Qwen Code PATH entry from ${rc_file}."
|
||||
continue
|
||||
}
|
||||
|
||||
log_success "Removed Qwen Code PATH entry from ${rc_file}"
|
||||
done
|
||||
}
|
||||
|
||||
remove_empty_dir() {
|
||||
local dir="$1"
|
||||
|
||||
[[ -d "${dir}" ]] || return 0
|
||||
rmdir "${dir}" 2>/dev/null || true
|
||||
}
|
||||
|
||||
remove_source_marker() {
|
||||
local source_json="${HOME:-}/.qwen/source.json"
|
||||
|
||||
if [[ "${PURGE}" != "1" ]]; then
|
||||
log_info "Preserving ${HOME:-~}/.qwen (set QWEN_UNINSTALL_PURGE=1 to remove source.json)."
|
||||
return 0
|
||||
fi
|
||||
|
||||
[[ -n "${HOME:-}" ]] || return 0
|
||||
if [[ -f "${source_json}" ]]; then
|
||||
rm -f "${source_json}"
|
||||
log_success "Removed ${source_json}"
|
||||
fi
|
||||
remove_empty_dir "${HOME}/.qwen"
|
||||
}
|
||||
|
||||
validate_options
|
||||
|
||||
echo "Qwen Code Standalone Uninstaller"
|
||||
echo ""
|
||||
|
||||
install_was_managed=0
|
||||
if is_qwen_standalone_install_dir "${INSTALL_LIB_DIR}"; then
|
||||
install_was_managed=1
|
||||
rm -rf "${INSTALL_LIB_DIR}"
|
||||
log_success "Removed ${INSTALL_LIB_DIR}"
|
||||
elif [[ -e "${INSTALL_LIB_DIR}" ]]; then
|
||||
log_warning "${INSTALL_LIB_DIR} exists but is not a Qwen Code standalone install; skipping."
|
||||
else
|
||||
log_info "No standalone runtime found at ${INSTALL_LIB_DIR}."
|
||||
fi
|
||||
|
||||
if [[ "${install_was_managed}" == "1" ]]; then
|
||||
remove_install_wrapper
|
||||
else
|
||||
log_info "Leaving ${INSTALL_BIN_DIR}/qwen unchanged because no managed standalone runtime was removed."
|
||||
fi
|
||||
|
||||
remove_shell_path_entry
|
||||
remove_source_marker
|
||||
|
||||
log_success "Qwen Code standalone install removed."
|
||||
124
scripts/release-script-utils.js
Normal file
124
scripts/release-script-utils.js
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
/**
|
||||
* @license
|
||||
* Copyright 2026 Qwen Team
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
export function fail(message) {
|
||||
throw new Error(`ERROR: ${message}`);
|
||||
}
|
||||
|
||||
export async function sha256File(filePath) {
|
||||
const hash = crypto.createHash('sha256');
|
||||
await pipeline(fs.createReadStream(filePath), hash);
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a SHA256SUMS file. Handles:
|
||||
* - optional leading UTF-8 BOM (uploaded via Windows tools)
|
||||
* - binary-prefix markers (`*` before filename)
|
||||
* - empty lines and CRLF / LF line endings
|
||||
*/
|
||||
export function parseSha256Sums(content) {
|
||||
// Strip a leading UTF-8 BOM so a SHA256SUMS file uploaded via a Windows tool
|
||||
// that prepends one still reports a useful "Missing checksum entry" error
|
||||
// instead of "Malformed SHA256SUMS line 1".
|
||||
const normalized = content.replace(/^\uFEFF/, '');
|
||||
const checksums = new Map();
|
||||
for (const [index, line] of normalized.split(/\r?\n/).entries()) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const match = /^([0-9a-fA-F]{64})\s+\*?(.+)$/.exec(trimmed);
|
||||
if (!match) {
|
||||
fail(`Malformed SHA256SUMS line ${index + 1}: ${trimmed}`);
|
||||
}
|
||||
if (checksums.has(match[2])) {
|
||||
fail(`Duplicate SHA256SUMS entry for: ${match[2]}`);
|
||||
}
|
||||
checksums.set(match[2], match[1].toLowerCase());
|
||||
}
|
||||
return checksums;
|
||||
}
|
||||
|
||||
export function readOptionValue(argv, index, optionName) {
|
||||
const value = argv[index + 1];
|
||||
if (!value || value.startsWith('-')) {
|
||||
fail(`${optionName} requires a value`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function isMainModule(importMetaUrl) {
|
||||
const filename = fileURLToPath(importMetaUrl);
|
||||
return process.argv[1] && path.resolve(process.argv[1]) === filename;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse CLI arguments. Supports:
|
||||
* - --flag → args[def.key] = true
|
||||
* - --key value → args[def.key] = value
|
||||
* - --key=value → args[def.key] = value
|
||||
* - -h, --help → args.help = true (always recognised)
|
||||
*
|
||||
* @param {string[]} argv
|
||||
* @param {Record<string, {key: string, type: 'flag'|'value'}>} definitions
|
||||
* @returns {{help: false} & Record<string, any>}
|
||||
*/
|
||||
export function parseArgs(argv, definitions) {
|
||||
const args = { help: false };
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const raw = argv[index];
|
||||
if (raw === '--help' || raw === '-h') {
|
||||
args.help = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// --key=value form
|
||||
const eqIndex = raw.indexOf('=');
|
||||
if (eqIndex >= 0) {
|
||||
const key = raw.slice(0, eqIndex);
|
||||
const value = raw.slice(eqIndex + 1);
|
||||
if (key === '--help' || key === '-h') {
|
||||
fail(`${key} does not accept a value`);
|
||||
}
|
||||
const def = definitions[key];
|
||||
if (!def) {
|
||||
fail(`Unknown option: ${key}`);
|
||||
}
|
||||
if (def.type === 'flag') {
|
||||
fail(`${key} does not accept a value`);
|
||||
}
|
||||
if (!value || value.startsWith('-')) {
|
||||
fail(`${key} requires a value`);
|
||||
}
|
||||
args[def.key] = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
const def = definitions[raw];
|
||||
if (!def) {
|
||||
fail(`Unknown option: ${raw}`);
|
||||
}
|
||||
|
||||
if (def.type === 'flag') {
|
||||
args[def.key] = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
args[def.key] = readOptionValue(argv, index, raw);
|
||||
index += 1;
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
175
scripts/tests/upload-aliyun-oss-assets.test.js
Normal file
175
scripts/tests/upload-aliyun-oss-assets.test.js
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
/**
|
||||
* @license
|
||||
* Copyright 2026 Qwen Team
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { parseUploadArgs, uploadAssets } from '../upload-aliyun-oss-assets.js';
|
||||
|
||||
describe('parseUploadArgs', () => {
|
||||
it('returns help=true and skips later validation when --help is passed', () => {
|
||||
const args = parseUploadArgs(['--help']);
|
||||
expect(args.help).toBe(true);
|
||||
// Other fields stay at their defaults; no fail() is thrown.
|
||||
expect(args.assets).toEqual([]);
|
||||
});
|
||||
|
||||
it('parses required options and asset list', () => {
|
||||
const args = parseUploadArgs([
|
||||
'--bucket',
|
||||
'my-bucket',
|
||||
'--config',
|
||||
'/tmp/.ossutilconfig',
|
||||
'--prefix',
|
||||
'releases/qwen-code/v1.2.3',
|
||||
'a.tar.gz',
|
||||
'b.zip',
|
||||
]);
|
||||
expect(args).toMatchObject({
|
||||
bucket: 'my-bucket',
|
||||
config: '/tmp/.ossutilconfig',
|
||||
prefix: 'releases/qwen-code/v1.2.3',
|
||||
assets: ['a.tar.gz', 'b.zip'],
|
||||
help: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('strips a trailing slash from --prefix', () => {
|
||||
const args = parseUploadArgs([
|
||||
'--bucket',
|
||||
'b',
|
||||
'--config',
|
||||
'c',
|
||||
'--prefix',
|
||||
'installation/',
|
||||
'one.txt',
|
||||
]);
|
||||
expect(args.prefix).toBe('installation');
|
||||
});
|
||||
|
||||
it.each([
|
||||
[['--bucket', 'b', '--config', 'c', 'asset.txt'], '--prefix'],
|
||||
[['--config', 'c', '--prefix', 'p', 'asset.txt'], '--bucket'],
|
||||
[['--bucket', 'b', '--prefix', 'p', 'asset.txt'], '--config'],
|
||||
[['--bucket', 'b', '--config', 'c', '--prefix', 'p'], 'ASSET path'],
|
||||
])('rejects when %j is missing', (argv, expectedFragment) => {
|
||||
expect(() => parseUploadArgs(argv)).toThrow(
|
||||
new RegExp(expectedFragment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')),
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects unknown options', () => {
|
||||
expect(() =>
|
||||
parseUploadArgs([
|
||||
'--bucket',
|
||||
'b',
|
||||
'--config',
|
||||
'c',
|
||||
'--prefix',
|
||||
'p',
|
||||
'--bogus',
|
||||
'asset.txt',
|
||||
]),
|
||||
).toThrow(/Unknown option: --bogus/);
|
||||
});
|
||||
|
||||
it('errors when an option is missing its value', () => {
|
||||
expect(() => parseUploadArgs(['--bucket'])).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('uploadAssets (integration)', () => {
|
||||
function makeOssutilShim(workDir, behavior = 'success') {
|
||||
fs.mkdirSync(workDir, { recursive: true });
|
||||
const ossutilPath = path.join(workDir, 'ossutil-shim.cjs');
|
||||
const logPath = path.join(workDir, 'ossutil.log');
|
||||
fs.writeFileSync(
|
||||
ossutilPath,
|
||||
[
|
||||
"const fs = require('node:fs');",
|
||||
`fs.appendFileSync(${JSON.stringify(logPath)}, process.argv.slice(2).join('\\n') + '\\n');`,
|
||||
`process.exit(${behavior === 'fail' ? 1 : 0});`,
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
return {
|
||||
logPath,
|
||||
ossutilCommand: process.execPath,
|
||||
ossutilCommandArgs: [ossutilPath],
|
||||
};
|
||||
}
|
||||
|
||||
it('spawns ossutil with the expected cp arguments per asset', async () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'qwen-upload-'));
|
||||
try {
|
||||
const { logPath, ossutilCommand, ossutilCommandArgs } =
|
||||
makeOssutilShim(tmp);
|
||||
const assets = ['a.tar.gz', 'b.zip'].map((name) => {
|
||||
const filePath = path.join(tmp, name);
|
||||
fs.writeFileSync(filePath, name);
|
||||
return filePath;
|
||||
});
|
||||
const configPath = path.join(tmp, '.ossutilconfig');
|
||||
fs.writeFileSync(configPath, '[Credentials]\n');
|
||||
|
||||
uploadAssets(
|
||||
{
|
||||
assets,
|
||||
bucket: 'qwen-test-bucket',
|
||||
config: configPath,
|
||||
prefix: 'releases/qwen-code/v0.0.0',
|
||||
},
|
||||
{ ossutilCommand, ossutilCommandArgs },
|
||||
);
|
||||
|
||||
const log = fs.readFileSync(logPath, 'utf8');
|
||||
expect(log).toContain(
|
||||
`oss://qwen-test-bucket/releases/qwen-code/v0.0.0/a.tar.gz`,
|
||||
);
|
||||
expect(log).toContain(
|
||||
`oss://qwen-test-bucket/releases/qwen-code/v0.0.0/b.zip`,
|
||||
);
|
||||
expect(log).toContain(`-c\n${configPath}`);
|
||||
expect(log).toContain('--acl\npublic-read');
|
||||
} finally {
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('aggregates failures from ossutil non-zero exits', async () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'qwen-upload-fail-'));
|
||||
try {
|
||||
const { logPath, ossutilCommand, ossutilCommandArgs } = makeOssutilShim(
|
||||
tmp,
|
||||
'fail',
|
||||
);
|
||||
const assetPath = path.join(tmp, 'asset.tar.gz');
|
||||
fs.writeFileSync(assetPath, 'asset');
|
||||
const configPath = path.join(tmp, '.ossutilconfig');
|
||||
fs.writeFileSync(configPath, '[Credentials]\n');
|
||||
|
||||
expect(() =>
|
||||
uploadAssets(
|
||||
{
|
||||
assets: [assetPath],
|
||||
bucket: 'qwen-test-bucket',
|
||||
config: configPath,
|
||||
prefix: 'releases/qwen-code/v0.0.0',
|
||||
},
|
||||
{ ossutilCommand, ossutilCommandArgs },
|
||||
),
|
||||
).toThrow(/ossutil failed after 3 attempts/);
|
||||
const uploadAttempts = fs
|
||||
.readFileSync(logPath, 'utf8')
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => line === assetPath);
|
||||
expect(uploadAttempts).toHaveLength(3);
|
||||
} finally {
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_000);
|
||||
});
|
||||
164
scripts/upload-aliyun-oss-assets.js
Normal file
164
scripts/upload-aliyun-oss-assets.js
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Qwen Team
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { fail, isMainModule, readOptionValue } from './release-script-utils.js';
|
||||
|
||||
if (isMainModule(import.meta.url)) {
|
||||
try {
|
||||
main(process.argv.slice(2));
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : error);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
function main(argv) {
|
||||
const args = parseUploadArgs(argv);
|
||||
if (args.help) {
|
||||
printUsage();
|
||||
return;
|
||||
}
|
||||
uploadAssets(args);
|
||||
}
|
||||
|
||||
function printUsage() {
|
||||
console.log(`Usage: node scripts/upload-aliyun-oss-assets.js [options] ASSET...
|
||||
|
||||
Uploads local release assets to a public Aliyun OSS prefix via ossutil.
|
||||
|
||||
Options:
|
||||
--bucket NAME OSS bucket name.
|
||||
--config PATH ossutil config path.
|
||||
--prefix PREFIX Destination object prefix.
|
||||
-h, --help Show this help message.
|
||||
`);
|
||||
}
|
||||
|
||||
function parseUploadArgs(argv) {
|
||||
const args = {
|
||||
assets: [],
|
||||
bucket: '',
|
||||
config: '',
|
||||
help: false,
|
||||
prefix: '',
|
||||
};
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index];
|
||||
if (arg === '--help' || arg === '-h') {
|
||||
args.help = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--bucket') {
|
||||
args.bucket = readOptionValue(argv, index, arg);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--config') {
|
||||
args.config = readOptionValue(argv, index, arg);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--prefix') {
|
||||
args.prefix = readOptionValue(argv, index, arg).replace(/\/+$/, '');
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('-')) {
|
||||
fail(`Unknown option: ${arg}`);
|
||||
}
|
||||
args.assets.push(arg);
|
||||
}
|
||||
|
||||
if (args.help) {
|
||||
return args;
|
||||
}
|
||||
if (!args.bucket) {
|
||||
fail('--bucket requires a value');
|
||||
}
|
||||
if (!args.config) {
|
||||
fail('--config requires a value');
|
||||
}
|
||||
if (!args.prefix) {
|
||||
fail('--prefix requires a value');
|
||||
}
|
||||
if (args.assets.length === 0) {
|
||||
fail('At least one ASSET path is required');
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
|
||||
const MAX_UPLOAD_ATTEMPTS = 3;
|
||||
const INITIAL_BACKOFF_MS = 2000;
|
||||
|
||||
function uploadAssets(
|
||||
{ assets, bucket, config, prefix },
|
||||
{ ossutilCommand = 'ossutil', ossutilCommandArgs = [] } = {},
|
||||
) {
|
||||
for (const asset of assets) {
|
||||
const key = `${prefix}/${path.basename(asset)}`;
|
||||
uploadWithRetry(asset, bucket, key, config, {
|
||||
ossutilCommand,
|
||||
ossutilCommandArgs,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function uploadWithRetry(
|
||||
asset,
|
||||
bucket,
|
||||
key,
|
||||
config,
|
||||
{ ossutilCommand, ossutilCommandArgs },
|
||||
) {
|
||||
for (let attempt = 1; attempt <= MAX_UPLOAD_ATTEMPTS; attempt += 1) {
|
||||
const result = spawnSync(
|
||||
ossutilCommand,
|
||||
[
|
||||
...ossutilCommandArgs,
|
||||
'cp',
|
||||
asset,
|
||||
`oss://${bucket}/${key}`,
|
||||
'-c',
|
||||
config,
|
||||
'-f',
|
||||
'--acl',
|
||||
'public-read',
|
||||
],
|
||||
{ stdio: 'inherit' },
|
||||
);
|
||||
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
if (result.status === 0) {
|
||||
return;
|
||||
}
|
||||
if (attempt < MAX_UPLOAD_ATTEMPTS) {
|
||||
const delayMs = INITIAL_BACKOFF_MS * 2 ** (attempt - 1);
|
||||
console.warn(
|
||||
`Upload attempt ${attempt}/${MAX_UPLOAD_ATTEMPTS} failed for ${path.basename(asset)}, retrying in ${delayMs / 1000}s...`,
|
||||
);
|
||||
sleepSync(delayMs);
|
||||
}
|
||||
}
|
||||
fail(
|
||||
`ossutil failed after ${MAX_UPLOAD_ATTEMPTS} attempts while uploading ${asset}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Cross-platform synchronous sleep. `spawnSync('sleep', ...)` is unavailable
|
||||
// on Windows runners; Atomics.wait blocks the current thread without spawning.
|
||||
function sleepSync(ms) {
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
||||
}
|
||||
|
||||
export { parseUploadArgs, uploadAssets };
|
||||
304
scripts/verify-installation-release.js
Normal file
304
scripts/verify-installation-release.js
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Qwen Team
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Readable } from 'node:stream';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { RELEASE_TARGETS } from './build-standalone-release.js';
|
||||
import {
|
||||
fail,
|
||||
isMainModule,
|
||||
parseArgs,
|
||||
parseSha256Sums,
|
||||
sha256File,
|
||||
} from './release-script-utils.js';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const rootDir = path.resolve(__dirname, '..');
|
||||
|
||||
const EXPECTED_STANDALONE_ARCHIVE_NAMES =
|
||||
standaloneArchiveNamesFromReleaseTargets(RELEASE_TARGETS);
|
||||
// Release artifacts that the installer chain expects in a GitHub Release.
|
||||
// Hosted installer scripts are served from a separate endpoint and are
|
||||
// intentionally not part of this set; they have their own staging path in
|
||||
// `package:hosted-installation`.
|
||||
const EXPECTED_RELEASE_ASSET_NAMES = [
|
||||
...EXPECTED_STANDALONE_ARCHIVE_NAMES,
|
||||
'SHA256SUMS',
|
||||
];
|
||||
const REMOTE_FETCH_TIMEOUT_MS = 30_000;
|
||||
|
||||
// Mirrors `build-standalone-release.js`'s archive-name derivation. The two
|
||||
// must stay aligned: any new platform/extension landing in RELEASE_TARGETS
|
||||
// has to be reflected here (and there) before a new target ships, otherwise
|
||||
// the verify and the build will disagree on expected filenames.
|
||||
function standaloneArchiveNamesFromReleaseTargets(releaseTargets) {
|
||||
return releaseTargets.map(
|
||||
({ qwenTarget }) =>
|
||||
`qwen-code-${qwenTarget}.${qwenTarget === 'win-x64' ? 'zip' : 'tar.gz'}`,
|
||||
);
|
||||
}
|
||||
|
||||
const ARG_DEFS = {
|
||||
'--dir': { key: 'dir', type: 'value' },
|
||||
'--base-url': { key: 'baseUrl', type: 'value' },
|
||||
'--list-release-asset-paths': {
|
||||
key: 'listReleaseAssetPaths',
|
||||
type: 'flag',
|
||||
},
|
||||
};
|
||||
|
||||
if (isMainModule(import.meta.url)) {
|
||||
try {
|
||||
await main();
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : error);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv.slice(2), ARG_DEFS);
|
||||
if (args.help) {
|
||||
printUsage();
|
||||
return;
|
||||
}
|
||||
if (args.dir && args.baseUrl) {
|
||||
fail('Pass --dir or --base-url, not both.');
|
||||
}
|
||||
if (args.listReleaseAssetPaths && args.baseUrl) {
|
||||
fail('Pass --list-release-asset-paths with --dir, not --base-url.');
|
||||
}
|
||||
if (args.listReleaseAssetPaths) {
|
||||
const dir = path.resolve(
|
||||
args.dir || path.join(rootDir, 'dist', 'standalone'),
|
||||
);
|
||||
await verifyReleaseDirectory(dir, { silent: true });
|
||||
for (const assetPath of releaseAssetPaths(dir)) {
|
||||
console.log(assetPath);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (args.baseUrl) {
|
||||
await verifyReleaseBaseUrl(args.baseUrl);
|
||||
return;
|
||||
}
|
||||
await verifyReleaseDirectory(
|
||||
path.resolve(args.dir || path.join(rootDir, 'dist', 'standalone')),
|
||||
);
|
||||
}
|
||||
|
||||
function printUsage() {
|
||||
console.log(`Usage: npm run verify:installation-release -- [options]
|
||||
|
||||
Verifies that an installation release directory contains the expected standalone
|
||||
archives with matching SHA256SUMS entries. For a release URL, downloads
|
||||
SHA256SUMS and the expected archives, then verifies each archive hash.
|
||||
|
||||
Options:
|
||||
--dir PATH Verify a local release directory. Defaults to dist/standalone.
|
||||
--base-url URL Verify a remote release URL (e.g. a GitHub release download
|
||||
prefix). Cannot be combined with --dir.
|
||||
--list-release-asset-paths
|
||||
Verify --dir, then print explicit asset paths for upload.
|
||||
-h, --help Show this help message.
|
||||
`);
|
||||
}
|
||||
|
||||
async function verifyReleaseDirectory(dir, options = {}) {
|
||||
const { silent = false } = options;
|
||||
const checksums = readReleaseChecksums(dir);
|
||||
assertExpectedChecksumEntries(checksums);
|
||||
assertExpectedArchiveFiles(dir);
|
||||
|
||||
for (const assetName of EXPECTED_STANDALONE_ARCHIVE_NAMES) {
|
||||
const assetPath = path.join(dir, assetName);
|
||||
if (!fs.existsSync(assetPath)) {
|
||||
fail(`Missing release asset: ${assetName}`);
|
||||
}
|
||||
|
||||
const actual = await sha256File(assetPath);
|
||||
const expected = checksums.get(assetName);
|
||||
if (actual !== expected) {
|
||||
fail(
|
||||
`Checksum mismatch for ${assetName}: expected ${expected}, got ${actual}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!silent) {
|
||||
console.log(
|
||||
`Verified ${EXPECTED_RELEASE_ASSET_NAMES.length} installation release assets in ${dir}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function verifyReleaseBaseUrl(baseUrl, options = {}) {
|
||||
const { fetchImpl = fetch } = options;
|
||||
const normalizedBaseUrl = normalizeHttpsBaseUrl(baseUrl);
|
||||
const checksumUrl = new URL('SHA256SUMS', normalizedBaseUrl).toString();
|
||||
const checksums = parseSha256Sums(await fetchText(checksumUrl, fetchImpl));
|
||||
assertExpectedChecksumEntries(checksums);
|
||||
|
||||
await assertRemoteAssetChecksums(normalizedBaseUrl, checksums, fetchImpl);
|
||||
|
||||
console.log(
|
||||
`Verified ${EXPECTED_RELEASE_ASSET_NAMES.length} installation release assets at ${baseUrl}`,
|
||||
);
|
||||
}
|
||||
|
||||
function readReleaseChecksums(dir) {
|
||||
const checksumPath = path.join(dir, 'SHA256SUMS');
|
||||
if (!fs.existsSync(checksumPath)) {
|
||||
fail(`SHA256SUMS was not found at ${checksumPath}`);
|
||||
}
|
||||
|
||||
return parseSha256Sums(fs.readFileSync(checksumPath, 'utf8'));
|
||||
}
|
||||
|
||||
function assertExpectedChecksumEntries(checksums) {
|
||||
const expected = new Set(EXPECTED_STANDALONE_ARCHIVE_NAMES);
|
||||
const missing = EXPECTED_STANDALONE_ARCHIVE_NAMES.filter(
|
||||
(assetName) => !checksums.has(assetName),
|
||||
);
|
||||
const extra = Array.from(checksums.keys()).filter(
|
||||
(assetName) => !expected.has(assetName),
|
||||
);
|
||||
|
||||
if (missing.length > 0) {
|
||||
fail(`Missing release asset checksum: ${missing.join(', ')}`);
|
||||
}
|
||||
if (extra.length > 0) {
|
||||
fail(`Unexpected release asset checksum: ${extra.join(', ')}`);
|
||||
}
|
||||
}
|
||||
|
||||
function assertExpectedArchiveFiles(dir) {
|
||||
const expected = new Set(EXPECTED_RELEASE_ASSET_NAMES);
|
||||
const extra = fs
|
||||
.readdirSync(dir)
|
||||
.filter((assetName) => !expected.has(assetName))
|
||||
.sort();
|
||||
|
||||
if (extra.length > 0) {
|
||||
fail(`Unexpected release asset: ${extra.join(', ')}`);
|
||||
}
|
||||
}
|
||||
|
||||
function releaseAssetPaths(dir) {
|
||||
return EXPECTED_RELEASE_ASSET_NAMES.map((assetName) =>
|
||||
path.join(dir, assetName),
|
||||
);
|
||||
}
|
||||
|
||||
async function assertRemoteAssetChecksums(
|
||||
normalizedBaseUrl,
|
||||
checksums,
|
||||
fetchImpl,
|
||||
) {
|
||||
const failures = [];
|
||||
for (const assetName of EXPECTED_STANDALONE_ARCHIVE_NAMES) {
|
||||
try {
|
||||
const assetUrl = new URL(assetName, normalizedBaseUrl).toString();
|
||||
const actual = await fetchSha256(assetUrl, fetchImpl);
|
||||
const expected = checksums.get(assetName);
|
||||
if (actual !== expected) {
|
||||
fail(
|
||||
`Checksum mismatch for ${assetName}: expected ${expected}, got ${actual}`,
|
||||
);
|
||||
}
|
||||
} catch (reason) {
|
||||
failures.push({
|
||||
assetName,
|
||||
reason: formatErrorReason(reason),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (failures.length === 0) {
|
||||
return;
|
||||
}
|
||||
if (failures.length === EXPECTED_STANDALONE_ARCHIVE_NAMES.length) {
|
||||
fail(
|
||||
`All ${failures.length} release asset URLs are unavailable; check --base-url: ${normalizedBaseUrl}`,
|
||||
);
|
||||
}
|
||||
fail(
|
||||
`Unavailable or invalid release asset(s): ${failures
|
||||
.map(({ assetName, reason }) => `${assetName} (${reason})`)
|
||||
.join('; ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
async function fetchSha256(url, fetchImpl) {
|
||||
const response = await fetchWithTimeout(fetchImpl, url);
|
||||
if (!response.ok) {
|
||||
fail(
|
||||
`Failed to download ${url}: ${response.status} ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
if (!response.body) {
|
||||
fail(`Downloaded response has no body: ${url}`);
|
||||
}
|
||||
|
||||
const hash = crypto.createHash('sha256');
|
||||
await pipeline(Readable.fromWeb(response.body), hash);
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
function formatErrorReason(reason) {
|
||||
if (reason instanceof Error) {
|
||||
return reason.message.replace(/^ERROR:\s*/, '');
|
||||
}
|
||||
return String(reason);
|
||||
}
|
||||
|
||||
async function fetchText(url, fetchImpl) {
|
||||
const response = await fetchWithTimeout(fetchImpl, url);
|
||||
if (!response.ok) {
|
||||
fail(
|
||||
`Failed to download ${url}: ${response.status} ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
return response.text();
|
||||
}
|
||||
|
||||
function fetchWithTimeout(fetchImpl, url, options = {}) {
|
||||
return fetchImpl(url, {
|
||||
...options,
|
||||
signal: AbortSignal.timeout(REMOTE_FETCH_TIMEOUT_MS),
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeHttpsBaseUrl(baseUrl) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(baseUrl);
|
||||
} catch {
|
||||
fail(`--base-url must be a valid URL: ${baseUrl}`);
|
||||
}
|
||||
if (parsed.protocol !== 'https:') {
|
||||
fail(`--base-url must use https: ${baseUrl}`);
|
||||
}
|
||||
if (!parsed.pathname.endsWith('/')) {
|
||||
parsed.pathname = `${parsed.pathname}/`;
|
||||
}
|
||||
return parsed.toString();
|
||||
}
|
||||
|
||||
export {
|
||||
EXPECTED_STANDALONE_ARCHIVE_NAMES,
|
||||
EXPECTED_RELEASE_ASSET_NAMES,
|
||||
releaseAssetPaths,
|
||||
verifyReleaseBaseUrl,
|
||||
verifyReleaseDirectory,
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue