Repository navigation
Expand file tree
/
Copy pathpromises.js
More file actions
881 lines (774 loc) · 25.1 KB
/
Copy pathpromises.js
File metadata and controls
881 lines (774 loc) · 25.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
/**
* @module fs.promises
*
* * This module enables interacting with the file system in a way modeled on
* standard POSIX functions.
*
* The Application Sandbox restricts access to the file system.
*
* iOS Application Sandboxing has a set of rules that limits access to the file
* system. Apps can only access files in their own sandboxed home directory.
*
* | Directory | Description |
* | --- | --- |
* | `Documents` | The app’s sandboxed documents directory. The contents of this directory are backed up by iTunes and may be set as accessible to the user via iTunes when `UIFileSharingEnabled` is set to `true` in the application's `info.plist`. |
* | `Library` | The app’s sandboxed library directory. The contents of this directory are synchronized via iTunes (except the `Library/Caches` subdirectory, see below), but never exposed to the user. |
* | `Library/Caches` | The app’s sandboxed caches directory. The contents of this directory are not synchronized via iTunes and may be deleted by the system at any time. It's a good place to store data which provides a good offline-first experience for the user. |
* | `Library/Preferences` | The app’s sandboxed preferences directory. The contents of this directory are synchronized via iTunes. Its purpose is to be used by the Settings app. Avoid creating your own files in this directory. |
* | `tmp` | The app’s sandboxed temporary directory. The contents of this directory are not synchronized via iTunes and may be deleted by the system at any time. Although, it's recommended that you delete data that is not necessary anymore manually to minimize the space your app takes up on the file system. Use this directory to store data that is only useful during the app runtime. |
*
* Example usage:
* ```js
* import fs from 'oro:fs/promises'
* ```
*/
import ipc from '../ipc.js'
import { Buffer } from '../buffer.js'
import { Dir, Dirent, sortDirectoryEntries } from './dir.js'
import { DirectoryHandle, FileHandle } from './handle.js'
import { ReadStream, WriteStream } from './stream.js'
import * as constants from './constants.js'
import { Watcher } from './watcher.js'
import { Stats } from './stats.js'
import bookmarks from './bookmarks.js'
import fds from './fds.js'
import * as exports from './promises.js'
// re-exports
export {
bookmarks,
constants,
Dir,
DirectoryHandle,
Dirent,
fds,
FileHandle,
ReadStream,
Stats,
Watcher,
WriteStream
}
const kFileDescriptor = Symbol.for('oro.runtime.fs.web.FileDescriptor')
function normalizePath (path) {
if (path instanceof URL) {
if (path.origin === globalThis.location.origin) {
return normalizePath(path.href)
}
return null
}
if (URL.canParse(path)) {
const url = new URL(path)
if (url.origin === globalThis.location.origin) {
path = `./${url.pathname.slice(1)}`
}
}
return path
}
/**
* @typedef {Uint8Array|Int8Array} TypedArray
* @ignore
*/
async function visit (path, options, callback) {
if (typeof options === 'function') {
callback = options
options = {}
}
const { flags, flag, mode } = options || {}
path = normalizePath(path)
// just visit `FileHandle`, without closing if given
if (path instanceof FileHandle) {
return await callback(path)
} else if (path?.fd) {
return await callback(FileHandle.from(path.fd))
} else if (path && typeof path === 'object' && kFileDescriptor in path) {
return await callback(FileHandle.from(path))
}
const handle = await FileHandle.open(path, flags || flag, mode, options)
const value = await callback(handle)
await handle.close(options)
return value
}
/**
* Asynchronously check access a file.
* @see {@link https://nodejs.org/dist/latest-v20.x/docs/api/fs.html#fspromisesaccesspath-mode}
* @param {string|Buffer|URL} path
* @param {number=} [mode]
* @param {object=} [options]
*/
export async function access (path, mode, options) {
path = normalizePath(path)
return await FileHandle.access(path, mode, options)
}
/**
* @see {@link https://nodejs.org/api/fs.html#fspromiseschmodpath-mode}
* @param {string | Buffer | URL} path
* @param {number} mode
* @returns {Promise<void>}
*/
export async function chmod (path, mode) {
path = normalizePath(path)
if (typeof mode !== 'number') {
throw new TypeError(
`The argument 'mode' must be a 32-bit unsigned integer or an octal string. Received ${mode}`
)
}
if (mode < 0 || !Number.isInteger(mode)) {
throw new RangeError(
`The value of 'mode" is out of range. It must be an integer. Received ${mode}`
)
}
const result = await ipc.send('fs.chmod', { mode, path })
if (result.err) {
throw result.err
}
}
/**
* Changes ownership of file or directory at `path` with `uid` and `gid`.
* @param {string} path
* @param {number} uid
* @param {number} gid
* @return {Promise}
*/
export async function chown (path, uid, gid) {
path = normalizePath(path)
if (typeof path !== 'string') {
throw new TypeError("The argument 'path' must be a string")
}
if (!Number.isInteger(uid)) {
throw new TypeError("The argument 'uid' must be an integer")
}
if (!Number.isInteger(gid)) {
throw new TypeError("The argument 'gid' must be an integer")
}
const result = await ipc.send('fs.chown', { path, uid, gid })
if (result.err) {
throw result.err
}
}
/**
* Asynchronously copies `src` to `dest` calling `callback` upon success or error.
* @param {string} src - The source file path.
* @param {string} dest - The destination file path.
* @param {number} flags - Modifiers for copy operation.
* @return {Promise}
*/
export async function copyFile (src, dest, flags = 0) {
src = normalizePath(src)
dest = normalizePath(dest)
if (typeof src !== 'string') {
throw new TypeError("The argument 'src' must be a string")
}
if (typeof dest !== 'string') {
throw new TypeError("The argument 'dest' must be a string")
}
if (!Number.isInteger(flags)) {
throw new TypeError("The argument 'flags' must be an integer")
}
const result = await ipc.send('fs.copyFile', { src, dest, flags })
if (result.err) {
throw result.err
}
}
/**
* Changes ownership of a symbolic link at `path` with `uid` and `gid`.
* @param {string} path
* @param {number} uid
* @param {number} gid
* @return {Promise}
*/
export async function lchown (path, uid, gid) {
path = normalizePath(path)
if (typeof path !== 'string') {
throw new TypeError("The argument 'src' must be a string")
}
if (!Number.isInteger(uid)) {
throw new TypeError("The argument 'uid' must be an integer")
}
if (!Number.isInteger(gid)) {
throw new TypeError("The argument 'gid' must be an integer")
}
const result = await ipc.send('fs.lchown', { path, uid, gid })
if (result.err) {
throw result.err
}
}
/**
* Changes permissions of a symbolic link at `path`.
*
* On platforms that do not implement `lchmod`, the native backend may treat
* this as a no-op or reject the request with a platform-specific error.
* @param {string|Buffer|URL} path
* @param {number} mode
* @returns {Promise<void>}
*/
export async function lchmod (path, mode) {
path = normalizePath(path)
if (typeof path !== 'string') {
throw new TypeError("The argument 'path' must be a string")
}
if (typeof mode !== 'number') {
throw new TypeError("The argument 'mode' must be a number")
}
const result = await ipc.send('fs.lchmod', { path, mode })
if (result.err) throw result.err
}
/**
* Creates a hard link to `dest` from `src`.
* @param {string} src
* @param {string} dest
* @return {Promise}
*/
export async function link (src, dest) {
src = normalizePath(src)
dest = normalizePath(dest)
if (typeof src !== 'string') {
throw new TypeError("The argument 'src' must be a string")
}
if (typeof dest !== 'string') {
throw new TypeError("The argument 'dest' must be a string")
}
const result = await ipc.send('fs.link', { src, dest })
if (result.err) {
throw result.err
}
}
/**
* Asynchronously creates a directory.
*
* @param {string} path - The path to create
* @param {object} [options] - The optional options argument can be an integer specifying mode (permission and sticky bits), or an object with a mode property and a recursive property indicating whether parent directories should be created. Calling fs.mkdir() when path is a directory that exists results in an error only when recursive is false.
* @param {boolean} [options.recursive=false] - Recursively create missing path segments.
* @param {number} [options.mode=0o777] - Set the mode of directory, or missing path segments when recursive is true.
* @return {Promise} - Upon success, fulfills with undefined if recursive is false, or the first directory path created if recursive is true.
*/
export async function mkdir (path, options = {}) {
const mode = options.mode ?? 0o777
const recursive = Boolean(options.recursive)
path = normalizePath(path)
if (typeof mode !== 'number') {
throw new TypeError('mode must be a number.')
}
if (mode < 0 || !Number.isInteger(mode)) {
throw new RangeError('mode must be a positive finite number.')
}
const result = await ipc.request('fs.mkdir', { mode, path, recursive })
if (result.err) {
throw result.err
}
}
/** Create a unique temporary directory */
export async function mkdtemp (prefix, options) {
prefix = normalizePath(prefix)
if (typeof prefix !== 'string') throw new TypeError('prefix must be a string')
const result = await ipc.send('fs.mkdtemp', { prefix })
if (result.err) throw result.err
const path = result.data.path
const enc = typeof options === 'string' ? options : options?.encoding
if (enc === 'buffer') return Buffer.from(path)
return path
}
/**
* Asynchronously open a file.
* @see {@link https://nodejs.org/api/fs.html#fspromisesopenpath-flags-mode }
*
* @param {string | Buffer | URL} path
* @param {string=} flags - default: 'r'
* @param {number=} mode - default: 0o666
* @return {Promise<FileHandle>}
*/
export async function open (path, flags = 'r', mode = 0o666) {
path = normalizePath(path)
return await FileHandle.open(path, flags, mode)
}
/**
* @see {@link https://nodejs.org/api/fs.html#fspromisesopendirpath-options}
* @param {string | Buffer | URL} path
* @param {object=} [options]
* @param {string=} [options.encoding = 'utf8']
* @param {number=} [options.bufferSize = 32]
* @return {Promise<Dir>}
*/
export async function opendir (path, options) {
path = normalizePath(path)
const handle = await DirectoryHandle.open(path, options)
return new Dir(handle, options)
}
/**
* @see {@link https://nodejs.org/dist/latest-v20.x/docs/api/fs.html#fspromisesreaddirpath-options}
* @param {string|Buffer|URL} path
* @param {object=} [options]
* @param {string=} [options.encoding = 'utf8']
* @param {boolean=} [options.withFileTypes = false]
* @return {Promise<(string|Dirent)[]>}
*/
export async function readdir (path, options) {
path = normalizePath(path)
options = {
entries: DirectoryHandle.MAX_ENTRIES,
withFileTypes: false,
...options
}
const entries = []
const handle = await DirectoryHandle.open(path, options)
const dir = new Dir(handle, options)
for await (const entry of dir.entries(options)) {
entries.push(entry)
}
if (!dir.closing && !dir.closed) {
try {
await dir.close()
} catch (err) {
if (!/not opened/i.test(err.message)) {
console.warn(err)
}
}
}
return entries.sort(sortDirectoryEntries)
}
/**
* @see {@link https://nodejs.org/dist/latest-v20.x/docs/api/fs.html#fspromisesreadfilepath-options}
* @param {string} path
* @param {object=} [options]
* @param {(string|null)=} [options.encoding = null]
* @param {string=} [options.flag = 'r']
* @param {AbortSignal|undefined} [options.signal]
* @return {Promise<Buffer | string>}
*/
export async function readFile (path, options) {
if (typeof options === 'string') {
options = { encoding: options }
}
path = normalizePath(path)
options = { flags: 'r', ...options }
return await visit(path, options, async (handle) => {
return await handle.readFile(options)
})
}
/**
* Reads link at `path`
* @param {string} path
* @return {Promise<string>}
*/
export async function readlink (path, options) {
path = normalizePath(path)
if (typeof path !== 'string') {
throw new TypeError("The argument 'path' must be a string")
}
const result = await ipc.send('fs.readlink', { path })
if (result.err) {
throw result.err
}
const target = result.data.path
const enc = typeof options === 'string' ? options : options?.encoding
if (enc === 'buffer') return Buffer.from(target)
return target
}
/**
* Computes real path for `path`
* @param {string} path
* @return {Promise<string>}
*/
export async function realpath (path) {
path = normalizePath(path)
if (typeof path !== 'string') {
throw new TypeError("The argument 'path' must be a string")
}
const result = await ipc.send('fs.realpath', { path })
if (result.err) {
throw result.err
}
return result.data.path
}
/**
* Renames file or directory at `src` to `dest`.
* @param {string} src
* @param {string} dest
* @return {Promise}
*/
export async function rename (src, dest) {
src = normalizePath(src)
dest = normalizePath(dest)
if (typeof src !== 'string') {
throw new TypeError("The argument 'path' must be a string")
}
if (typeof dest !== 'string') {
throw new TypeError("The argument 'path' must be a string")
}
const result = await ipc.send('fs.rename', { src, dest })
if (result.err) {
throw result.err
}
}
/**
* Removes directory at `path`.
* @param {string} path
* @return {Promise}
*/
export async function rmdir (path) {
path = normalizePath(path)
if (typeof path !== 'string') {
throw new TypeError("The argument 'path' must be a string")
}
const result = await ipc.send('fs.rmdir', { path })
if (result.err) {
throw result.err
}
}
/**
* Get the stats of a file
* @see {@link https://nodejs.org/api/fs.html#fspromisesstatpath-options}
* @param {string | Buffer | URL} path
* @param {object=} [options]
* @param {boolean=} [options.bigint = false]
* @return {Promise<Stats>}
*/
export async function stat (path, options) {
path = normalizePath(path)
if (typeof path !== 'string') {
return await visit(path, {}, async (handle) => handle.stat(options))
}
// Metadata lookup must not require opening the file for reading.
const result = await ipc.request('fs.stat', { path }, options)
if (result.err) throw result.err
return Stats.from(result.data, Boolean(options?.bigint))
}
/**
* Get the stats of an open file descriptor.
* @see {@link https://nodejs.org/api/fs.html#fspromisesfstatfd-options}
* @param {number|FileHandle} fd
* @param {object=} [options]
* @param {boolean=} [options.bigint = false]
* @return {Promise<Stats>}
*/
export async function fstat (fd, options) {
const handle = FileHandle.from(fd)
return await handle.stat(options)
}
/**
* Get the stats of a symbolic link.
* @see {@link https://nodejs.org/api/fs.html#fspromiseslstatpath-options}
* @param {string | Buffer | URL} path
* @param {object=} [options]
* @param {boolean=} [options.bigint = false]
* @return {Promise<Stats>}
*/
export async function lstat (path, options) {
path = normalizePath(path)
if (typeof path !== 'string') {
return await visit(path, {}, async (handle) => handle.lstat(options))
}
// Opening the path would follow symlinks and reject unreadable targets.
const result = await ipc.request('fs.lstat', { path }, options)
if (result.err) throw result.err
return Stats.from(result.data, Boolean(options?.bigint))
}
/**
* Creates a symlink of `src` at `dest`.
* @param {string} src
* @param {string} dest
* @return {Promise}
*/
export async function symlink (src, dest, type = null) {
let flags = 0
src = normalizePath(src)
dest = normalizePath(dest)
if (typeof src !== 'string') {
throw new TypeError("The argument 'src' must be a string")
}
if (typeof dest !== 'string') {
throw new TypeError("The argument 'dest' must be a string")
}
if (!type) {
type = 'file'
}
if (type === 'file') {
flags = 0
} else if (type === 'dir') {
flags = constants.UV_FS_SYMLINK_DIR
} else if (type === 'junction') {
flags = constants.UV_FS_SYMLINK_JUNCTION
}
const result = await ipc.send('fs.symlink', { src, dest, flags })
if (result.err) {
throw result.err
}
}
/**
* Update atime/mtime for a path (promises)
*/
export async function utimes (path, atime, mtime) {
path = normalizePath(path)
const a = atime instanceof Date ? atime.getTime() / 1000 : Number(atime)
const m = mtime instanceof Date ? mtime.getTime() / 1000 : Number(mtime)
if (!Number.isFinite(a) || !Number.isFinite(m)) {
throw new TypeError('time must be a number or Date')
}
const result = await ipc.send('fs.utimes', { path, atime: a, mtime: m })
if (result.err) throw result.err
}
/**
* Update atime/mtime for an fd (promises)
*/
export async function futimes (fd, atime, mtime) {
const handle = FileHandle.from(fd)
const a = atime instanceof Date ? atime.getTime() / 1000 : Number(atime)
const m = mtime instanceof Date ? mtime.getTime() / 1000 : Number(mtime)
if (!Number.isFinite(a) || !Number.isFinite(m)) {
throw new TypeError('time must be a number or Date')
}
const result = await ipc.send('fs.futimes', {
id: handle.id,
atime: a,
mtime: m
})
if (result.err) throw result.err
}
/** Update atime/mtime for a symlink without following it (promises) */
export async function lutimes (path, atime, mtime) {
path = normalizePath(path)
const a = atime instanceof Date ? atime.getTime() / 1000 : Number(atime)
const m = mtime instanceof Date ? mtime.getTime() / 1000 : Number(mtime)
if (!Number.isFinite(a) || !Number.isFinite(m)) {
throw new TypeError('time must be a number or Date')
}
const result = await ipc.send('fs.lutimes', { path, atime: a, mtime: m })
if (result.err) throw result.err
}
/**
* Unlinks (removes) file at `path`.
* @param {string} path
* @return {Promise}
*/
export async function unlink (path) {
path = normalizePath(path)
if (typeof path !== 'string') {
throw new TypeError("The argument 'path' must be a string")
}
const result = await ipc.send('fs.unlink', { path })
if (result.err) {
throw result.err
}
}
/**
* @see {@link https://nodejs.org/dist/latest-v20.x/docs/api/fs.html#fspromiseswritefilefile-data-options}
* @param {string|Buffer|URL|FileHandle} path - filename or FileHandle
* @param {string|Buffer|Array|DataView|TypedArray} data
* @param {object=} [options]
* @param {(string|null)=} [options.encoding = 'utf8']
* @param {number=} [options.mode = 0o666]
* @param {string=} [options.flag = 'w']
* @param {AbortSignal|undefined} [options.signal]
* @return {Promise<void>}
*/
export async function writeFile (path, data, options) {
if (typeof options === 'string') {
options = { encoding: options }
}
path = normalizePath(path)
options = { flag: 'w', mode: 0o666, ...options }
return await visit(path, options, async (handle) => {
return await handle.writeFile(data, options)
})
}
/** Vector write: write multiple buffers to a FileHandle or fd */
export async function writev (fdOrHandle, buffers, position = null) {
const handle =
fdOrHandle instanceof FileHandle ? fdOrHandle : FileHandle.from(fdOrHandle)
return await handle.writev(buffers, position)
}
/** Vector read: read into multiple buffers from a FileHandle or fd */
export async function readv (fdOrHandle, buffers, position = null) {
const handle =
fdOrHandle instanceof FileHandle ? fdOrHandle : FileHandle.from(fdOrHandle)
return await handle.readv(buffers, position)
}
/** Truncate file */
export async function truncate (path, len = 0) {
const handle = await FileHandle.open(path, 'r+')
try {
await handle.truncate(len)
} finally {
await handle.close().catch(() => {})
}
}
/** Append data */
export async function appendFile (path, data, options) {
if (typeof options === 'string') options = { encoding: options }
options = { flag: 'a', mode: 0o666, ...options }
return await writeFile(path, data, options)
}
/** Remove file or directory */
export async function rm (path, options) {
options = { recursive: false, force: false, ...options }
const { recursive, force } = options
try {
const stats = await lstat(path)
if (stats.isDirectory()) {
if (!recursive) throw new Error('EISDIR: recursive not set')
const entries = await readdir(path, { withFileTypes: true })
for (const entry of entries) {
const name = typeof entry === 'string' ? entry : entry.name
await rm(joinPath(path, name), { recursive, force })
}
await (await import('./promises.js')).rmdir(path)
} else {
await (await import('./promises.js')).unlink(path)
}
} catch (err) {
if (
!(
force &&
/exist|enoent|not found|no such file/i.test(err.message || String(err))
)
) {
throw err
}
}
}
async function pathExists (path) {
try {
await lstat(path)
return true
} catch {
return false
}
}
function createAlreadyExistsError (path) {
const err = new Error(`EEXIST: file already exists, cp '${path}'`)
err.code = 'EEXIST'
err.errno = 'EEXIST'
err.path = path
err.syscall = 'cp'
return err
}
/**
* Copy file or directory.
* Options:
* - recursive: copy directories recursively
* - dereference: follow symlinks (default true). When false, copies symlinks as symlinks
* - force: overwrite if destination exists; when false and errorOnExist is false, leaves dest untouched
* - errorOnExist: if true and destination exists, error (when force is false)
* - preserveTimestamps: set atime/mtime on dest to match src (files)
* - preserveMode: apply src mode (chmod) to dest
* - preserveOwner: attempt to apply src uid/gid (chown) to dest (may be ignored by platform; may require privileges)
* - filter: function (src, dest) => boolean|Promise<boolean> to include/exclude entries
*/
export async function cp (src, dest, options) {
options = {
recursive: false,
dereference: true,
force: false,
preserveTimestamps: false,
filter: null,
errorOnExist: false,
preserveMode: false,
preserveOwner: false,
...options
}
const {
recursive,
dereference,
force,
preserveTimestamps,
filter,
errorOnExist,
preserveMode,
preserveOwner
} = options
const st = await stat(src)
if (st.isDirectory()) {
if (!recursive) throw new Error('EISDIR: recursive not set')
await (await import('./promises.js')).mkdir(dest, { recursive: true })
if (preserveMode) {
try {
const st = await stat(src)
await (await import('./promises.js')).chmod(dest, st.mode & 0o777)
} catch {}
}
if (preserveOwner) {
try {
const st = await stat(src)
await (await import('./promises.js')).chown(dest, st.uid, st.gid)
} catch {}
}
const entries = await readdir(src, { withFileTypes: true })
for (const entry of entries) {
const name = typeof entry === 'string' ? entry : entry.name
const s = joinPath(src, name)
const d = joinPath(dest, name)
if (typeof filter === 'function') {
if (!(await filter(s, d))) continue
}
await cp(s, d, {
recursive,
dereference,
force,
preserveTimestamps,
filter,
errorOnExist,
preserveMode,
preserveOwner
})
}
} else {
if (!dereference) {
try {
const lst = await lstat(src)
if (lst.isSymbolicLink()) {
const destinationExists = await pathExists(dest)
if (destinationExists && !force) {
if (errorOnExist) throw createAlreadyExistsError(dest)
return
}
if (destinationExists) {
await rm(dest, { recursive: true, force: true })
}
const target = await readlink(src)
await (await import('./promises.js')).symlink(target, dest)
return
}
} catch {}
}
if (!force && (await pathExists(dest))) {
if (errorOnExist) throw createAlreadyExistsError(dest)
return
}
await (await import('./promises.js')).copyFile(src, dest, 0)
if (preserveMode) {
try {
const st = await stat(src)
await (await import('./promises.js')).chmod(dest, st.mode & 0o777)
} catch {}
}
if (preserveOwner) {
try {
const st = await stat(src)
await (await import('./promises.js')).chown(dest, st.uid, st.gid)
} catch {}
}
if (preserveTimestamps) {
try {
const srcStat = await stat(src)
await (
await import('./promises.js')
).utimes(dest, srcStat.atimeMs / 1000, srcStat.mtimeMs / 1000)
} catch {}
}
}
}
/**
* Watch for changes at `path` calling `callback`
* @param {string}
* @param {function|object=} [options]
* @param {string=} [options.encoding = 'utf8']
* @param {AbortSignal=} [options.signal]
* @return {Watcher}
*/
export function watch (path, options) {
path = normalizePath(path)
return new Watcher(path, options)
}
export default exports
function joinPath (base, name) {
const sep = base.includes('\\') ? '\\' : '/'
return base.endsWith(sep) ? base + name : base + sep + name
}