@ihason/rust-portable-win32-x64 1.99.1 → 1.100.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,24 +1,33 @@
1
1
  # @ihason/rust-portable-win32-x64
2
2
 
3
- Portable Rust 1.99.1 toolchain for Windows 10/11 x64.
3
+ Portable Rust 1.100.1 toolchain for Windows x64.
4
4
 
5
- This package does not download anything from the network. It joins the data
6
- chunks installed from npm, verifies the SHA256 of the archive, and extracts it
7
- to `%LOCALAPPDATA%\rust-portable\1.99.1`. Override the location with
8
- `RUST_PORTABLE_HOME`; the path must not contain spaces.
5
+ Release 1.100.1.
9
6
 
10
- After installation:
7
+ Install the entry package and run the setup command:
11
8
 
12
- 1. Run `<install dir>\windows\configure-env.bat`.
13
- 2. Open a new terminal.
14
- 3. Run `<install dir>\windows\doctor.bat`.
9
+ ```bash
10
+ npx @ihason/rust-portable setup
11
+ ```
15
12
 
16
- If the `postinstall` script was skipped (for example with `--ignore-scripts`),
17
- run the installer manually:
13
+ The setup command is interactive. It asks for the install location, PATH
14
+ configuration and self-check. Press Enter to accept the recommended values.
18
15
 
19
- ```powershell
20
- node node_modules/@ihason/rust-portable-win32-x64/install.js
21
- ```
16
+ All data comes from the npm chunk packages. Setup does not use GitHub.
17
+
18
+ This platform package does not download anything from the network. It joins
19
+ the data chunks, verifies the SHA256, and extracts the archive.
20
+
21
+ After setup:
22
+
23
+ 1. Run `configure-env.bat` in the extracted `windows` directory.
24
+ 2. Open a new terminal.
25
+ 3. Run `doctor.bat` in the extracted `windows` directory.
26
+
27
+ If you run `npm install` instead, the postinstall script extracts the bundle
28
+ to `rust-portable` in the directory where npm was run. Run `install.sh` on
29
+ Linux after extraction.
22
30
 
23
31
  The bundle contains third-party toolchains with their own licenses. See
24
32
  `shared/licenses/` and `shared/THIRD-PARTY-NOTICES.md` in the installed bundle.
33
+ Documentation: <https://github.com/HasonHuang/rust-portable/blob/main/docs/NPM.md>
package/archive.json CHANGED
@@ -1,7 +1,12 @@
1
1
  {
2
- "zip": "rust-portable-v1.99.1-windows-x64.zip",
3
- "size": 611000377,
4
- "sha256": "4919731198a63585d6f50ac5e8c2a6c48cc62b1cc80bf3b267e4cad2c1375b83",
2
+ "platform": "win32-x64",
3
+ "asset": "rust-portable-v1.100.1-windows-x64.zip",
4
+ "type": "zip",
5
+ "bundleVersion": "1.100.1",
6
+ "bundleRevision": "",
7
+ "releaseVersion": "1.100.1",
8
+ "size": 610692980,
9
+ "sha256": "7ce522c97789d1a52c15821a8643866dd64c64d3bc878dc3d076f6c33f8888c2",
5
10
  "parts": [
6
11
  {
7
12
  "package": "@ihason/rust-portable-win32-x64-chunk-01",
@@ -31,7 +36,7 @@
31
36
  {
32
37
  "package": "@ihason/rust-portable-win32-x64-chunk-06",
33
38
  "file": "part06",
34
- "bytes": 86712377
39
+ "bytes": 86404980
35
40
  }
36
41
  ]
37
42
  }
package/extract.js ADDED
@@ -0,0 +1,248 @@
1
+ 'use strict';
2
+
3
+ // Shared helpers for npm platform packages.
4
+ // The helpers join the data chunks, verify the archive, and extract it.
5
+
6
+ const fs = require('node:fs');
7
+ const os = require('node:os');
8
+ const path = require('node:path');
9
+ const crypto = require('node:crypto');
10
+ const { spawnSync } = require('node:child_process');
11
+ const { createRequire } = require('node:module');
12
+
13
+ const requireFromHere = createRequire(__filename);
14
+ const BUFFER_SIZE = 1024 * 1024;
15
+
16
+ function fail(message) {
17
+ const error = new Error(message);
18
+ error.rustPortable = true;
19
+ throw error;
20
+ }
21
+
22
+ function partPath(part) {
23
+ const packageJson = requireFromHere.resolve(`${part.package}/package.json`);
24
+ return path.join(path.dirname(packageJson), part.file);
25
+ }
26
+
27
+ function joinArchive(archive, destination) {
28
+ const hash = crypto.createHash('sha256');
29
+ const buffer = Buffer.allocUnsafe(BUFFER_SIZE);
30
+ const out = fs.openSync(destination, 'w');
31
+ let written = 0;
32
+
33
+ try {
34
+ for (const part of archive.parts) {
35
+ const source = partPath(part);
36
+ const stat = fs.statSync(source);
37
+ if (stat.size !== part.bytes) {
38
+ fail(`Chunk size mismatch for ${source}: expected ${part.bytes}, got ${stat.size}`);
39
+ }
40
+
41
+ const input = fs.openSync(source, 'r');
42
+ let remaining = part.bytes;
43
+ try {
44
+ while (remaining > 0) {
45
+ const want = Math.min(buffer.length, remaining);
46
+ const read = fs.readSync(input, buffer, 0, want, null);
47
+ if (read <= 0) {
48
+ fail(`Unexpected end of ${source}`);
49
+ }
50
+ hash.update(buffer.subarray(0, read));
51
+ fs.writeSync(out, buffer, 0, read);
52
+ written += read;
53
+ remaining -= read;
54
+ }
55
+ } finally {
56
+ fs.closeSync(input);
57
+ }
58
+ }
59
+ } finally {
60
+ fs.closeSync(out);
61
+ }
62
+
63
+ const actual = hash.digest('hex');
64
+ if (written !== archive.size) {
65
+ fail(`Archive size mismatch: expected ${archive.size}, got ${written}`);
66
+ }
67
+ if (actual !== archive.sha256.toLowerCase()) {
68
+ fail(`Archive SHA256 mismatch: expected ${archive.sha256}, got ${actual}`);
69
+ }
70
+ }
71
+
72
+ function tarCommand() {
73
+ if (process.platform !== 'win32') {
74
+ return 'tar';
75
+ }
76
+ const candidate = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe');
77
+ if (!fs.existsSync(candidate)) {
78
+ fail(`Windows tar.exe was not found at ${candidate}. Windows 10 1803 or newer is required.`);
79
+ }
80
+ return candidate;
81
+ }
82
+
83
+ function extractArchive(archivePath, type, destination) {
84
+ fs.mkdirSync(destination, { recursive: true });
85
+ const args = type === 'zip'
86
+ ? ['-xf', archivePath, '-C', destination, '--strip-components=1']
87
+ : ['-xzf', archivePath, '-C', destination, '--strip-components=1'];
88
+ const result = spawnSync(tarCommand(), args, { stdio: 'inherit' });
89
+ if (result.error) {
90
+ fail(`Cannot run tar: ${result.error.message}`);
91
+ }
92
+ if (result.status !== 0) {
93
+ fail(`tar failed with exit code ${result.status}`);
94
+ }
95
+ }
96
+
97
+ function verifyBundle(directory, platform) {
98
+ if (platform === 'win32-x64') {
99
+ for (const relative of ['windows/configure-env.bat', 'windows/doctor.bat']) {
100
+ if (!fs.existsSync(path.join(directory, relative))) {
101
+ fail(`The archive is missing ${relative}.`);
102
+ }
103
+ }
104
+ return;
105
+ }
106
+ if (platform === 'linux-x64' || platform === 'linux-arm64') {
107
+ if (!fs.existsSync(path.join(directory, 'linux', 'install.sh'))) {
108
+ fail('The archive is missing linux/install.sh.');
109
+ }
110
+ return;
111
+ }
112
+ fail(`Unsupported platform: ${platform}`);
113
+ }
114
+
115
+ function archiveExtension(type) {
116
+ return type === 'zip' ? 'zip' : 'tar.gz';
117
+ }
118
+
119
+ function extractBundle(archive, destination) {
120
+ const parent = path.dirname(destination);
121
+ fs.mkdirSync(parent, { recursive: true });
122
+ const suffix = `${process.pid}-${Date.now()}`;
123
+ const temporaryArchive = path.join(
124
+ os.tmpdir(),
125
+ `rust-portable-${archive.platform}-${suffix}.${archiveExtension(archive.type)}`
126
+ );
127
+ const staging = path.join(parent, `.staging-${archive.platform}-${suffix}`);
128
+
129
+ fs.rmSync(staging, { recursive: true, force: true });
130
+ fs.mkdirSync(staging, { recursive: true });
131
+
132
+ try {
133
+ joinArchive(archive, temporaryArchive);
134
+ extractArchive(temporaryArchive, archive.type, staging);
135
+ verifyBundle(staging, archive.platform);
136
+ return staging;
137
+ } catch (error) {
138
+ fs.rmSync(staging, { recursive: true, force: true });
139
+ throw error;
140
+ } finally {
141
+ fs.rmSync(temporaryArchive, { force: true });
142
+ }
143
+ }
144
+
145
+ function readText(file) {
146
+ try {
147
+ return fs.readFileSync(file, 'utf8');
148
+ } catch {
149
+ return '';
150
+ }
151
+ }
152
+
153
+ function readRelease(directory) {
154
+ const rustVersion = readText(path.join(directory, 'RUST_VERSION')).trim()
155
+ || readText(path.join(directory, 'VERSION')).trim();
156
+ const releaseVersion = readText(path.join(directory, 'RELEASE_VERSION')).trim();
157
+ const buildInfo = readText(path.join(directory, 'BUILD-INFO.txt'));
158
+ const match = /^Bundle revision:[ \t]*(\S+)[ \t]*$/m.exec(buildInfo);
159
+ let revision = match && match[1] !== 'none' ? match[1] : '';
160
+ if (!revision) {
161
+ const revisionMatch = /-r(\d+)$/.exec(releaseVersion);
162
+ if (revisionMatch) {
163
+ revision = `r${revisionMatch[1]}`;
164
+ }
165
+ }
166
+ return {
167
+ version: releaseVersion || rustVersion,
168
+ rustVersion,
169
+ releaseVersion,
170
+ revision
171
+ };
172
+ }
173
+
174
+ function installedInfo(directory, platform) {
175
+ if (platform === 'win32-x64') {
176
+ return readRelease(directory);
177
+ }
178
+ const root = path.join(directory, 'share', 'rust-portable');
179
+ return readRelease(root);
180
+ }
181
+
182
+ function bundleInfo(directory) {
183
+ return readRelease(directory);
184
+ }
185
+
186
+ function isComplete(directory, platform) {
187
+ if (platform === 'win32-x64') {
188
+ return fs.existsSync(path.join(directory, 'windows', 'cargo', 'bin', 'cargo.exe'))
189
+ && fs.existsSync(path.join(directory, 'windows', 'configure-env.bat'));
190
+ }
191
+ return fs.existsSync(path.join(directory, 'bin', 'rustc'))
192
+ && fs.existsSync(path.join(directory, 'share', 'rust-portable', 'VERSION'));
193
+ }
194
+
195
+ function isBundle(directory, platform) {
196
+ if (platform === 'win32-x64') {
197
+ return isComplete(directory, platform);
198
+ }
199
+ return fs.existsSync(path.join(directory, 'linux', 'install.sh'))
200
+ && fs.existsSync(path.join(directory, 'VERSION'));
201
+ }
202
+
203
+ function looksLikeInstall(directory, platform) {
204
+ return isComplete(directory, platform) || Boolean(installedInfo(directory, platform).version);
205
+ }
206
+
207
+ function looksLikeBundle(directory, platform) {
208
+ return isBundle(directory, platform) || Boolean(bundleInfo(directory).version);
209
+ }
210
+
211
+ function isEmptyDirectory(directory) {
212
+ try {
213
+ return fs.readdirSync(directory).length === 0;
214
+ } catch {
215
+ return false;
216
+ }
217
+ }
218
+
219
+ function releaseKey(info) {
220
+ if (info.releaseVersion) {
221
+ return info.releaseVersion;
222
+ }
223
+ if (info.version && info.revision) {
224
+ return `${info.version}-${info.revision}`;
225
+ }
226
+ return info.version || info.rustVersion || '';
227
+ }
228
+
229
+ function sameRelease(info, archive) {
230
+ const archiveKey = archive.releaseVersion
231
+ || (archive.bundleRevision
232
+ ? `${archive.bundleVersion}-${archive.bundleRevision}`
233
+ : archive.bundleVersion);
234
+ return releaseKey(info) === (archiveKey || '');
235
+ }
236
+
237
+ module.exports = {
238
+ fail,
239
+ extractBundle,
240
+ bundleInfo,
241
+ installedInfo,
242
+ isBundle,
243
+ isComplete,
244
+ isEmptyDirectory,
245
+ looksLikeBundle,
246
+ looksLikeInstall,
247
+ sameRelease
248
+ };
package/install.js CHANGED
@@ -1,21 +1,25 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- // Joins the npm data chunks, verifies the resulting ZIP, and extracts the
5
- // portable Rust toolchain into a directory without spaces.
4
+ // Platform package postinstall.
5
+ //
6
+ // Joins the npm data chunks, verifies the archive, and extracts the portable
7
+ // Rust toolchain into `rust-portable` in the directory where npm was run.
8
+ // The setup command in the entry package controls installation under npx.
6
9
 
7
10
  const fs = require('node:fs');
8
- const os = require('node:os');
9
11
  const path = require('node:path');
10
- const crypto = require('node:crypto');
11
- const { execFileSync } = require('node:child_process');
12
- const { createRequire } = require('node:module');
13
- const { pipeline } = require('node:stream/promises');
14
- const { Transform } = require('node:stream');
15
12
 
16
13
  const archive = require('./archive.json');
17
14
  const pkg = require('./package.json');
18
- const requireFromHere = createRequire(__filename);
15
+ const {
16
+ extractBundle,
17
+ bundleInfo,
18
+ isBundle,
19
+ isEmptyDirectory,
20
+ looksLikeBundle,
21
+ sameRelease
22
+ } = require('./extract');
19
23
 
20
24
  function log(message) {
21
25
  console.log(`[rust-portable] ${message}`);
@@ -27,123 +31,101 @@ function fail(message) {
27
31
  throw new Error(message);
28
32
  }
29
33
 
30
- function isComplete(directory) {
31
- return fs.existsSync(path.join(directory, 'windows', 'cargo', 'bin', 'cargo.exe'));
34
+ function invocationDirectory() {
35
+ if (process.env.INIT_CWD) return path.resolve(process.env.INIT_CWD);
36
+ if (process.env.npm_config_local_prefix) return path.resolve(process.env.npm_config_local_prefix);
37
+
38
+ const cwd = process.cwd();
39
+ const marker = `${path.sep}node_modules${path.sep}`;
40
+ const index = cwd.indexOf(marker);
41
+ return index === -1 ? cwd : cwd.slice(0, index);
32
42
  }
33
43
 
34
- async function main() {
35
- if (process.platform !== 'win32' || process.arch !== 'x64') {
36
- fail(`Unsupported platform ${process.platform}/${process.arch}. This package supports Windows 10/11 x64 only.`);
37
- }
38
- if (!Array.isArray(archive.parts) || archive.parts.length === 0) {
39
- fail('archive.json does not list any data chunks.');
44
+ function defaultDestination() {
45
+ if (process.env.RUST_PORTABLE_INSTALL_DIR) {
46
+ return path.resolve(process.env.RUST_PORTABLE_INSTALL_DIR);
40
47
  }
48
+ return path.join(invocationDirectory(), 'rust-portable');
49
+ }
41
50
 
42
- const defaultHome = path.join(
43
- process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'),
44
- 'rust-portable'
45
- );
46
- const home = path.resolve(process.env.RUST_PORTABLE_HOME || defaultHome);
47
- if (/\s/.test(home)) {
48
- fail(`Install path contains spaces: ${home}\nSet RUST_PORTABLE_HOME to a path without spaces, for example C:\\rust-portable.`);
51
+ function printNextSteps(destination) {
52
+ console.log('');
53
+ log('Next steps:');
54
+ if (archive.platform === 'win32-x64') {
55
+ log(` 1. Run "${path.join(destination, 'windows', 'configure-env.bat')}"`);
56
+ log(' 2. Open a new terminal');
57
+ log(` 3. Run "${path.join(destination, 'windows', 'doctor.bat')}"`);
58
+ } else {
59
+ log(` 1. Run "bash ${path.join(destination, 'linux', 'install.sh')}"`);
60
+ log(' 2. Open a new terminal, or source env.sh');
61
+ log(' 3. Run "<prefix>/share/rust-portable/doctor.sh"');
49
62
  }
63
+ }
50
64
 
51
- const destination = path.join(home, pkg.version);
52
- const marker = path.join(destination, '.installed');
53
-
54
- if (fs.existsSync(marker) && isComplete(destination)) {
55
- log(`${pkg.version} is already installed at ${destination}`);
56
- printNextSteps(destination);
65
+ function main() {
66
+ if (process.env.npm_command === 'exec') {
67
+ // npx: the entry package CLI runs setup.js. Do not extract twice.
57
68
  return;
58
69
  }
59
70
 
60
- const temporaryZip = path.join(os.tmpdir(), `rust-portable-${pkg.version}-${process.pid}.zip`);
61
- const staging = path.join(home, `.staging-${pkg.version}-${process.pid}`);
62
- const hash = crypto.createHash('sha256');
63
- let written = 0;
64
-
65
- fs.mkdirSync(home, { recursive: true });
66
- fs.rmSync(staging, { recursive: true, force: true });
67
- fs.mkdirSync(staging, { recursive: true });
68
- fs.writeFileSync(temporaryZip, '');
69
-
70
- try {
71
- for (const part of archive.parts) {
72
- const packageJson = requireFromHere.resolve(`${part.package}/package.json`);
73
- const partPath = path.join(path.dirname(packageJson), part.file);
74
- if (!fs.existsSync(partPath)) {
75
- fail(`Missing data chunk: ${partPath}`);
76
- }
77
- log(`Adding ${part.package}/${part.file}`);
78
- const meter = new Transform({
79
- transform(chunk, encoding, callback) {
80
- hash.update(chunk);
81
- written += chunk.length;
82
- callback(null, chunk);
83
- }
84
- });
85
- await pipeline(
86
- fs.createReadStream(partPath),
87
- meter,
88
- fs.createWriteStream(temporaryZip, { flags: 'a' })
89
- );
90
- }
71
+ const current = `${process.platform}-${process.arch}`;
72
+ if (current !== archive.platform) {
73
+ fail(`This package is for ${archive.platform}, not ${current}.`);
74
+ }
91
75
 
92
- const actualHash = hash.digest('hex');
93
- if (written !== archive.size || actualHash !== archive.sha256) {
94
- fail(`Archive verification failed: ${written}/${archive.size} bytes, SHA256 ${actualHash}.`);
95
- }
96
- log(`Verified ${archive.zip} (${written} bytes, SHA256 ${actualHash})`);
76
+ const destination = defaultDestination();
97
77
 
98
- const tar = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe');
99
- if (!fs.existsSync(tar)) {
100
- fail(`Windows tar.exe was not found at ${tar}. Windows 10 1803 or newer is required.`);
101
- }
78
+ const force = process.env.RUST_PORTABLE_FORCE === '1';
102
79
 
103
- log(`Extracting to ${staging}`);
104
- execFileSync(tar, ['-xf', temporaryZip, '-C', staging, '--strip-components=1'], {
105
- stdio: 'inherit'
106
- });
80
+ if (fs.existsSync(destination)) {
81
+ if (!fs.statSync(destination).isDirectory()) {
82
+ fail(`Destination exists and is not a directory: ${destination}`);
83
+ }
107
84
 
108
- if (!isComplete(staging)) {
109
- fail('Extraction finished but windows\\cargo\\bin\\cargo.exe is missing.');
85
+ const info = bundleInfo(destination);
86
+ if (isBundle(destination, archive.platform) && sameRelease(info, archive) && !force) {
87
+ log(`${pkg.version} is already installed at ${destination}`);
88
+ printNextSteps(destination);
89
+ return;
110
90
  }
111
91
 
112
- if (fs.existsSync(destination)) {
113
- if (isComplete(destination)) {
114
- log(`${pkg.version} is already installed at ${destination}`);
115
- printNextSteps(destination);
116
- return;
117
- }
118
- if (process.env.RUST_PORTABLE_FORCE !== '1') {
119
- fail(`Destination already exists and does not look complete: ${destination}\nRemove it, or set RUST_PORTABLE_FORCE=1 to replace it.`);
120
- }
121
- fs.rmSync(destination, { recursive: true, force: true });
92
+ if (!looksLikeBundle(destination, archive.platform)
93
+ && !isEmptyDirectory(destination)
94
+ && !force) {
95
+ fail(
96
+ `Destination is not a rust-portable install: ${destination}\n` +
97
+ 'Choose another RUST_PORTABLE_INSTALL_DIR, or set RUST_PORTABLE_FORCE=1.'
98
+ );
122
99
  }
123
100
 
124
- fs.renameSync(staging, destination);
125
- fs.writeFileSync(marker, `${archive.sha256}\n`);
126
- log(`Installed to ${destination}`);
127
- log('The npm data chunks remain in node_modules; remove that project\'s node_modules to reclaim the space.');
128
- printNextSteps(destination);
129
- } finally {
130
- fs.rmSync(temporaryZip, { force: true });
131
- fs.rmSync(staging, { recursive: true, force: true });
101
+ if (looksLikeBundle(destination, archive.platform) && !sameRelease(info, archive) && !force) {
102
+ const installed = info.version || 'an unknown version';
103
+ fail(
104
+ `Destination contains rust-portable ${installed}: ${destination}\n` +
105
+ 'Set RUST_PORTABLE_FORCE=1 to replace it.'
106
+ );
107
+ }
132
108
  }
133
- }
134
109
 
135
- function printNextSteps(destination) {
136
- const windows = path.join(destination, 'windows');
137
- console.log('');
138
- log('Next steps:');
139
- log(` 1. Run "${path.join(windows, 'configure-env.bat')}"`);
140
- log(' 2. Open a new terminal');
141
- log(` 3. Run "${path.join(windows, 'doctor.bat')}"`);
110
+ const staging = extractBundle(archive, destination);
111
+ if (fs.existsSync(destination)) {
112
+ fs.rmSync(destination, { recursive: true, force: true });
113
+ }
114
+ fs.renameSync(staging, destination);
115
+ fs.writeFileSync(path.join(destination, '.installed'), `${pkg.version}\n${archive.sha256}\n`);
116
+ log(`Installed to ${destination}`);
117
+ if (archive.platform !== 'win32-x64') {
118
+ log('The bundle is extracted. Run linux/install.sh to install it to a prefix.');
119
+ }
120
+ printNextSteps(destination);
142
121
  }
143
122
 
144
- main().catch((error) => {
123
+ try {
124
+ main();
125
+ } catch (error) {
145
126
  if (!process.exitCode) {
146
127
  console.error(error.stack || String(error));
147
128
  process.exitCode = 1;
148
129
  }
149
- });
130
+ process.exit(process.exitCode);
131
+ }
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@ihason/rust-portable-win32-x64",
3
- "version": "1.99.1",
4
- "description": "Portable Rust 1.99.1 toolchain for Windows x64",
3
+ "version": "1.100.1",
4
+ "description": "Portable Rust 1.100.1 toolchain for Windows x64",
5
5
  "keywords": [
6
6
  "rust",
7
7
  "toolchain",
8
8
  "portable",
9
9
  "windows",
10
- "mingw"
10
+ "linux"
11
11
  ],
12
12
  "homepage": "https://github.com/HasonHuang/rust-portable#readme",
13
13
  "bugs": {
@@ -26,23 +26,22 @@
26
26
  "x64"
27
27
  ],
28
28
  "files": [
29
- "install.js",
30
29
  "archive.json",
30
+ "extract.js",
31
+ "setup.js",
32
+ "install.js",
31
33
  "README.md"
32
34
  ],
33
- "bin": {
34
- "rust-portable-install": "install.js"
35
- },
36
35
  "scripts": {
37
36
  "postinstall": "node install.js"
38
37
  },
39
38
  "dependencies": {
40
- "@ihason/rust-portable-win32-x64-chunk-01": "1.99.1",
41
- "@ihason/rust-portable-win32-x64-chunk-02": "1.99.1",
42
- "@ihason/rust-portable-win32-x64-chunk-03": "1.99.1",
43
- "@ihason/rust-portable-win32-x64-chunk-04": "1.99.1",
44
- "@ihason/rust-portable-win32-x64-chunk-05": "1.99.1",
45
- "@ihason/rust-portable-win32-x64-chunk-06": "1.99.1"
39
+ "@ihason/rust-portable-win32-x64-chunk-01": "1.100.1",
40
+ "@ihason/rust-portable-win32-x64-chunk-02": "1.100.1",
41
+ "@ihason/rust-portable-win32-x64-chunk-03": "1.100.1",
42
+ "@ihason/rust-portable-win32-x64-chunk-04": "1.100.1",
43
+ "@ihason/rust-portable-win32-x64-chunk-05": "1.100.1",
44
+ "@ihason/rust-portable-win32-x64-chunk-06": "1.100.1"
46
45
  },
47
46
  "engines": {
48
47
  "node": ">=18"
package/setup.js ADDED
@@ -0,0 +1,559 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // Interactive and non-interactive setup for one npm platform package.
5
+ // All data comes from the npm chunk packages. The setup does not use GitHub.
6
+
7
+ const fs = require('node:fs');
8
+ const os = require('node:os');
9
+ const path = require('node:path');
10
+ const { spawnSync } = require('node:child_process');
11
+ const readline = require('node:readline/promises');
12
+
13
+ const archive = require('./archive.json');
14
+ const pkg = require('./package.json');
15
+ const {
16
+ extractBundle,
17
+ installedInfo,
18
+ isComplete,
19
+ isEmptyDirectory,
20
+ looksLikeInstall,
21
+ sameRelease
22
+ } = require('./extract');
23
+
24
+ const options = {
25
+ prefix: '',
26
+ system: false,
27
+ user: false,
28
+ configurePath: true,
29
+ installDeps: false,
30
+ force: false,
31
+ runDoctor: true,
32
+ interactive: 'auto',
33
+ help: false
34
+ };
35
+
36
+ const originalArgs = process.argv.slice(2);
37
+ let rl = null;
38
+
39
+ function log(message) {
40
+ console.log(`[rust-portable] ${message}`);
41
+ }
42
+
43
+ function warn(message) {
44
+ console.error(`[rust-portable] WARNING: ${message}`);
45
+ }
46
+
47
+ function fail(message) {
48
+ const error = new Error(message);
49
+ error.rustPortable = true;
50
+ throw error;
51
+ }
52
+
53
+ function usage() {
54
+ const platform = archive.platform === 'win32-x64' ? 'Windows' : 'Linux';
55
+ console.log(`Usage: rust-portable setup [options]
56
+
57
+ Install the portable Rust toolchain for ${platform}.
58
+ All data is included in the npm packages. Setup does not use GitHub.
59
+
60
+ Options:
61
+ --prefix DIR Install to DIR. On Windows, DIR is the bundle directory.
62
+ --dir DIR Alias for --prefix on Windows.
63
+ --system Linux: install for all users. Requires sudo.
64
+ --user Linux: install for the current user. Default for non-root.
65
+ --no-path Do not configure PATH.
66
+ --install-deps Linux: install missing system tools.
67
+ --force Replace an existing installation.
68
+ --skip-doctor Do not run the self-check.
69
+ --interactive Ask for the options. A terminal is required.
70
+ --non-interactive Do not ask. Use the options and recommended defaults.
71
+ --yes Same as --non-interactive.
72
+ -h, --help Show this help.
73
+
74
+ When setup has no options and stdin is a terminal, it asks for the options.
75
+ Press Enter to accept the recommended value.`);
76
+ }
77
+
78
+ function parseArgs() {
79
+ let index = 0;
80
+ while (index < originalArgs.length) {
81
+ const arg = originalArgs[index];
82
+ switch (arg) {
83
+ case '--prefix':
84
+ case '--dir':
85
+ if (index + 1 >= originalArgs.length) fail(`${arg} needs a directory`);
86
+ options.prefix = originalArgs[index + 1];
87
+ index += 2;
88
+ break;
89
+ case '--system':
90
+ options.system = true;
91
+ index += 1;
92
+ break;
93
+ case '--user':
94
+ options.user = true;
95
+ index += 1;
96
+ break;
97
+ case '--no-path':
98
+ options.configurePath = false;
99
+ index += 1;
100
+ break;
101
+ case '--install-deps':
102
+ options.installDeps = true;
103
+ index += 1;
104
+ break;
105
+ case '--force':
106
+ options.force = true;
107
+ index += 1;
108
+ break;
109
+ case '--skip-doctor':
110
+ options.runDoctor = false;
111
+ index += 1;
112
+ break;
113
+ case '--interactive':
114
+ options.interactive = 'yes';
115
+ index += 1;
116
+ break;
117
+ case '--non-interactive':
118
+ case '--yes':
119
+ options.interactive = 'no';
120
+ index += 1;
121
+ break;
122
+ case '-h':
123
+ case '--help':
124
+ options.help = true;
125
+ index += 1;
126
+ break;
127
+ default:
128
+ if (arg.startsWith('--prefix=')) {
129
+ options.prefix = arg.slice('--prefix='.length);
130
+ index += 1;
131
+ } else if (arg.startsWith('--dir=')) {
132
+ options.prefix = arg.slice('--dir='.length);
133
+ index += 1;
134
+ } else {
135
+ fail(`unknown option: ${arg}`);
136
+ }
137
+ }
138
+ }
139
+
140
+ if (options.system && options.user) {
141
+ fail('use --system or --user, not both');
142
+ }
143
+ }
144
+
145
+ function terminalAvailable() {
146
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
147
+ }
148
+
149
+ function interactiveEnabled() {
150
+ if (options.interactive === 'no') return false;
151
+ if (options.interactive === 'yes') {
152
+ if (!terminalAvailable()) fail('--interactive needs a terminal');
153
+ return true;
154
+ }
155
+ return originalArgs.length === 0 && terminalAvailable();
156
+ }
157
+
158
+ function openPrompts() {
159
+ rl = readline.createInterface({ input: process.stdin, output: process.stdout });
160
+ }
161
+
162
+ function closePrompts() {
163
+ if (rl) {
164
+ rl.close();
165
+ rl = null;
166
+ }
167
+ }
168
+
169
+ async function ask(prompt, defaultValue) {
170
+ const answer = (await rl.question(`${prompt} [${defaultValue}]: `)).trim();
171
+ return answer || defaultValue;
172
+ }
173
+
174
+ async function askYesNo(prompt, defaultValue) {
175
+ const hint = defaultValue ? 'Y/n' : 'y/N';
176
+ const answer = (await rl.question(`${prompt} [${hint}]: `)).trim().toLowerCase();
177
+ if (!answer) return defaultValue;
178
+ return answer === 'y' || answer === 'yes';
179
+ }
180
+
181
+ function expandHome(value) {
182
+ if (value === '~') return os.homedir();
183
+ if (value.startsWith('~/')) return path.join(os.homedir(), value.slice(2));
184
+ return value;
185
+ }
186
+
187
+ function normalizePath(value) {
188
+ let result = path.resolve(expandHome(value));
189
+ while (result.length > 1 && result.endsWith(path.sep)) {
190
+ result = result.slice(0, -1);
191
+ }
192
+ return result;
193
+ }
194
+
195
+ function invocationDirectory() {
196
+ if (process.env.INIT_CWD) return path.resolve(process.env.INIT_CWD);
197
+ if (process.env.npm_config_local_prefix) return path.resolve(process.env.npm_config_local_prefix);
198
+
199
+ const cwd = process.cwd();
200
+ const marker = `${path.sep}node_modules${path.sep}`;
201
+ const index = cwd.indexOf(marker);
202
+ return index === -1 ? cwd : cwd.slice(0, index);
203
+ }
204
+
205
+ function hasCommand(name) {
206
+ const result = spawnSync('sh', ['-c', 'command -v "$1" >/dev/null 2>&1', 'sh', name], {
207
+ stdio: 'ignore'
208
+ });
209
+ return !result.error && result.status === 0;
210
+ }
211
+
212
+ function missingTools() {
213
+ return ['gcc', 'g++', 'make', 'tar', 'xz', 'find'].filter((tool) => !hasCommand(tool));
214
+ }
215
+
216
+ function isRoot() {
217
+ return typeof process.getuid === 'function' && process.getuid() === 0;
218
+ }
219
+
220
+ async function decideExisting(directory) {
221
+ if (!fs.existsSync(directory)) {
222
+ return { install: true, force: options.force };
223
+ }
224
+ if (!fs.statSync(directory).isDirectory()) {
225
+ fail(`The destination exists and is not a directory: ${directory}`);
226
+ }
227
+
228
+ const info = installedInfo(directory, archive.platform);
229
+ const complete = isComplete(directory, archive.platform);
230
+ const same = complete && sameRelease(info, archive);
231
+
232
+ if (same && !options.force) {
233
+ if (rl) {
234
+ const again = await askYesNo(
235
+ `rust-portable ${archive.releaseVersion || archive.bundleVersion} is already installed at ${directory}. Reinstall`,
236
+ false
237
+ );
238
+ if (!again) return { install: false, force: false };
239
+ return { install: true, force: true };
240
+ }
241
+ return { install: false, force: false };
242
+ }
243
+
244
+ if (!looksLikeInstall(directory, archive.platform)
245
+ && !isEmptyDirectory(directory)
246
+ && !options.force) {
247
+ if (rl) {
248
+ const proceed = await askYesNo(
249
+ `The destination is not empty and is not a rust-portable install: ${directory}. Replace its contents`,
250
+ false
251
+ );
252
+ if (!proceed) {
253
+ log('Cancelled.');
254
+ process.exit(0);
255
+ }
256
+ return { install: true, force: true };
257
+ }
258
+ fail(
259
+ `The destination is not empty and is not a rust-portable install: ${directory}\n` +
260
+ 'Use --force or another --prefix.'
261
+ );
262
+ }
263
+
264
+ if (looksLikeInstall(directory, archive.platform) && !same && !options.force) {
265
+ const installed = info.version || 'an unknown version';
266
+ if (rl) {
267
+ const replace = await askYesNo(
268
+ `The destination contains rust-portable ${installed}. Replace it with ${archive.releaseVersion || archive.bundleVersion}`,
269
+ false
270
+ );
271
+ if (!replace) {
272
+ log('Cancelled.');
273
+ process.exit(0);
274
+ }
275
+ return { install: true, force: true };
276
+ }
277
+ fail(
278
+ `The destination contains rust-portable ${installed}.\n` +
279
+ 'Use --force to replace it.'
280
+ );
281
+ }
282
+
283
+ return { install: true, force: options.force };
284
+ }
285
+
286
+ async function confirm(summary) {
287
+ if (!rl) return true;
288
+ console.log('');
289
+ console.log(summary);
290
+ console.log('');
291
+ const proceed = await askYesNo('Proceed', true);
292
+ if (!proceed) {
293
+ log('Cancelled.');
294
+ process.exit(0);
295
+ }
296
+ return true;
297
+ }
298
+
299
+ function summaryWindows(destination, install) {
300
+ const lines = [
301
+ `rust-portable ${archive.releaseVersion || archive.bundleVersion}`,
302
+ ' Platform: win32-x64',
303
+ ` Directory: ${destination}`,
304
+ ` Configure: ${options.configurePath ? 'yes' : 'no'}`,
305
+ ` Self-check: ${options.runDoctor ? 'yes' : 'no'}`
306
+ ];
307
+ if (!install) {
308
+ lines.push(' Action: already installed');
309
+ }
310
+ return lines.join('\n');
311
+ }
312
+
313
+ function summaryLinux(prefix, userLevel, install) {
314
+ const lines = [
315
+ `rust-portable ${archive.releaseVersion || archive.bundleVersion}`,
316
+ ` Platform: ${archive.platform}`,
317
+ ` Prefix: ${prefix}`,
318
+ ` Type: ${userLevel ? 'user-level' : 'system-level'}`,
319
+ ` Dependencies: ${options.installDeps ? 'install missing tools' : 'do not install'}`,
320
+ ` Configure: ${options.configurePath ? 'yes' : 'no'}`,
321
+ ` Self-check: ${options.runDoctor ? 'yes' : 'no'}`
322
+ ];
323
+ if (!install) {
324
+ lines.push(' Action: already installed, no changes');
325
+ }
326
+ return lines.join('\n');
327
+ }
328
+
329
+ function printWindowsNextSteps(destination) {
330
+ console.log('');
331
+ log('Next steps:');
332
+ log(` 1. Run "${path.join(destination, 'windows', 'configure-env.bat')}"`);
333
+ log(' 2. Open a new terminal');
334
+ log(` 3. Run "${path.join(destination, 'windows', 'doctor.bat')}"`);
335
+ }
336
+
337
+ function printLinuxNextSteps(prefix) {
338
+ console.log('');
339
+ log('Next steps:');
340
+ log(` 1. Activate: . "${path.join(prefix, 'share', 'rust-portable', 'env.sh')}"`);
341
+ log(` 2. Check: "${path.join(prefix, 'share', 'rust-portable', 'doctor.sh')}"`);
342
+ }
343
+
344
+ function runWindowsBatch(destination, name) {
345
+ const file = path.join(destination, 'windows', name);
346
+ if (!fs.existsSync(file)) {
347
+ fail(`Missing file: ${file}`);
348
+ }
349
+ const result = spawnSync(
350
+ process.env.ComSpec || 'cmd.exe',
351
+ ['/d', '/c', file, '--no-pause'],
352
+ { stdio: 'inherit' }
353
+ );
354
+ if (result.error) {
355
+ fail(`Cannot run ${name}: ${result.error.message}`);
356
+ }
357
+ if (result.status !== 0) {
358
+ fail(`${name} failed with exit code ${result.status}`);
359
+ }
360
+ }
361
+
362
+ async function runWindows() {
363
+ if (options.system || options.user) {
364
+ warn('--system and --user are for Linux. They are ignored on Windows.');
365
+ }
366
+ if (options.installDeps) {
367
+ warn('--install-deps is for Linux. It is ignored on Windows.');
368
+ }
369
+
370
+ let destination = options.prefix
371
+ ? normalizePath(options.prefix)
372
+ : process.env.RUST_PORTABLE_INSTALL_DIR
373
+ ? normalizePath(process.env.RUST_PORTABLE_INSTALL_DIR)
374
+ : path.join(invocationDirectory(), 'rust-portable');
375
+
376
+ if (rl) {
377
+ destination = normalizePath(await ask('Install directory', destination));
378
+ options.configurePath = await askYesNo('Configure Windows user PATH after extraction', true);
379
+ options.runDoctor = await askYesNo('Run the self-check after extraction', true);
380
+ }
381
+
382
+ const decision = await decideExisting(destination);
383
+ if (decision.install || options.configurePath || options.runDoctor) {
384
+ await confirm(summaryWindows(destination, decision.install));
385
+ }
386
+ closePrompts();
387
+
388
+ if (decision.install) {
389
+ const staging = extractBundle(archive, destination);
390
+ if (fs.existsSync(destination)) {
391
+ fs.rmSync(destination, { recursive: true, force: true });
392
+ }
393
+ fs.renameSync(staging, destination);
394
+ log(`Extracted to ${destination}`);
395
+ } else {
396
+ log(`rust-portable ${archive.releaseVersion || archive.bundleVersion} is already installed at ${destination}`);
397
+ }
398
+
399
+ if (options.configurePath) {
400
+ log('Configuring the Windows user environment');
401
+ runWindowsBatch(destination, 'configure-env.bat');
402
+ }
403
+
404
+ if (options.runDoctor) {
405
+ log('Running the self-check');
406
+ runWindowsBatch(destination, 'doctor.bat');
407
+ }
408
+
409
+ printWindowsNextSteps(destination);
410
+ }
411
+
412
+ async function runLinux() {
413
+ const root = isRoot();
414
+ const sudo = hasCommand('sudo');
415
+ let userLevel;
416
+
417
+ if (options.system) {
418
+ userLevel = false;
419
+ } else if (options.user) {
420
+ userLevel = true;
421
+ } else {
422
+ userLevel = !root;
423
+ }
424
+
425
+ let prefix = options.prefix
426
+ ? normalizePath(options.prefix)
427
+ : userLevel
428
+ ? path.join(os.homedir(), '.local', 'rust-portable')
429
+ : '/opt/rust-portable';
430
+
431
+ if (rl) {
432
+ if (!root && !options.system && !options.user) {
433
+ console.log('Install type:');
434
+ console.log(` 1) user-level (${path.join(os.homedir(), '.local', 'rust-portable')}) [recommended]`);
435
+ console.log(' 2) system-level (/opt/rust-portable, needs root)');
436
+ const answer = (await rl.question('Select [1]: ')).trim() || '1';
437
+ if (answer === '2') {
438
+ userLevel = false;
439
+ prefix = '/opt/rust-portable';
440
+ } else if (answer !== '1') {
441
+ fail(`invalid selection: ${answer}`);
442
+ }
443
+ } else {
444
+ console.log(`Install type: ${userLevel ? 'user-level' : 'system-level'}`);
445
+ }
446
+
447
+ prefix = normalizePath(await ask('Install prefix', prefix));
448
+
449
+ const missing = missingTools();
450
+ if (missing.length > 0 && !options.installDeps) {
451
+ console.log(`Missing system tools: ${missing.join(' ')}`);
452
+ options.installDeps = await askYesNo('Install missing system tools automatically', true);
453
+ }
454
+
455
+ options.configurePath = await askYesNo('Configure PATH for future shells', true);
456
+ options.runDoctor = await askYesNo('Run the self-check after installation', true);
457
+ }
458
+
459
+ if (!path.isAbsolute(prefix)) {
460
+ fail(`The install prefix must be an absolute path: ${prefix}`);
461
+ }
462
+ if (prefix === '/') {
463
+ fail('Refusing to install to /');
464
+ }
465
+ if (/\s/.test(prefix)) {
466
+ fail(`The install prefix must not contain spaces: ${prefix}`);
467
+ }
468
+ if (!userLevel && !root && !sudo) {
469
+ fail('System-level install needs sudo. Install sudo or use the default user-level install.');
470
+ }
471
+
472
+ const decision = await decideExisting(prefix);
473
+ if (decision.install) {
474
+ await confirm(summaryLinux(prefix, userLevel, decision.install));
475
+ }
476
+ closePrompts();
477
+
478
+ if (!decision.install) {
479
+ log(`rust-portable ${archive.releaseVersion || archive.bundleVersion} is already installed at ${prefix}`);
480
+ printLinuxNextSteps(prefix);
481
+ return;
482
+ }
483
+
484
+ const temporaryRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'rust-portable-setup-'));
485
+ try {
486
+ const staging = extractBundle(archive, path.join(temporaryRoot, 'bundle'));
487
+ const installer = path.join(staging, 'linux', 'install.sh');
488
+ // Passing --prefix already disables the interactive prompts in install.sh.
489
+ const args = [installer, '--prefix', prefix];
490
+
491
+ if (!options.configurePath) args.push('--no-path');
492
+ if (options.installDeps) args.push('--install-deps');
493
+ if (decision.force) args.push('--force');
494
+ if (!options.runDoctor) args.push('--skip-doctor');
495
+
496
+ const useSudo = !userLevel && !root;
497
+ const command = useSudo ? 'sudo' : 'bash';
498
+ const commandArgs = useSudo ? ['bash', ...args] : args;
499
+
500
+ const result = spawnSync(command, commandArgs, { stdio: 'inherit' });
501
+ if (result.error) {
502
+ fail(`Cannot run the installer: ${result.error.message}`);
503
+ }
504
+ if (result.status !== 0) {
505
+ fail(`The installer failed with exit code ${result.status}`);
506
+ }
507
+ } finally {
508
+ fs.rmSync(temporaryRoot, { recursive: true, force: true });
509
+ }
510
+
511
+ printLinuxNextSteps(prefix);
512
+ }
513
+
514
+ async function main() {
515
+ parseArgs();
516
+ if (options.help) {
517
+ usage();
518
+ return;
519
+ }
520
+
521
+ const current = `${process.platform}-${process.arch}`;
522
+ if (current !== archive.platform) {
523
+ fail(`This package is for ${archive.platform}, not ${current}.`);
524
+ }
525
+
526
+ if (process.platform === 'linux') {
527
+ const report = process.report && process.report.getReport();
528
+ if (report && report.header && !report.header.glibcVersionRuntime) {
529
+ fail('musl-based Linux is not supported. Use a glibc distribution such as Debian, Ubuntu, RHEL or AlmaLinux.');
530
+ }
531
+ }
532
+
533
+ if (process.platform === 'linux' && isRoot() && process.env.SUDO_USER) {
534
+ fail('Do not run npx with sudo. Run npx as your user; setup uses sudo when needed.');
535
+ }
536
+
537
+ const interactive = interactiveEnabled();
538
+ if (interactive) openPrompts();
539
+
540
+ try {
541
+ if (archive.platform === 'win32-x64') {
542
+ await runWindows();
543
+ } else {
544
+ await runLinux();
545
+ }
546
+ } finally {
547
+ closePrompts();
548
+ }
549
+ }
550
+
551
+ main().catch((error) => {
552
+ closePrompts();
553
+ if (error.rustPortable) {
554
+ console.error(`[rust-portable] ERROR: ${error.message}`);
555
+ } else {
556
+ console.error(error.stack || String(error));
557
+ }
558
+ process.exit(1);
559
+ });