fauxnix-cli 1.0.0 → 2.1.0
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 +61 -8
- package/dist/cli.js +30 -7
- package/dist/commands/archive.js +135 -103
- package/dist/commands/files.d.ts +2 -1
- package/dist/commands/files.js +140 -50
- package/dist/commands/gzip-node.d.ts +17 -0
- package/dist/commands/gzip-node.js +136 -0
- package/dist/commands/move-native.d.ts +1 -0
- package/dist/commands/move-native.js +82 -0
- package/dist/commands/net.js +26 -34
- package/dist/commands/sysinfo.js +7 -3
- package/dist/commands/text-filters.js +60 -123
- package/dist/commands/text-io.js +106 -92
- package/dist/commands/text-output.d.ts +14 -0
- package/dist/commands/text-output.js +29 -0
- package/dist/doctor.js +18 -12
- package/dist/encoding.d.ts +5 -0
- package/dist/encoding.js +40 -0
- package/dist/executor.js +1 -15
- package/dist/facade-launch.d.ts +29 -0
- package/dist/facade-launch.js +197 -0
- package/dist/facade-main.d.ts +1 -0
- package/dist/facade-main.js +11 -0
- package/dist/facade-sea.cjs +17800 -0
- package/dist/facade.js +137 -8
- package/dist/index.js +11 -5
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +162 -141
- package/dist/parser.js +42 -33
- package/dist/ps-host.js +34 -3
- package/dist/registry.d.ts +5 -0
- package/dist/registry.js +10 -5
- package/dist/runtime-support.d.ts +3 -0
- package/dist/runtime-support.js +31 -0
- package/dist/translator.d.ts +3 -1
- package/dist/translator.js +155 -56
- package/dist/version.js +12 -5
- package/package.json +8 -4
package/dist/commands/files.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { FauxnixParseError, wordToString } from '../ast.js';
|
|
2
2
|
import { parseWords, psStr, } from '../registry.js';
|
|
3
3
|
import { argListExpr, exprOfWord, operandExpr } from '../translator.js';
|
|
4
|
+
import { PS_WRITE_FN, fxTermLine } from './text-output.js';
|
|
5
|
+
import { PS_MOVE_REPLACE_FN } from './move-native.js';
|
|
4
6
|
/* ------------------------------------------------------------------ */
|
|
5
7
|
/* Shared PS snippets */
|
|
6
8
|
/* ------------------------------------------------------------------ */
|
|
@@ -69,6 +71,7 @@ const ls = (args) => {
|
|
|
69
71
|
return [
|
|
70
72
|
PS_GLOB_FN,
|
|
71
73
|
PS_FTIME_FN,
|
|
74
|
+
PS_HSIZE_FN,
|
|
72
75
|
'function fx-mode($it) {',
|
|
73
76
|
" $t = '-'; if ($it.PSIsContainer) { $t = 'd' } elseif " + psIsLink('$it') + " { $t = 'l' }",
|
|
74
77
|
" if ($it.PSIsContainer) { return ($t + 'rwxr-xr-x') }",
|
|
@@ -149,22 +152,22 @@ const cp = (args) => {
|
|
|
149
152
|
PS_GLOB_FN,
|
|
150
153
|
'$fx_all = ' + argListExpr(operandWords),
|
|
151
154
|
"if ($fx_all.Count -lt 2) { $fx_srcs = @(); $fx_dst = '' } else { $fx_dst = [string]$fx_all[$fx_all.Count - 1]; $fx_srcs = @($fx_all[0..($fx_all.Count - 2)]) }",
|
|
155
|
+
'$fx_srcs = @($fx_srcs | ForEach-Object { fx-glob $_ })',
|
|
152
156
|
"if ($fx_srcs.Count -eq 0) { [Console]::Error.WriteLine('cp: missing file operand'); $script:fx_exit = 1 }",
|
|
153
157
|
"elseif ($fx_dst -eq '') { [Console]::Error.WriteLine('cp: missing destination file operand'); $script:fx_exit = 1 }",
|
|
158
|
+
'elseif ($fx_srcs.Count -gt 1 -and -not (Test-Path -LiteralPath $fx_dst -PathType Container)) { [Console]::Error.WriteLine("cp: target \'" + $fx_dst + "\' is not a directory"); $script:fx_exit = 1 }',
|
|
154
159
|
'else {',
|
|
155
|
-
' foreach ($
|
|
156
|
-
'
|
|
157
|
-
'
|
|
158
|
-
'
|
|
159
|
-
'
|
|
160
|
-
'
|
|
161
|
-
'
|
|
162
|
-
'
|
|
163
|
-
'
|
|
164
|
-
'
|
|
165
|
-
'
|
|
166
|
-
' } catch { [Console]::Error.WriteLine("cp: cannot copy \'" + $fx_g + "\': " + $_.Exception.Message); $script:fx_exit = 1 }',
|
|
167
|
-
' }',
|
|
160
|
+
' foreach ($fx_g in $fx_srcs) {',
|
|
161
|
+
' if (-not (Test-Path -LiteralPath $fx_g)) { [Console]::Error.WriteLine("cp: cannot stat \'" + $fx_g + "\': No such file or directory"); $script:fx_exit = 1; continue }',
|
|
162
|
+
' $fx_isdir = (Test-Path -LiteralPath $fx_g -PathType Container)',
|
|
163
|
+
' if ($fx_isdir -and ' + (recurse ? '$false' : '$true') + ') { [Console]::Error.WriteLine("cp: -r not specified; omitting directory \'" + $fx_g + "\'"); $script:fx_exit = 1; continue }',
|
|
164
|
+
' $fx_target = $fx_dst',
|
|
165
|
+
' if (Test-Path -LiteralPath $fx_dst -PathType Container) { $fx_target = Join-Path $fx_dst (Split-Path $fx_g -Leaf) }',
|
|
166
|
+
' if (' + (noclobber ? '$true' : '$false') + ' -and (Test-Path -LiteralPath $fx_target)) { continue }',
|
|
167
|
+
' try {',
|
|
168
|
+
' Copy-Item -LiteralPath $fx_g -Destination $fx_target -Recurse:' + (recurse ? '$true' : '$false') + ' -Force -ErrorAction Stop',
|
|
169
|
+
' if (' + (verbose ? '$true' : '$false') + ') { [Console]::Error.WriteLine("\'" + $fx_g + "\' -> \'" + $fx_target + "\'") }',
|
|
170
|
+
' } catch { [Console]::Error.WriteLine("cp: cannot copy \'" + $fx_g + "\': " + $_.Exception.Message); $script:fx_exit = 1 }',
|
|
168
171
|
' }',
|
|
169
172
|
'}',
|
|
170
173
|
].join('\n');
|
|
@@ -175,24 +178,48 @@ const mv = (args) => {
|
|
|
175
178
|
const noclobber = flags.has('n') || longs.has('--no-clobber');
|
|
176
179
|
return [
|
|
177
180
|
PS_GLOB_FN,
|
|
181
|
+
PS_MOVE_REPLACE_FN,
|
|
178
182
|
'$fx_all = ' + argListExpr(operandWords),
|
|
179
183
|
"if ($fx_all.Count -lt 2) { $fx_srcs = @(); $fx_dst = '' } else { $fx_dst = [string]$fx_all[$fx_all.Count - 1]; $fx_srcs = @($fx_all[0..($fx_all.Count - 2)]) }",
|
|
184
|
+
'$fx_srcs = @($fx_srcs | ForEach-Object { fx-glob $_ })',
|
|
180
185
|
"if ($fx_srcs.Count -eq 0) { [Console]::Error.WriteLine('mv: missing file operand'); $script:fx_exit = 1 }",
|
|
181
186
|
"elseif ($fx_dst -eq '') { [Console]::Error.WriteLine('mv: missing destination file operand'); $script:fx_exit = 1 }",
|
|
182
187
|
'elseif ($fx_srcs.Count -gt 1 -and -not (Test-Path -LiteralPath $fx_dst -PathType Container)) { [Console]::Error.WriteLine("mv: target \'" + $fx_dst + "\' is not a directory"); $script:fx_exit = 1 }',
|
|
183
188
|
'else {',
|
|
184
|
-
' foreach ($
|
|
185
|
-
'
|
|
186
|
-
'
|
|
187
|
-
'
|
|
188
|
-
'
|
|
189
|
-
'
|
|
190
|
-
'
|
|
191
|
-
'
|
|
192
|
-
'
|
|
193
|
-
|
|
194
|
-
'
|
|
195
|
-
'
|
|
189
|
+
' foreach ($fx_g in $fx_srcs) {',
|
|
190
|
+
' if (-not (Test-Path -LiteralPath $fx_g)) { [Console]::Error.WriteLine("mv: cannot stat \'" + $fx_g + "\': No such file or directory"); $script:fx_exit = 1; continue }',
|
|
191
|
+
' $fx_target = $fx_dst',
|
|
192
|
+
' if (Test-Path -LiteralPath $fx_dst -PathType Container) { $fx_target = Join-Path $fx_dst (Split-Path $fx_g -Leaf) }',
|
|
193
|
+
' if (' + (noclobber ? '$true' : '$false') + ' -and (Test-Path -LiteralPath $fx_target)) { continue }',
|
|
194
|
+
' try {',
|
|
195
|
+
' if (Test-Path -LiteralPath $fx_target) {',
|
|
196
|
+
' $fx_sourcePath = (Resolve-Path -LiteralPath $fx_g -ErrorAction Stop).ProviderPath',
|
|
197
|
+
' $fx_targetPath = (Resolve-Path -LiteralPath $fx_target -ErrorAction Stop).ProviderPath',
|
|
198
|
+
" if ($fx_sourcePath.TrimEnd([char[]]'\\/') -eq $fx_targetPath.TrimEnd([char[]]'\\/')) {",
|
|
199
|
+
' [Console]::Error.WriteLine("mv: \'" + $fx_g + "\' and \'" + $fx_target + "\' are the same file"); $script:fx_exit = 1; continue',
|
|
200
|
+
' }',
|
|
201
|
+
' $fx_sourceItem = Get-Item -LiteralPath $fx_g -Force -ErrorAction Stop',
|
|
202
|
+
' $fx_targetItem = Get-Item -LiteralPath $fx_target -Force -ErrorAction Stop',
|
|
203
|
+
' if (-not $fx_sourceItem.PSIsContainer -and $fx_targetItem.PSIsContainer) {',
|
|
204
|
+
' [Console]::Error.WriteLine("mv: cannot overwrite directory \'" + $fx_target + "\' with non-directory \'" + $fx_g + "\'"); $script:fx_exit = 1; continue',
|
|
205
|
+
' }',
|
|
206
|
+
' if ($fx_sourceItem.PSIsContainer -and -not $fx_targetItem.PSIsContainer) {',
|
|
207
|
+
' [Console]::Error.WriteLine("mv: cannot overwrite non-directory \'" + $fx_target + "\' with directory \'" + $fx_g + "\'"); $script:fx_exit = 1; continue',
|
|
208
|
+
' }',
|
|
209
|
+
' if ($fx_targetItem.PSIsContainer) {',
|
|
210
|
+
' if (@(Get-ChildItem -LiteralPath $fx_target -Force -ErrorAction Stop).Count -gt 0) {',
|
|
211
|
+
' [Console]::Error.WriteLine("mv: cannot move \'" + $fx_g + "\' to \'" + $fx_target + "\': Directory not empty"); $script:fx_exit = 1; continue',
|
|
212
|
+
' }',
|
|
213
|
+
' [Console]::Error.WriteLine("mv: replacement of an existing empty directory is unsupported; both directories retained"); $script:fx_exit = 1; continue',
|
|
214
|
+
' } else {',
|
|
215
|
+
' fx-move-replace-file $fx_sourcePath $fx_targetPath',
|
|
216
|
+
' }',
|
|
217
|
+
' } else {',
|
|
218
|
+
// No force retry if a destination appears after the preflight.
|
|
219
|
+
' Move-Item -LiteralPath $fx_g -Destination $fx_target -ErrorAction Stop',
|
|
220
|
+
' }',
|
|
221
|
+
' if (' + (verbose ? '$true' : '$false') + ') { [Console]::Error.WriteLine("renamed \'" + $fx_g + "\' -> \'" + $fx_target + "\'") }',
|
|
222
|
+
' } catch { [Console]::Error.WriteLine("mv: cannot move \'" + $fx_g + "\': " + $_.Exception.Message); $script:fx_exit = 1 }',
|
|
196
223
|
' }',
|
|
197
224
|
'}',
|
|
198
225
|
].join('\n');
|
|
@@ -215,7 +242,7 @@ const rm = (args) => {
|
|
|
215
242
|
' $fx_isdir = (Test-Path -LiteralPath $fx_g -PathType Container)',
|
|
216
243
|
' if ($fx_isdir -and ' + (recurse ? '$false' : '$true') + ') { [Console]::Error.WriteLine("rm: cannot remove \'" + $fx_g + "\': Is a directory"); $script:fx_exit = 1; continue }',
|
|
217
244
|
' try {',
|
|
218
|
-
' Remove-Item -LiteralPath $fx_g -Recurse:' + (recurse ? '$true' : '$false') + ' -Force',
|
|
245
|
+
' Remove-Item -LiteralPath $fx_g -Recurse:' + (recurse ? '$true' : '$false') + ' -Force -ErrorAction Stop',
|
|
219
246
|
' if (' + (verbose ? '$true' : '$false') + ') { [Console]::Error.WriteLine("removed \'" + $fx_g + "\'") }',
|
|
220
247
|
' } catch { [Console]::Error.WriteLine("rm: cannot remove \'" + $fx_g + "\': Permission denied"); $script:fx_exit = 1 }',
|
|
221
248
|
' }',
|
|
@@ -234,11 +261,11 @@ const mkdir = (args) => {
|
|
|
234
261
|
"if ($fx_dirs.Count -eq 0) { [Console]::Error.WriteLine('mkdir: missing operand'); $script:fx_exit = 1 }",
|
|
235
262
|
'foreach ($fx_d in $fx_dirs) {',
|
|
236
263
|
' if (Test-Path -LiteralPath $fx_d) {',
|
|
237
|
-
' if (' + (parents ? '$false' : '$true') + ') { [Console]::Error.WriteLine("mkdir: cannot create directory \'" + $fx_d + "\': File exists"); $script:fx_exit = 1 }',
|
|
264
|
+
' if (' + (parents ? '$false' : '$true') + ' -or -not (Test-Path -LiteralPath $fx_d -PathType Container)) { [Console]::Error.WriteLine("mkdir: cannot create directory \'" + $fx_d + "\': File exists"); $script:fx_exit = 1 }',
|
|
238
265
|
' continue',
|
|
239
266
|
' }',
|
|
240
267
|
' try {',
|
|
241
|
-
' New-Item -ItemType Directory -Path $fx_d -Force:' + (parents ? '$true' : '$false') + ' | Out-Null',
|
|
268
|
+
' New-Item -ItemType Directory -Path $fx_d -Force:' + (parents ? '$true' : '$false') + ' -ErrorAction Stop | Out-Null',
|
|
242
269
|
' if (' + (verbose ? '$true' : '$false') + ') { [Console]::Error.WriteLine("mkdir: created directory \'" + $fx_d + "\'") }',
|
|
243
270
|
' } catch { [Console]::Error.WriteLine("mkdir: cannot create directory \'" + $fx_d + "\': " + $_.Exception.Message); $script:fx_exit = 1 }',
|
|
244
271
|
'}',
|
|
@@ -252,7 +279,7 @@ const rmdir = (args) => {
|
|
|
252
279
|
'foreach ($fx_d in $fx_dirs) {',
|
|
253
280
|
' if (-not (Test-Path -LiteralPath $fx_d -PathType Container)) { [Console]::Error.WriteLine("rmdir: failed to remove \'" + $fx_d + "\': No such file or directory"); $script:fx_exit = 1; continue }',
|
|
254
281
|
' if ((Get-ChildItem -LiteralPath $fx_d -Force).Count -gt 0) { [Console]::Error.WriteLine("rmdir: failed to remove \'" + $fx_d + "\': Directory not empty"); $script:fx_exit = 1; continue }',
|
|
255
|
-
' try { Remove-Item -LiteralPath $fx_d -Force } catch { [Console]::Error.WriteLine("rmdir: failed to remove \'" + $fx_d + "\': " + $_.Exception.Message); $script:fx_exit = 1 }',
|
|
282
|
+
' try { Remove-Item -LiteralPath $fx_d -Force -ErrorAction Stop } catch { [Console]::Error.WriteLine("rmdir: failed to remove \'" + $fx_d + "\': " + $_.Exception.Message); $script:fx_exit = 1 }',
|
|
256
283
|
'}',
|
|
257
284
|
].join('\n');
|
|
258
285
|
};
|
|
@@ -267,7 +294,7 @@ const touch = (args) => {
|
|
|
267
294
|
' try { (Get-Item -LiteralPath $fx_f).LastWriteTime = Get-Date } catch { [Console]::Error.WriteLine("touch: cannot touch \'" + $fx_f + "\': Permission denied"); $script:fx_exit = 1 }',
|
|
268
295
|
' } else {',
|
|
269
296
|
' if (' + (noCreate ? '$true' : '$false') + ') { continue }',
|
|
270
|
-
' try { New-Item -ItemType File -Path $fx_f | Out-Null }',
|
|
297
|
+
' try { New-Item -ItemType File -Path $fx_f -ErrorAction Stop | Out-Null }',
|
|
271
298
|
' catch { [Console]::Error.WriteLine("touch: cannot touch \'" + $fx_f + "\': No such file or directory"); $script:fx_exit = 1 }',
|
|
272
299
|
' }',
|
|
273
300
|
'}',
|
|
@@ -280,7 +307,7 @@ const mktemp = (args) => {
|
|
|
280
307
|
'try {',
|
|
281
308
|
' if (' + (dir ? '$true' : '$false') + ') {',
|
|
282
309
|
" $fx_p = Join-Path $env:TEMP ('fauxnix-' + ([IO.Path]::GetRandomFileName() -replace '\\.', ''))",
|
|
283
|
-
' New-Item -ItemType Directory -Path $fx_p | Out-Null',
|
|
310
|
+
' New-Item -ItemType Directory -Path $fx_p -ErrorAction Stop | Out-Null',
|
|
284
311
|
' } else {',
|
|
285
312
|
' $fx_p = [IO.Path]::GetTempFileName()',
|
|
286
313
|
' }',
|
|
@@ -302,7 +329,7 @@ const ln = (args) => {
|
|
|
302
329
|
"if ($fx_src -eq '' -or $fx_dst -eq '') { [Console]::Error.WriteLine('ln: missing file operand'); $script:fx_exit = 1 }",
|
|
303
330
|
'else {',
|
|
304
331
|
' if (Test-Path -LiteralPath $fx_dst -PathType Container) { $fx_dst = Join-Path $fx_dst (Split-Path $fx_src -Leaf) }',
|
|
305
|
-
' try { New-Item -ItemType ' + kind + ' -Path $fx_dst -Target $fx_src | Out-Null }',
|
|
332
|
+
' try { New-Item -ItemType ' + kind + ' -Path $fx_dst -Target $fx_src -ErrorAction Stop | Out-Null }',
|
|
306
333
|
' catch { [Console]::Error.WriteLine("ln: failed to create ' + label + ' \'" + $fx_dst + "\': " + $_.Exception.Message); $script:fx_exit = 1 }',
|
|
307
334
|
'}',
|
|
308
335
|
].join('\n');
|
|
@@ -341,8 +368,9 @@ const realpath = (args) => {
|
|
|
341
368
|
/* basename / dirname */
|
|
342
369
|
/* ------------------------------------------------------------------ */
|
|
343
370
|
const basename = (args) => {
|
|
371
|
+
const { operandWords } = parseWords(args);
|
|
344
372
|
return [
|
|
345
|
-
'$fx_ps = ' + argListExpr(
|
|
373
|
+
'$fx_ps = ' + argListExpr(operandWords, exprOfWord),
|
|
346
374
|
"if ($fx_ps.Count -eq 0) { [Console]::Error.WriteLine('basename: missing operand'); $script:fx_exit = 1 }",
|
|
347
375
|
'elseif ($fx_ps.Count -eq 2) {',
|
|
348
376
|
' $fx_p = [string]$fx_ps[0]',
|
|
@@ -361,8 +389,9 @@ const basename = (args) => {
|
|
|
361
389
|
].join('\n');
|
|
362
390
|
};
|
|
363
391
|
const dirname = (args) => {
|
|
392
|
+
const { operandWords } = parseWords(args);
|
|
364
393
|
return [
|
|
365
|
-
'$fx_ps = ' + argListExpr(
|
|
394
|
+
'$fx_ps = ' + argListExpr(operandWords, exprOfWord),
|
|
366
395
|
"if ($fx_ps.Count -eq 0) { [Console]::Error.WriteLine('dirname: missing operand'); $script:fx_exit = 1 }",
|
|
367
396
|
'foreach ($fx_p in $fx_ps) {',
|
|
368
397
|
" $fx_n = ($fx_p.TrimEnd('/')).TrimEnd('\\')",
|
|
@@ -376,12 +405,71 @@ const dirname = (args) => {
|
|
|
376
405
|
/* ------------------------------------------------------------------ */
|
|
377
406
|
/* stat / file */
|
|
378
407
|
/* ------------------------------------------------------------------ */
|
|
379
|
-
const
|
|
380
|
-
|
|
381
|
-
|
|
408
|
+
const STAT_DIRECTIVES = {
|
|
409
|
+
'%%': psStr('%'),
|
|
410
|
+
'%s': '[string]$fx_size',
|
|
411
|
+
'%n': '$fx_g',
|
|
412
|
+
'%F': '$fx_ft',
|
|
413
|
+
'%a': "$fx_mode.TrimStart('0')",
|
|
414
|
+
'%Y': '[string]$fx_epoch',
|
|
415
|
+
'%y': "$fx_it.LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss')",
|
|
416
|
+
};
|
|
417
|
+
/** Expand the existing stat directives once; inserted metadata is literal. */
|
|
418
|
+
function statFormatExpr(format) {
|
|
419
|
+
// Only odd slots are recognized directives. Other text, including unknown
|
|
420
|
+
// directives, stays quoted rather than being mistaken for a lookup key.
|
|
421
|
+
return format.split(/(%[%snFaYy])/)
|
|
422
|
+
.map((part, index) => index % 2 ? STAT_DIRECTIVES[part] : psStr(part))
|
|
423
|
+
.join(' + ');
|
|
424
|
+
}
|
|
425
|
+
/** GNU --printf escapes are scanned beside directives, never before them. */
|
|
426
|
+
function statPrintfFormat(format) {
|
|
427
|
+
const warnings = [];
|
|
428
|
+
let error;
|
|
429
|
+
const controls = { a: 7, b: 8, e: 27, f: 12, n: 10, r: 13, t: 9, v: 11 };
|
|
430
|
+
const expr = format.split(/(%[%snFaYy]|\\(?:[0-7]{1,3}|x[0-9a-fA-F]{1,2}|[\s\S]|$))/)
|
|
431
|
+
.map((part, index) => {
|
|
432
|
+
if (index % 2 === 0)
|
|
433
|
+
return psStr(part);
|
|
434
|
+
if (part.startsWith('%'))
|
|
435
|
+
return STAT_DIRECTIVES[part];
|
|
436
|
+
const escape = part.slice(1);
|
|
437
|
+
let byte;
|
|
438
|
+
if (/^[0-7]{1,3}$/.test(escape))
|
|
439
|
+
byte = parseInt(escape, 8) & 255;
|
|
440
|
+
else if (/^x[0-9a-fA-F]{1,2}$/.test(escape))
|
|
441
|
+
byte = parseInt(escape.slice(1), 16);
|
|
442
|
+
if (byte !== undefined) {
|
|
443
|
+
if (byte >= 128) {
|
|
444
|
+
error = 'stat: fauxnix: non-ASCII numeric byte escapes are not supported by the text output contract';
|
|
445
|
+
}
|
|
446
|
+
return '[string][char]' + byte;
|
|
447
|
+
}
|
|
448
|
+
if (Object.hasOwn(controls, escape))
|
|
449
|
+
return '[string][char]' + controls[escape];
|
|
450
|
+
if (escape === '\\')
|
|
451
|
+
return psStr('\\');
|
|
452
|
+
if (escape === '') {
|
|
453
|
+
warnings.push('stat: warning: backslash at end of format');
|
|
454
|
+
return psStr('\\');
|
|
455
|
+
}
|
|
456
|
+
warnings.push("stat: warning: unrecognized escape '\\" + escape + "'");
|
|
457
|
+
return psStr(escape);
|
|
458
|
+
}).join(' + ');
|
|
459
|
+
return { expr, warnings, error };
|
|
460
|
+
}
|
|
461
|
+
const stat = (args, ctx) => {
|
|
462
|
+
const { valueEntries, operandWords } = parseWords(args, ['c'], ['--format', '--printf']);
|
|
463
|
+
const formatOption = valueEntries.at(-1);
|
|
464
|
+
const fmt = formatOption?.value ?? null;
|
|
465
|
+
const printfMode = formatOption?.name === '--printf';
|
|
466
|
+
const format = printfMode ? statPrintfFormat(fmt ?? '') : { expr: statFormatExpr(fmt ?? ''), warnings: [] };
|
|
467
|
+
if (format.error)
|
|
468
|
+
return '[Console]::Error.WriteLine(' + psStr(format.error) + '); $script:fx_exit = 1';
|
|
382
469
|
return [
|
|
383
470
|
PS_FTIME_FN,
|
|
384
471
|
PS_GLOB_FN,
|
|
472
|
+
...(printfMode ? [PS_WRITE_FN, fxTermLine(ctx.position), '$fx_stat_out = New-Object System.Text.StringBuilder'] : []),
|
|
385
473
|
'$fx_files = ' + psArray(operandWords),
|
|
386
474
|
"if ($fx_files.Count -eq 0) { [Console]::Error.WriteLine('stat: missing operand'); $script:fx_exit = 1 }",
|
|
387
475
|
'foreach ($fx_f in $fx_files) {',
|
|
@@ -394,11 +482,11 @@ const stat = (args) => {
|
|
|
394
482
|
" { $fx_ft = 'symbolic link' }",
|
|
395
483
|
" $fx_ro = $fx_it.Attributes.ToString().Contains('ReadOnly')",
|
|
396
484
|
" $fx_mode = '0664'; if ($fx_it.PSIsContainer) { $fx_mode = '0775' } elseif ($fx_ro) { $fx_mode = '0444' }",
|
|
397
|
-
" $fx_epoch = [
|
|
398
|
-
' if (' + (fmt ? '$true' : '$false') + ') {',
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
' $fx_o',
|
|
485
|
+
" $fx_epoch = [long][math]::Floor(($fx_it.LastWriteTime.ToUniversalTime() - [datetime]'1970-01-01').TotalSeconds)",
|
|
486
|
+
' if (' + (fmt !== null ? '$true' : '$false') + ') {',
|
|
487
|
+
...format.warnings.map((warning) => ' [Console]::Error.WriteLine(' + psStr(warning) + ')'),
|
|
488
|
+
' $fx_o = ' + format.expr,
|
|
489
|
+
printfMode ? ' [void]$fx_stat_out.Append($fx_o)' : ' $fx_o',
|
|
402
490
|
' } else {',
|
|
403
491
|
' " File: " + $fx_g',
|
|
404
492
|
' (" Size: {0}`tBlocks: {1}`tIO Block: 4096 {2}" -f $fx_size, [math]::Ceiling($fx_size / 512), $fx_ft)',
|
|
@@ -408,6 +496,7 @@ const stat = (args) => {
|
|
|
408
496
|
' }',
|
|
409
497
|
' }',
|
|
410
498
|
'}',
|
|
499
|
+
...(printfMode ? ['fx-write ($fx_stat_out.ToString()) $fx_term'] : []),
|
|
411
500
|
].join('\n');
|
|
412
501
|
};
|
|
413
502
|
const file = (args) => {
|
|
@@ -838,8 +927,8 @@ const chmod = (args) => {
|
|
|
838
927
|
' if (-not (Test-Path -LiteralPath $fx_f)) { [Console]::Error.WriteLine("chmod: cannot access \'" + $fx_f + "\': No such file or directory"); $script:fx_exit = 1; continue }',
|
|
839
928
|
' try {',
|
|
840
929
|
' $fx_it = Get-Item -LiteralPath $fx_f -Force',
|
|
841
|
-
' if (' + (readOnly ===
|
|
842
|
-
' elseif (' + (readOnly ===
|
|
930
|
+
' if (' + (readOnly === true ? '$true' : '$false') + ') { $fx_it.Attributes = $fx_it.Attributes -bor [IO.FileAttributes]::ReadOnly }',
|
|
931
|
+
' elseif (' + (readOnly === false ? '$true' : '$false') + ') { $fx_it.Attributes = $fx_it.Attributes -band (-bnot [IO.FileAttributes]::ReadOnly) }',
|
|
843
932
|
' # symbolic modes (+x, u+w ...): Windows has no exec bit — accepted as a no-op',
|
|
844
933
|
' } catch { [Console]::Error.WriteLine("chmod: changing permissions of \'" + $fx_f + "\': " + $_.Exception.Message); $script:fx_exit = 1 }',
|
|
845
934
|
'}',
|
|
@@ -872,7 +961,7 @@ const diff = (args) => {
|
|
|
872
961
|
' $fx_lb = @((fx-read $fx_b) -split "`r?`n")',
|
|
873
962
|
" if ($fx_lb.Count -eq 1 -and $fx_lb[0] -eq '') { $fx_lb = @() }",
|
|
874
963
|
' $fx_same = ($fx_la.Count -eq $fx_lb.Count)',
|
|
875
|
-
' if ($fx_same) { for ($fx_i = 0; $fx_i -lt $fx_la.Count; $fx_i++) { if ($fx_la[$fx_i] -
|
|
964
|
+
' if ($fx_same) { for ($fx_i = 0; $fx_i -lt $fx_la.Count; $fx_i++) { if ($fx_la[$fx_i] -cne $fx_lb[$fx_i]) { $fx_same = $false; break } } }',
|
|
876
965
|
' if ($fx_same) { }',
|
|
877
966
|
' elseif (' + (brief ? '$true' : '$false') + ') { "Files " + $fx_a + " and " + $fx_b + " differ"; $script:fx_exit = 1 }',
|
|
878
967
|
' elseif ($fx_la.Count -gt 4000 -or $fx_lb.Count -gt 4000) { "Files " + $fx_a + " and " + $fx_b + " differ (too large for a fauxnix line diff)"; $script:fx_exit = 1 }',
|
|
@@ -882,14 +971,14 @@ const diff = (args) => {
|
|
|
882
971
|
" $fx_dp = New-Object 'int[]' (($fx_n + 1) * $fx_w)",
|
|
883
972
|
' for ($fx_i = $fx_n - 1; $fx_i -ge 0; $fx_i--) {',
|
|
884
973
|
' for ($fx_j = $fx_m - 1; $fx_j -ge 0; $fx_j--) {',
|
|
885
|
-
' if ($fx_la[$fx_i] -
|
|
974
|
+
' if ($fx_la[$fx_i] -ceq $fx_lb[$fx_j]) { $fx_dp[($fx_i * $fx_w) + $fx_j] = $fx_dp[(($fx_i + 1) * $fx_w) + ($fx_j + 1)] + 1 }',
|
|
886
975
|
' else { $fx_r = $fx_dp[(($fx_i + 1) * $fx_w) + $fx_j]; $fx_d2 = $fx_dp[($fx_i * $fx_w) + ($fx_j + 1)]; if ($fx_r -ge $fx_d2) { $fx_dp[($fx_i * $fx_w) + $fx_j] = $fx_r } else { $fx_dp[($fx_i * $fx_w) + $fx_j] = $fx_d2 } }',
|
|
887
976
|
' }',
|
|
888
977
|
' }',
|
|
889
978
|
" $fx_ops = @() # tuples: @('<op>', text, aIndex, bIndex)",
|
|
890
979
|
' $fx_i = 0; $fx_j = 0',
|
|
891
980
|
' while ($fx_i -lt $fx_n -and $fx_j -lt $fx_m) {',
|
|
892
|
-
" if ($fx_la[$fx_i] -
|
|
981
|
+
" if ($fx_la[$fx_i] -ceq $fx_lb[$fx_j]) { $fx_ops += ,@('=', $fx_la[$fx_i], $fx_i, $fx_j); $fx_i++; $fx_j++ }",
|
|
893
982
|
" elseif ($fx_dp[(($fx_i + 1) * $fx_w) + $fx_j] -ge $fx_dp[($fx_i * $fx_w) + ($fx_j + 1)]) { $fx_ops += ,@('-', $fx_la[$fx_i], $fx_i, $fx_j); $fx_i++ }",
|
|
894
983
|
" else { $fx_ops += ,@('+', $fx_lb[$fx_j], $fx_i, $fx_j); $fx_j++ }",
|
|
895
984
|
' }',
|
|
@@ -907,8 +996,8 @@ const diff = (args) => {
|
|
|
907
996
|
' if ($fx_del.Count -gt 0) { $fx_a1 = $fx_del[0][1] + 1; $fx_a2 = $fx_del[$fx_del.Count - 1][1] + 1 }',
|
|
908
997
|
' if ($fx_add.Count -gt 0) { $fx_b1 = $fx_add[0][1] + 1; $fx_b2 = $fx_add[$fx_add.Count - 1][1] + 1 }',
|
|
909
998
|
' $fx_range = \'\'',
|
|
910
|
-
" if ($fx_del.Count -eq 0) { $fx_range = ([string]$
|
|
911
|
-
" elseif ($fx_add.Count -eq 0) { $fx_range = (fx-dr $fx_a1 $fx_a2) + 'd' + ([string]$
|
|
999
|
+
" if ($fx_del.Count -eq 0) { $fx_range = ([string]$fx_ops[$fx_start][2]) + 'a' + (fx-dr $fx_b1 $fx_b2) }",
|
|
1000
|
+
" elseif ($fx_add.Count -eq 0) { $fx_range = (fx-dr $fx_a1 $fx_a2) + 'd' + ([string]$fx_ops[$fx_start][3]) }",
|
|
912
1001
|
" else { $fx_range = (fx-dr $fx_a1 $fx_a2) + 'c' + (fx-dr $fx_b1 $fx_b2) }",
|
|
913
1002
|
' $fx_range',
|
|
914
1003
|
" foreach ($fx_d in $fx_del) { '< ' + $fx_d[0] }",
|
|
@@ -939,7 +1028,8 @@ function fileSpec(names, effects, options, handler) {
|
|
|
939
1028
|
}
|
|
940
1029
|
const INTERACTIVE = { reason: 'interactive prompt' };
|
|
941
1030
|
/** Destructive file commands migrated first (#130). Unspec'd handlers stay unchecked.
|
|
942
|
-
* cp
|
|
1031
|
+
* cp `-f` is always-on overwrite. mv `-f` retains safe same-volume regular-file
|
|
1032
|
+
* replacement and never overrides preservation limits or permissions. */
|
|
943
1033
|
export const specs = [
|
|
944
1034
|
fileSpec(['cp'], ['read', 'write'], [
|
|
945
1035
|
opt('r', undefined),
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trusted program, no user text interpolation. It only reads input and emits bytes.
|
|
3
|
+
*
|
|
4
|
+
* A leased stdin is an ownership signal, not archive data or host RPC. PowerShell
|
|
5
|
+
* holds it open; EOF/error aborts decoding. The parent PID check is best effort.
|
|
6
|
+
*
|
|
7
|
+
* Windows pipe stdout writes are synchronous and can block the event loop that
|
|
8
|
+
* observes ownership loss. Its fs writer instead keeps those writes off-thread.
|
|
9
|
+
* An abandoned write can still retain a libuv worker during process.exit cleanup,
|
|
10
|
+
* so the existing one-second shutdown fallback directly terminates this Windows
|
|
11
|
+
* helper (exit code 1). POSIX retains its asynchronous stdout socket and exit path.
|
|
12
|
+
*
|
|
13
|
+
* Keep commentary outside the embedded program: its base64 is nested inside
|
|
14
|
+
* generated PowerShell, where avoidable size can exceed Windows argv limits.
|
|
15
|
+
*/
|
|
16
|
+
export declare const GZIP_DECODER_SOURCE: string;
|
|
17
|
+
export declare function gzipNodeFunctions(pure: boolean): string;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { psStr } from '../registry.js';
|
|
2
|
+
import { nodeEngineRange } from '../runtime-support.js';
|
|
3
|
+
/**
|
|
4
|
+
* Trusted program, no user text interpolation. It only reads input and emits bytes.
|
|
5
|
+
*
|
|
6
|
+
* A leased stdin is an ownership signal, not archive data or host RPC. PowerShell
|
|
7
|
+
* holds it open; EOF/error aborts decoding. The parent PID check is best effort.
|
|
8
|
+
*
|
|
9
|
+
* Windows pipe stdout writes are synchronous and can block the event loop that
|
|
10
|
+
* observes ownership loss. Its fs writer instead keeps those writes off-thread.
|
|
11
|
+
* An abandoned write can still retain a libuv worker during process.exit cleanup,
|
|
12
|
+
* so the existing one-second shutdown fallback directly terminates this Windows
|
|
13
|
+
* helper (exit code 1). POSIX retains its asynchronous stdout socket and exit path.
|
|
14
|
+
*
|
|
15
|
+
* Keep commentary outside the embedded program: its base64 is nested inside
|
|
16
|
+
* generated PowerShell, where avoidable size can exceed Windows argv limits.
|
|
17
|
+
*/
|
|
18
|
+
export const GZIP_DECODER_SOURCE = String.raw `
|
|
19
|
+
const { createReadStream, createWriteStream } = require('node:fs');
|
|
20
|
+
const { createGunzip } = require('node:zlib');
|
|
21
|
+
const { Writable } = require('node:stream');
|
|
22
|
+
const { pipeline } = require('node:stream/promises');
|
|
23
|
+
(async () => {
|
|
24
|
+
const controller = new AbortController();
|
|
25
|
+
let finished = false;
|
|
26
|
+
let stopping = false;
|
|
27
|
+
const stopDecoder = () => {
|
|
28
|
+
if (finished || stopping) return;
|
|
29
|
+
stopping = true;
|
|
30
|
+
controller.abort();
|
|
31
|
+
setTimeout(() => {
|
|
32
|
+
if (process.platform === 'win32') process.kill(process.pid, 'SIGTERM');
|
|
33
|
+
else process.exit(1);
|
|
34
|
+
}, 1000).unref();
|
|
35
|
+
};
|
|
36
|
+
const leased = process.argv[4] === 'lease';
|
|
37
|
+
if (leased) {
|
|
38
|
+
process.stdin.on('end', stopDecoder);
|
|
39
|
+
process.stdin.on('error', stopDecoder);
|
|
40
|
+
process.stdin.resume();
|
|
41
|
+
}
|
|
42
|
+
const parent = Number(process.argv[3]);
|
|
43
|
+
const watcher = Number.isSafeInteger(parent) && parent > 0 ? setInterval(() => {
|
|
44
|
+
try { process.kill(parent, 0); }
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (error.code === 'ESRCH') {
|
|
47
|
+
clearInterval(watcher);
|
|
48
|
+
stopDecoder();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}, 250) : undefined;
|
|
52
|
+
watcher?.unref();
|
|
53
|
+
process.stderr.on('error', () => {});
|
|
54
|
+
try {
|
|
55
|
+
const minimum = ${JSON.stringify(nodeEngineRange.slice(2).split('.').map(Number))};
|
|
56
|
+
const actual = process.versions.node.split('.').map(Number);
|
|
57
|
+
let supported = actual.every(Number.isSafeInteger);
|
|
58
|
+
for (let i = 0; supported && i < 3; i++) {
|
|
59
|
+
if (actual[i] !== minimum[i]) { supported = actual[i] > minimum[i]; break; }
|
|
60
|
+
}
|
|
61
|
+
if (!supported) throw new Error('Node.js ${nodeEngineRange} is required for strict gzip decoding');
|
|
62
|
+
const path = Buffer.from(process.argv[1], 'base64').toString('utf8');
|
|
63
|
+
const mode = process.argv[2];
|
|
64
|
+
if (mode !== 'test' && mode !== 'stream') throw new Error('invalid decoder mode');
|
|
65
|
+
const sink = mode === 'test'
|
|
66
|
+
? new Writable({ write(chunk, encoding, next) { next(); } })
|
|
67
|
+
: process.platform === 'win32'
|
|
68
|
+
? createWriteStream(null, { fd: 1, autoClose: false })
|
|
69
|
+
: process.stdout;
|
|
70
|
+
await pipeline(createReadStream(path), createGunzip(), sink, { signal: controller.signal });
|
|
71
|
+
} catch (error) {
|
|
72
|
+
process.stderr.write('gzip decoder: ' + String(error.message).slice(0, 2048) + '\n');
|
|
73
|
+
process.exitCode = error.code === 'Z_DATA_ERROR' || error.code === 'Z_BUF_ERROR' ? 2 : 1;
|
|
74
|
+
} finally {
|
|
75
|
+
finished = true;
|
|
76
|
+
if (watcher) clearInterval(watcher);
|
|
77
|
+
if (leased) process.stdin.destroy();
|
|
78
|
+
}
|
|
79
|
+
})();
|
|
80
|
+
`;
|
|
81
|
+
export function gzipNodeFunctions(pure) {
|
|
82
|
+
const program = Buffer.from(GZIP_DECODER_SOURCE, 'utf8').toString('base64');
|
|
83
|
+
const prefix = `-e "eval(Buffer.from('${program}','base64').toString())" -- `;
|
|
84
|
+
const node = pure
|
|
85
|
+
? "(Get-Command node.exe -CommandType Application -ErrorAction Stop).Source"
|
|
86
|
+
: psStr(process.execPath);
|
|
87
|
+
return [
|
|
88
|
+
'function fx-gz-decode($src, $isBytes, $sink, $testOnly) {',
|
|
89
|
+
' $fx_raw = $null; $fx_process = $null',
|
|
90
|
+
' try {',
|
|
91
|
+
' if ($isBytes) {',
|
|
92
|
+
" $fx_inputPath = [IO.Path]::Combine([IO.Path]::GetTempPath(), 'fauxnix-gzip-input-' + [Guid]::NewGuid().ToString('N') + '.tmp')",
|
|
93
|
+
' $fx_raw = New-Object IO.FileStream($fx_inputPath, [IO.FileMode]::CreateNew, [IO.FileAccess]::ReadWrite, ([IO.FileShare]::Read -bor [IO.FileShare]::Delete), 65536, [IO.FileOptions]::DeleteOnClose)',
|
|
94
|
+
' $fx_raw.Write($src, 0, $src.Length); $fx_raw.Flush()',
|
|
95
|
+
' } else {',
|
|
96
|
+
' $fx_inputPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($src)',
|
|
97
|
+
' $fx_raw = [IO.File]::Open($fx_inputPath, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)',
|
|
98
|
+
' }',
|
|
99
|
+
' $fx_psi = New-Object Diagnostics.ProcessStartInfo',
|
|
100
|
+
' $fx_psi.FileName = ' + node,
|
|
101
|
+
' $fx_psi.UseShellExecute = $false; $fx_psi.CreateNoWindow = $true',
|
|
102
|
+
' $fx_psi.RedirectStandardOutput = $true; $fx_psi.RedirectStandardError = $true',
|
|
103
|
+
' $fx_psi.RedirectStandardInput = $true',
|
|
104
|
+
' $fx_psi.StandardErrorEncoding = New-Object Text.UTF8Encoding($false)',
|
|
105
|
+
" $fx_mode = 'stream'; if ($testOnly) { $fx_mode = 'test' }",
|
|
106
|
+
' $fx_psi.Arguments = ' + psStr(prefix) + " + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($fx_inputPath)) + ' ' + $fx_mode + ' ' + $PID + ' lease'",
|
|
107
|
+
' $fx_process = New-Object Diagnostics.Process',
|
|
108
|
+
' $fx_process.StartInfo = $fx_psi',
|
|
109
|
+
" if (-not $fx_process.Start()) { throw 'unable to start the Node gzip decoder' }",
|
|
110
|
+
' $fx_errors = $fx_process.StandardError.ReadToEndAsync()',
|
|
111
|
+
// Binary stdout never passes through PowerShell's text pipeline.
|
|
112
|
+
' try { $fx_process.StandardOutput.BaseStream.CopyTo($sink, 65536) }',
|
|
113
|
+
" catch { throw ('gzip output transfer failed: ' + $_.Exception.Message) }",
|
|
114
|
+
' $fx_process.WaitForExit()',
|
|
115
|
+
' $fx_errorText = $fx_errors.Result',
|
|
116
|
+
" if ($fx_process.ExitCode -eq 2) { throw ('not in gzip format: strict gzip decode failed: ' + $fx_errorText.Trim()) }",
|
|
117
|
+
" if ($fx_process.ExitCode -ne 0) { throw ('gzip decoder failed: ' + $fx_errorText.Trim()) }",
|
|
118
|
+
' } finally {',
|
|
119
|
+
' if ($null -ne $fx_process) {',
|
|
120
|
+
' try { if (-not $fx_process.HasExited) { $fx_process.Kill(); [void]$fx_process.WaitForExit(5000) } } catch {}',
|
|
121
|
+
' $fx_process.Dispose()',
|
|
122
|
+
' }',
|
|
123
|
+
' if ($null -ne $fx_raw) { $fx_raw.Dispose() }',
|
|
124
|
+
' }',
|
|
125
|
+
'}',
|
|
126
|
+
'function fx-gz-open($src, $isBytes) {',
|
|
127
|
+
" $fx_path = [IO.Path]::Combine([IO.Path]::GetTempPath(), 'fauxnix-gzip-stdout-' + [Guid]::NewGuid().ToString('N') + '.tmp')",
|
|
128
|
+
' $fx_decoded = New-Object IO.FileStream($fx_path, [IO.FileMode]::CreateNew, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None, 65536, [IO.FileOptions]::DeleteOnClose)',
|
|
129
|
+
' try {',
|
|
130
|
+
' fx-gz-decode $src $isBytes $fx_decoded $false',
|
|
131
|
+
' $fx_decoded.Position = 0',
|
|
132
|
+
' return $fx_decoded',
|
|
133
|
+
' } catch { $fx_decoded.Dispose(); throw }',
|
|
134
|
+
'}',
|
|
135
|
+
].join('\n');
|
|
136
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const PS_MOVE_REPLACE_FN: string;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { psStr } from '../registry.js';
|
|
2
|
+
// No user data is interpolated into C#. Paths are ordinary method arguments.
|
|
3
|
+
// Windows 8+ FILE_ID_INFO retains ReFS's full 128-bit identity; unsupported
|
|
4
|
+
// filesystems fail closed rather than falling back to a partial identifier.
|
|
5
|
+
const nativeSource = String.raw `
|
|
6
|
+
using System;
|
|
7
|
+
using System.ComponentModel;
|
|
8
|
+
using System.IO;
|
|
9
|
+
using System.Runtime.InteropServices;
|
|
10
|
+
using Microsoft.Win32.SafeHandles;
|
|
11
|
+
namespace Fauxnix {
|
|
12
|
+
public static class FileMoveV1 {
|
|
13
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
14
|
+
private struct FileIdInfo {
|
|
15
|
+
public ulong Volume;
|
|
16
|
+
public ulong Low;
|
|
17
|
+
public ulong High;
|
|
18
|
+
}
|
|
19
|
+
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
|
|
20
|
+
private static extern SafeFileHandle CreateFileW(string path, uint access,
|
|
21
|
+
uint share, IntPtr security, uint creation, uint flags, IntPtr template);
|
|
22
|
+
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
|
|
23
|
+
[return: MarshalAs(UnmanagedType.Bool)]
|
|
24
|
+
private static extern bool GetFileInformationByHandleEx(SafeFileHandle handle,
|
|
25
|
+
int infoClass, out FileIdInfo information, uint size);
|
|
26
|
+
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
|
|
27
|
+
[return: MarshalAs(UnmanagedType.Bool)]
|
|
28
|
+
private static extern bool MoveFileExW(string source, string destination, uint flags);
|
|
29
|
+
|
|
30
|
+
private static SafeFileHandle OpenIdentity(string path) {
|
|
31
|
+
// Metadata-only access, read/write/delete sharing, OPEN_EXISTING,
|
|
32
|
+
// FILE_FLAG_OPEN_REPARSE_POINT: never create or modify the inspected file.
|
|
33
|
+
SafeFileHandle handle = CreateFileW(path, 0, 7, IntPtr.Zero, 3, 0x00200000, IntPtr.Zero);
|
|
34
|
+
if (handle.IsInvalid) {
|
|
35
|
+
int error = Marshal.GetLastWin32Error();
|
|
36
|
+
handle.Dispose();
|
|
37
|
+
throw new Win32Exception(error);
|
|
38
|
+
}
|
|
39
|
+
return handle;
|
|
40
|
+
}
|
|
41
|
+
private static FileIdInfo Identity(SafeFileHandle handle) {
|
|
42
|
+
FileIdInfo info;
|
|
43
|
+
if (!GetFileInformationByHandleEx(handle, 18, out info, (uint)Marshal.SizeOf(typeof(FileIdInfo))))
|
|
44
|
+
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
45
|
+
return info;
|
|
46
|
+
}
|
|
47
|
+
public static void ReplaceRegular(string source, string destination) {
|
|
48
|
+
FileAttributes disallowed = FileAttributes.Directory | FileAttributes.ReparsePoint;
|
|
49
|
+
if ((File.GetAttributes(source) & disallowed) != 0 ||
|
|
50
|
+
(File.GetAttributes(destination) & disallowed) != 0)
|
|
51
|
+
throw new IOException("replacement of directories or reparse points is unsupported");
|
|
52
|
+
using (SafeFileHandle sourceHandle = OpenIdentity(source))
|
|
53
|
+
using (SafeFileHandle destinationHandle = OpenIdentity(destination)) {
|
|
54
|
+
FileIdInfo a = Identity(sourceHandle);
|
|
55
|
+
FileIdInfo b = Identity(destinationHandle);
|
|
56
|
+
if (a.Volume != b.Volume)
|
|
57
|
+
throw new IOException("cross-volume replacement is unsupported; both files retained");
|
|
58
|
+
if (a.Low == b.Low && a.High == b.High)
|
|
59
|
+
throw new IOException("source and destination are the same file");
|
|
60
|
+
}
|
|
61
|
+
// Close identity handles before replacement: an open destination can
|
|
62
|
+
// prevent Windows replacement even when opened with delete sharing.
|
|
63
|
+
// This preflight is deliberately not represented as a namespace lock.
|
|
64
|
+
// MOVEFILE_REPLACE_EXISTING only. No COPY_ALLOWED/predelete fallback.
|
|
65
|
+
if (!MoveFileExW(source, destination, 1)) {
|
|
66
|
+
int error = Marshal.GetLastWin32Error();
|
|
67
|
+
if (error == 17)
|
|
68
|
+
throw new IOException("cross-volume replacement is unsupported; both files retained");
|
|
69
|
+
throw new Win32Exception(error);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
`;
|
|
75
|
+
export const PS_MOVE_REPLACE_FN = [
|
|
76
|
+
'function fx-move-replace-file($source, $destination) {',
|
|
77
|
+
" if (-not ('Fauxnix.FileMoveV1' -as [type])) {",
|
|
78
|
+
' Add-Type -TypeDefinition ' + psStr(nativeSource) + ' -ErrorAction Stop',
|
|
79
|
+
' }',
|
|
80
|
+
' [Fauxnix.FileMoveV1]::ReplaceRegular($source, $destination)',
|
|
81
|
+
'}',
|
|
82
|
+
].join('\n');
|