@gjsify/fs 0.3.16 → 0.3.18

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/lib/esm/sync.js CHANGED
@@ -1,418 +1 @@
1
- import { decode, encodeUint8Array, getEncodingFromOptions } from "./encoding.js";
2
- import { normalizePath, tempDirPath } from "./utils.js";
3
- import { FSWatcher } from "./fs-watcher.js";
4
- import { Dirent } from "./dirent.js";
5
- import { BigIntStats, STAT_ATTRIBUTES, Stats } from "./stats.js";
6
- import { FileHandle } from "./file-handle.js";
7
- import { createNodeError as createNodeError$1, isNotFoundError } from "./errors.js";
8
- import GLib from "@girs/glib-2.0";
9
- import Gio from "@girs/gio-2.0";
10
- import { join } from "node:path";
11
- import { Buffer } from "node:buffer";
12
- import { existsSync } from "@gjsify/utils";
13
-
14
- //#region src/sync.ts
15
- function statSync(path, options) {
16
- const pathStr = normalizePath(path);
17
- try {
18
- const file = Gio.File.new_for_path(pathStr);
19
- const info = file.query_info(STAT_ATTRIBUTES, Gio.FileQueryInfoFlags.NONE, null);
20
- return options?.bigint ? new BigIntStats(info, pathStr) : new Stats(info, pathStr);
21
- } catch (err) {
22
- if (options?.throwIfNoEntry === false && isNotFoundError(err)) return undefined;
23
- throw createNodeError$1(err, "stat", pathStr);
24
- }
25
- }
26
- function lstatSync(path, options) {
27
- const pathStr = normalizePath(path);
28
- try {
29
- const file = Gio.File.new_for_path(pathStr);
30
- const info = file.query_info(STAT_ATTRIBUTES, Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS, null);
31
- return options?.bigint ? new BigIntStats(info, pathStr) : new Stats(info, pathStr);
32
- } catch (err) {
33
- if (options?.throwIfNoEntry === false && isNotFoundError(err)) return undefined;
34
- throw createNodeError$1(err, "lstat", pathStr);
35
- }
36
- }
37
- function readdirSync(path, options) {
38
- const pathStr = normalizePath(path);
39
- const file = Gio.File.new_for_path(pathStr);
40
- const enumerator = file.enumerate_children("standard::name,standard::type", Gio.FileQueryInfoFlags.NONE, null);
41
- const result = [];
42
- let info = enumerator.next_file(null);
43
- while (info !== null) {
44
- const childName = info.get_name();
45
- const childPath = join(pathStr, childName);
46
- if (options?.withFileTypes) {
47
- result.push(new Dirent(childPath, childName));
48
- } else {
49
- result.push(childName);
50
- }
51
- if (options?.recursive && info.get_file_type() === Gio.FileType.DIRECTORY) {
52
- const subEntries = readdirSync(childPath, options);
53
- for (const entry of subEntries) {
54
- if (typeof entry === "string") {
55
- result.push(join(childName, entry));
56
- } else {
57
- result.push(entry);
58
- }
59
- }
60
- }
61
- info = enumerator.next_file(null);
62
- }
63
- return result;
64
- }
65
- const MAX_SYMLINK_DEPTH = 40;
66
- function realpathSync(path) {
67
- const pathStr = normalizePath(path);
68
- let current = Gio.File.new_for_path(pathStr);
69
- let depth = 0;
70
- while (true) {
71
- const info = current.query_info("standard::is-symlink,standard::symlink-target", Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS, null);
72
- if (!info.get_is_symlink()) {
73
- return current.get_path();
74
- }
75
- const target = info.get_symlink_target();
76
- const parent = current.get_parent();
77
- current = parent ? parent.resolve_relative_path(target) : Gio.File.new_for_path(target);
78
- if (++depth > MAX_SYMLINK_DEPTH) {
79
- throw new Error(`ELOOP: too many levels of symbolic links, realpath '${pathStr}'`);
80
- }
81
- }
82
- }
83
- realpathSync.native = realpathSync;
84
- function symlinkSync(target, path, _type) {
85
- const pathStr = normalizePath(path);
86
- const targetStr = normalizePath(target);
87
- const file = Gio.File.new_for_path(pathStr);
88
- file.make_symbolic_link(targetStr, null);
89
- }
90
- function readFileSync(path, options = {
91
- encoding: null,
92
- flag: "r"
93
- }) {
94
- const pathStr = normalizePath(path);
95
- const file = Gio.File.new_for_path(pathStr);
96
- try {
97
- const [ok, data] = file.load_contents(null);
98
- if (!ok) {
99
- throw createNodeError$1(new Error("failed to read file"), "read", pathStr);
100
- }
101
- return encodeUint8Array(getEncodingFromOptions(options, "buffer"), data);
102
- } catch (err) {
103
- if (err.code && typeof err.code === "string") throw err;
104
- throw createNodeError$1(err, "read", pathStr);
105
- }
106
- }
107
- /**
108
- * Synchronous mkdir(2) - create a directory.
109
- * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
110
- * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
111
- * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
112
- */
113
- function mkdirSync(path, options) {
114
- let recursive = false;
115
- let mode = 511;
116
- if (typeof options === "object") {
117
- if (options?.recursive) recursive = options.recursive;
118
- if (options?.mode) mode = options.mode;
119
- } else {
120
- mode = options || 511;
121
- }
122
- path = normalizePath(path);
123
- if (typeof mode === "string") {
124
- throw new TypeError("mode as string is currently not supported!");
125
- }
126
- if (recursive) {
127
- return mkdirSyncRecursive(path, mode);
128
- }
129
- const file = Gio.File.new_for_path(path);
130
- try {
131
- file.make_directory(null);
132
- } catch (err) {
133
- throw createNodeError$1(err, "mkdir", path);
134
- }
135
- return undefined;
136
- }
137
- /**
138
- * Recursively creates directories, similar to `mkdir -p`.
139
- * Returns the first directory path created, or undefined if all directories already existed.
140
- */
141
- function mkdirSyncRecursive(pathStr, mode) {
142
- const file = Gio.File.new_for_path(pathStr);
143
- try {
144
- file.make_directory(null);
145
- return pathStr;
146
- } catch (err) {
147
- const gErr = err;
148
- if (gErr.code === Gio.IOErrorEnum.EXISTS) {
149
- return undefined;
150
- }
151
- if (gErr.code === Gio.IOErrorEnum.NOT_FOUND) {
152
- const parentPath = join(pathStr, "..");
153
- const resolvedParent = Gio.File.new_for_path(parentPath).get_path();
154
- if (resolvedParent === pathStr) {
155
- throw createNodeError$1(err, "mkdir", pathStr);
156
- }
157
- const firstCreated = mkdirSyncRecursive(resolvedParent, mode);
158
- const retryFile = Gio.File.new_for_path(pathStr);
159
- try {
160
- retryFile.make_directory(null);
161
- } catch (retryErr) {
162
- throw createNodeError$1(retryErr, "mkdir", pathStr);
163
- }
164
- return firstCreated ?? pathStr;
165
- }
166
- throw createNodeError$1(err, "mkdir", pathStr);
167
- }
168
- }
169
- /**
170
- * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`.
171
- *
172
- * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error
173
- * on Windows and an `ENOTDIR` error on POSIX.
174
- *
175
- * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`.
176
- * @since v0.1.21
177
- */
178
- function rmdirSync(path, _options) {
179
- const pathStr = normalizePath(path);
180
- const file = Gio.File.new_for_path(pathStr);
181
- try {
182
- const info = file.query_info("standard::type", Gio.FileQueryInfoFlags.NONE, null);
183
- if (info.get_file_type() !== Gio.FileType.DIRECTORY) {
184
- const err = Object.assign(new Error(), { code: 4 });
185
- throw createNodeError$1(err, "rmdir", pathStr);
186
- }
187
- const enumerator = file.enumerate_children("standard::name", Gio.FileQueryInfoFlags.NONE, null);
188
- if (enumerator.next_file(null) !== null) {
189
- const err = Object.assign(new Error(), { code: 5 });
190
- throw createNodeError$1(err, "rmdir", pathStr);
191
- }
192
- file.delete(null);
193
- } catch (err) {
194
- if (err.code && typeof err.code === "string") throw err;
195
- throw createNodeError$1(err, "rmdir", pathStr);
196
- }
197
- }
198
- function unlinkSync(path) {
199
- const pathStr = normalizePath(path);
200
- const file = Gio.File.new_for_path(pathStr);
201
- try {
202
- file.delete(null);
203
- } catch (err) {
204
- throw createNodeError$1(err, "unlink", pathStr);
205
- }
206
- }
207
- function writeFileSync(path, data) {
208
- GLib.file_set_contents(normalizePath(path), data);
209
- }
210
- function renameSync(oldPath, newPath) {
211
- const oldStr = normalizePath(oldPath);
212
- const newStr = normalizePath(newPath);
213
- const src = Gio.File.new_for_path(oldStr);
214
- const dest = Gio.File.new_for_path(newStr);
215
- try {
216
- src.move(dest, Gio.FileCopyFlags.OVERWRITE, null, null);
217
- } catch (err) {
218
- throw createNodeError$1(err, "rename", oldStr, newStr);
219
- }
220
- }
221
- function copyFileSync(src, dest, mode) {
222
- const srcStr = normalizePath(src);
223
- const destStr = normalizePath(dest);
224
- const srcFile = Gio.File.new_for_path(srcStr);
225
- const destFile = Gio.File.new_for_path(destStr);
226
- let flags = Gio.FileCopyFlags.NONE;
227
- if (mode && (mode & 1) === 0) {
228
- flags = Gio.FileCopyFlags.OVERWRITE;
229
- } else if (!mode) {
230
- flags = Gio.FileCopyFlags.OVERWRITE;
231
- }
232
- try {
233
- srcFile.copy(destFile, flags, null, null);
234
- } catch (err) {
235
- throw createNodeError$1(err, "copyfile", srcStr, destStr);
236
- }
237
- }
238
- function accessSync(path, mode) {
239
- const pathStr = normalizePath(path);
240
- const file = Gio.File.new_for_path(pathStr);
241
- try {
242
- const info = file.query_info("access::*", Gio.FileQueryInfoFlags.NONE, null);
243
- if (mode !== undefined && mode !== 0) {
244
- const permErr = {
245
- code: 14,
246
- message: `permission denied, access '${pathStr}'`
247
- };
248
- if (mode & 4 && !info.get_attribute_boolean("access::can-read")) {
249
- throw createNodeError$1(permErr, "access", pathStr);
250
- }
251
- if (mode & 2 && !info.get_attribute_boolean("access::can-write")) {
252
- throw createNodeError$1(permErr, "access", pathStr);
253
- }
254
- if (mode & 1 && !info.get_attribute_boolean("access::can-execute")) {
255
- throw createNodeError$1(permErr, "access", pathStr);
256
- }
257
- }
258
- } catch (err) {
259
- if (err.code && typeof err.code === "string") throw err;
260
- throw createNodeError$1(err, "access", pathStr);
261
- }
262
- }
263
- function appendFileSync(path, data, options) {
264
- const pathStr = normalizePath(path);
265
- const file = Gio.File.new_for_path(pathStr);
266
- let bytes;
267
- if (typeof data === "string") {
268
- bytes = new TextEncoder().encode(data);
269
- } else {
270
- bytes = data;
271
- }
272
- try {
273
- const stream = file.append_to(Gio.FileCreateFlags.NONE, null);
274
- if (bytes.length > 0) {
275
- stream.write_bytes(new GLib.Bytes(bytes), null);
276
- }
277
- stream.close(null);
278
- } catch (err) {
279
- throw createNodeError$1(err, "appendfile", pathStr);
280
- }
281
- }
282
- function readlinkSync(path, options) {
283
- const pathStr = normalizePath(path);
284
- const file = Gio.File.new_for_path(pathStr);
285
- try {
286
- const info = file.query_info("standard::symlink-target", Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS, null);
287
- const target = info.get_symlink_target();
288
- if (!target) {
289
- throw Object.assign(new Error(`EINVAL: invalid argument, readlink '${pathStr}'`), {
290
- code: "EINVAL",
291
- errno: -22,
292
- syscall: "readlink",
293
- path: pathStr
294
- });
295
- }
296
- const encoding = typeof options === "string" ? options : options?.encoding;
297
- if (encoding === "buffer") {
298
- return Buffer.from(target);
299
- }
300
- return target;
301
- } catch (err) {
302
- if (typeof err.code === "string") throw err;
303
- throw createNodeError$1(err, "readlink", pathStr);
304
- }
305
- }
306
- function linkSync(existingPath, newPath) {
307
- const existingStr = normalizePath(existingPath);
308
- const newStr = normalizePath(newPath);
309
- const result = GLib.spawn_command_line_sync(`ln ${existingStr} ${newStr}`);
310
- if (!result[0]) {
311
- throw Object.assign(new Error(`EPERM: operation not permitted, link '${existingStr}' -> '${newStr}'`), {
312
- code: "EPERM",
313
- errno: -1,
314
- syscall: "link",
315
- path: existingStr,
316
- dest: newStr
317
- });
318
- }
319
- }
320
- function truncateSync(path, len) {
321
- const pathStr = normalizePath(path);
322
- const file = Gio.File.new_for_path(pathStr);
323
- try {
324
- const stream = file.replace(null, false, Gio.FileCreateFlags.NONE, null);
325
- if (len && len > 0) {
326
- const [, data] = file.load_contents(null);
327
- const truncated = data.slice(0, len);
328
- if (truncated.length > 0) {
329
- stream.write_bytes(new GLib.Bytes(truncated), null);
330
- }
331
- }
332
- stream.close(null);
333
- } catch (err) {
334
- throw createNodeError$1(err, "truncate", pathStr);
335
- }
336
- }
337
- function chmodSync(path, mode) {
338
- const pathStr = normalizePath(path);
339
- const modeNum = typeof mode === "string" ? parseInt(mode, 8) : mode;
340
- const result = GLib.spawn_command_line_sync(`chmod ${modeNum.toString(8)} ${pathStr}`);
341
- if (!result[0]) {
342
- throw Object.assign(new Error(`EPERM: operation not permitted, chmod '${pathStr}'`), {
343
- code: "EPERM",
344
- errno: -1,
345
- syscall: "chmod",
346
- path: pathStr
347
- });
348
- }
349
- }
350
- function chownSync(path, uid, gid) {
351
- const pathStr = normalizePath(path);
352
- const result = GLib.spawn_command_line_sync(`chown ${uid}:${gid} ${pathStr}`);
353
- if (!result[0]) {
354
- throw Object.assign(new Error(`EPERM: operation not permitted, chown '${pathStr}'`), {
355
- code: "EPERM",
356
- errno: -1,
357
- syscall: "chown",
358
- path: pathStr
359
- });
360
- }
361
- }
362
- function watch(filename, options, listener) {
363
- return new FSWatcher(normalizePath(filename), options, listener);
364
- }
365
- function openSync(path, flags, mode) {
366
- return new FileHandle({
367
- path,
368
- flags,
369
- mode
370
- });
371
- }
372
- function mkdtempSync(prefix, options) {
373
- const encoding = getEncodingFromOptions(options);
374
- const path = tempDirPath(prefix);
375
- mkdirSync(path, {
376
- recursive: false,
377
- mode: 511
378
- });
379
- return decode(path, encoding);
380
- }
381
- /**
382
- * Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`.
383
- * @since v14.14.0
384
- */
385
- function rmSync(path, options) {
386
- const pathStr = normalizePath(path);
387
- const file = Gio.File.new_for_path(pathStr);
388
- const recursive = options?.recursive || false;
389
- const force = options?.force || false;
390
- let dirent;
391
- try {
392
- dirent = new Dirent(pathStr);
393
- } catch (err) {
394
- if (force && isNotFoundError(err)) return;
395
- throw createNodeError$1(err, "rm", path);
396
- }
397
- if (dirent.isDirectory()) {
398
- const childFiles = readdirSync(path, { withFileTypes: true });
399
- if (!recursive && childFiles.length) {
400
- const err = Object.assign(new Error(), { code: 5 });
401
- throw createNodeError$1(err, "rm", path);
402
- }
403
- for (const childFile of childFiles) {
404
- if (typeof childFile !== "string") {
405
- rmSync(join(pathStr, childFile.name), options);
406
- }
407
- }
408
- }
409
- try {
410
- file.delete(null);
411
- } catch (err) {
412
- if (force && isNotFoundError(err)) return;
413
- throw createNodeError$1(err, "rm", path);
414
- }
415
- }
416
-
417
- //#endregion
418
- export { accessSync, appendFileSync, chmodSync, chownSync, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, symlinkSync, truncateSync, unlinkSync, watch, writeFileSync };
1
+ import{decode as e,encodeUint8Array as t,getEncodingFromOptions as n}from"./encoding.js";import{normalizePath as r,tempDirPath as i}from"./utils.js";import{FSWatcher as a}from"./fs-watcher.js";import{Dirent as o}from"./dirent.js";import{BigIntStats as s,STAT_ATTRIBUTES as c,Stats as l}from"./stats.js";import{FileHandle as u}from"./file-handle.js";import{createNodeError as d,isNotFoundError as f}from"./errors.js";import p from"@girs/glib-2.0";import m from"@girs/gio-2.0";import{join as h}from"node:path";import{Buffer as g}from"node:buffer";import{existsSync as _}from"@gjsify/utils";function v(e,t){let n=r(e);try{let e=m.File.new_for_path(n).query_info(c,m.FileQueryInfoFlags.NONE,null);return t?.bigint?new s(e,n):new l(e,n)}catch(e){if(t?.throwIfNoEntry===!1&&f(e))return;throw d(e,`stat`,n)}}function y(e,t){let n=r(e);try{let e=m.File.new_for_path(n).query_info(c,m.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null);return t?.bigint?new s(e,n):new l(e,n)}catch(e){if(t?.throwIfNoEntry===!1&&f(e))return;throw d(e,`lstat`,n)}}function b(e,t){let n=r(e),i=m.File.new_for_path(n).enumerate_children(`standard::name,standard::type`,m.FileQueryInfoFlags.NONE,null),a=[],s=i.next_file(null);for(;s!==null;){let e=s.get_name(),r=h(n,e);if(t?.withFileTypes?a.push(new o(r,e)):a.push(e),t?.recursive&&s.get_file_type()===m.FileType.DIRECTORY){let n=b(r,t);for(let t of n)typeof t==`string`?a.push(h(e,t)):a.push(t)}s=i.next_file(null)}return a}function x(e){let t=r(e),n=m.File.new_for_path(t),i=0;for(;;){let e=n.query_info(`standard::is-symlink,standard::symlink-target`,m.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null);if(!e.get_is_symlink())return n.get_path();let r=e.get_symlink_target(),a=n.get_parent();if(n=a?a.resolve_relative_path(r):m.File.new_for_path(r),++i>40)throw Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`)}}x.native=x;function S(e,t,n){let i=r(t),a=r(e);m.File.new_for_path(i).make_symbolic_link(a,null)}function C(e,i={encoding:null,flag:`r`}){let a=r(e),o=m.File.new_for_path(a);try{let[e,r]=o.load_contents(null);if(!e)throw d(Error(`failed to read file`),`read`,a);return t(n(i,`buffer`),r)}catch(e){throw e.code&&typeof e.code==`string`?e:d(e,`read`,a)}}function w(e,t){let n=!1,i=511;if(typeof t==`object`?(t?.recursive&&(n=t.recursive),t?.mode&&(i=t.mode)):i=t||511,e=r(e),typeof i==`string`)throw TypeError(`mode as string is currently not supported!`);if(n)return T(e,i);let a=m.File.new_for_path(e);try{a.make_directory(null)}catch(t){throw d(t,`mkdir`,e)}}function T(e,t){let n=m.File.new_for_path(e);try{return n.make_directory(null),e}catch(n){let r=n;if(r.code===m.IOErrorEnum.EXISTS)return;if(r.code===m.IOErrorEnum.NOT_FOUND){let r=h(e,`..`),i=m.File.new_for_path(r).get_path();if(i===e)throw d(n,`mkdir`,e);let a=T(i,t),o=m.File.new_for_path(e);try{o.make_directory(null)}catch(t){throw d(t,`mkdir`,e)}return a??e}throw d(n,`mkdir`,e)}}function E(e,t){let n=r(e),i=m.File.new_for_path(n);try{if(i.query_info(`standard::type`,m.FileQueryInfoFlags.NONE,null).get_file_type()!==m.FileType.DIRECTORY)throw d(Object.assign(Error(),{code:4}),`rmdir`,n);if(i.enumerate_children(`standard::name`,m.FileQueryInfoFlags.NONE,null).next_file(null)!==null)throw d(Object.assign(Error(),{code:5}),`rmdir`,n);i.delete(null)}catch(e){throw e.code&&typeof e.code==`string`?e:d(e,`rmdir`,n)}}function D(e){let t=r(e),n=m.File.new_for_path(t);try{n.delete(null)}catch(e){throw d(e,`unlink`,t)}}function O(e,t){p.file_set_contents(r(e),t)}function k(e,t){let n=r(e),i=r(t),a=m.File.new_for_path(n),o=m.File.new_for_path(i);try{a.move(o,m.FileCopyFlags.OVERWRITE,null,null)}catch(e){throw d(e,`rename`,n,i)}}function A(e,t,n){let i=r(e),a=r(t),o=m.File.new_for_path(i),s=m.File.new_for_path(a),c=m.FileCopyFlags.NONE;n&&!(n&1)?c=m.FileCopyFlags.OVERWRITE:n||(c=m.FileCopyFlags.OVERWRITE);try{o.copy(s,c,null,null)}catch(e){throw d(e,`copyfile`,i,a)}}function j(e,t){let n=r(e),i=m.File.new_for_path(n);try{let e=i.query_info(`access::*`,m.FileQueryInfoFlags.NONE,null);if(t!==void 0&&t!==0){let r={code:14,message:`permission denied, access '${n}'`};if(t&4&&!e.get_attribute_boolean(`access::can-read`)||t&2&&!e.get_attribute_boolean(`access::can-write`)||t&1&&!e.get_attribute_boolean(`access::can-execute`))throw d(r,`access`,n)}}catch(e){throw e.code&&typeof e.code==`string`?e:d(e,`access`,n)}}function M(e,t,n){let i=r(e),a=m.File.new_for_path(i),o;o=typeof t==`string`?new TextEncoder().encode(t):t;try{let e=a.append_to(m.FileCreateFlags.NONE,null);o.length>0&&e.write_bytes(new p.Bytes(o),null),e.close(null)}catch(e){throw d(e,`appendfile`,i)}}function N(e,t){let n=r(e),i=m.File.new_for_path(n);try{let e=i.query_info(`standard::symlink-target`,m.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null).get_symlink_target();if(!e)throw Object.assign(Error(`EINVAL: invalid argument, readlink '${n}'`),{code:`EINVAL`,errno:-22,syscall:`readlink`,path:n});return(typeof t==`string`?t:t?.encoding)===`buffer`?g.from(e):e}catch(e){throw typeof e.code==`string`?e:d(e,`readlink`,n)}}function P(e,t){let n=r(e),i=r(t);if(!p.spawn_command_line_sync(`ln ${n} ${i}`)[0])throw Object.assign(Error(`EPERM: operation not permitted, link '${n}' -> '${i}'`),{code:`EPERM`,errno:-1,syscall:`link`,path:n,dest:i})}function F(e,t){let n=r(e),i=m.File.new_for_path(n);try{let e=i.replace(null,!1,m.FileCreateFlags.NONE,null);if(t&&t>0){let[,n]=i.load_contents(null),r=n.slice(0,t);r.length>0&&e.write_bytes(new p.Bytes(r),null)}e.close(null)}catch(e){throw d(e,`truncate`,n)}}function I(e,t){let n=r(e),i=typeof t==`string`?parseInt(t,8):t;if(!p.spawn_command_line_sync(`chmod ${i.toString(8)} ${n}`)[0])throw Object.assign(Error(`EPERM: operation not permitted, chmod '${n}'`),{code:`EPERM`,errno:-1,syscall:`chmod`,path:n})}function L(e,t,n){let i=r(e);if(!p.spawn_command_line_sync(`chown ${t}:${n} ${i}`)[0])throw Object.assign(Error(`EPERM: operation not permitted, chown '${i}'`),{code:`EPERM`,errno:-1,syscall:`chown`,path:i})}function R(e,t,n){return new a(r(e),t,n)}function z(e,t,n){return new u({path:e,flags:t,mode:n})}function B(t,r){let a=n(r),o=i(t);return w(o,{recursive:!1,mode:511}),e(o,a)}function V(e,t){let n=r(e),i=m.File.new_for_path(n),a=t?.recursive||!1,s=t?.force||!1,c;try{c=new o(n)}catch(t){if(s&&f(t))return;throw d(t,`rm`,e)}if(c.isDirectory()){let r=b(e,{withFileTypes:!0});if(!a&&r.length)throw d(Object.assign(Error(),{code:5}),`rm`,e);for(let e of r)typeof e!=`string`&&V(h(n,e.name),t)}try{i.delete(null)}catch(t){if(s&&f(t))return;throw d(t,`rm`,e)}}export{j as accessSync,M as appendFileSync,I as chmodSync,L as chownSync,A as copyFileSync,_ as existsSync,P as linkSync,y as lstatSync,w as mkdirSync,B as mkdtempSync,z as openSync,C as readFileSync,b as readdirSync,N as readlinkSync,x as realpathSync,k as renameSync,V as rmSync,E as rmdirSync,v as statSync,S as symlinkSync,F as truncateSync,D as unlinkSync,R as watch,O as writeFileSync};
@@ -1,6 +1 @@
1
- import "./encoding-option.js";
2
- import "./file-read-options.js";
3
- import "./file-read-result.js";
4
- import "./flag-and-open-mode.js";
5
- import "./open-flags.js";
6
- import "./read-options.js";
1
+ import"./encoding-option.js";import"./file-read-options.js";import"./file-read-result.js";import"./flag-and-open-mode.js";import"./open-flags.js";import"./read-options.js";
package/lib/esm/utils.js CHANGED
@@ -1,23 +1 @@
1
- import { existsSync } from "./sync.js";
2
- import { URL as URL$1, fileURLToPath } from "node:url";
3
-
4
- //#region src/utils.ts
5
- function normalizePath(path) {
6
- if (path instanceof URL || path instanceof URL$1) return fileURLToPath(path);
7
- if (typeof path === "string") return path;
8
- return path.toString();
9
- }
10
- const CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
11
- function randomName() {
12
- return [...Array(6)].map(() => CHARS[Math.floor(Math.random() * CHARS.length)]).join("");
13
- }
14
- function tempDirPath(prefix) {
15
- let path;
16
- do {
17
- path = prefix + randomName();
18
- } while (existsSync(path));
19
- return path;
20
- }
21
-
22
- //#endregion
23
- export { normalizePath, randomName, tempDirPath };
1
+ import{existsSync as e}from"./sync.js";import{URL as t,fileURLToPath as n}from"node:url";function r(e){return e instanceof URL||e instanceof t?n(e):typeof e==`string`?e:e.toString()}function i(){return[...[,,,,,,]].map(()=>`0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`[Math.floor(Math.random()*62)]).join(``)}function a(t){let n;do n=t+i();while(e(n));return n}export{r as normalizePath,i as randomName,a as tempDirPath};
package/lib/esm/utimes.js CHANGED
@@ -1,51 +1 @@
1
- import { normalizePath } from "./utils.js";
2
- import GLib from "@girs/glib-2.0";
3
- import Gio from "@girs/gio-2.0";
4
-
5
- //#region src/utimes.ts
6
- function toGLibDateTime(t) {
7
- const ms = t instanceof Date ? t.getTime() : typeof t === "bigint" ? Number(t) : typeof t === "string" ? Date.parse(t) : t * 1e3;
8
- return GLib.DateTime.new_from_unix_utc(Math.floor(ms / 1e3));
9
- }
10
- function setTimestamps(path, atime, mtime, flags) {
11
- const file = Gio.File.new_for_path(path);
12
- const info = new Gio.FileInfo();
13
- info.set_modification_date_time(toGLibDateTime(mtime));
14
- info.set_access_date_time(toGLibDateTime(atime));
15
- file.set_attributes_from_info(info, flags, null);
16
- }
17
- function utimesSync(path, atime, mtime) {
18
- setTimestamps(normalizePath(path), atime, mtime, Gio.FileQueryInfoFlags.NONE);
19
- }
20
- function utimes(path, atime, mtime, callback) {
21
- Promise.resolve().then(() => utimesSync(path, atime, mtime)).then(() => callback(null), callback);
22
- }
23
- async function utimesAsync(path, atime, mtime) {
24
- utimesSync(path, atime, mtime);
25
- }
26
- function lutimesSync(path, atime, mtime) {
27
- setTimestamps(normalizePath(path), atime, mtime, Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS);
28
- }
29
- function lutimes(path, atime, mtime, callback) {
30
- Promise.resolve().then(() => lutimesSync(path, atime, mtime)).then(() => callback(null), callback);
31
- }
32
- async function lutimesAsync(path, atime, mtime) {
33
- lutimesSync(path, atime, mtime);
34
- }
35
- function lchownSync(path, uid, gid) {
36
- GLib.spawn_command_line_sync(`chown -h ${uid}:${gid} ${normalizePath(path)}`);
37
- }
38
- function lchown(path, uid, gid, callback) {
39
- Promise.resolve().then(() => lchownSync(path, uid, gid)).then(() => callback(null), callback);
40
- }
41
- async function lchownAsync(path, uid, gid) {
42
- lchownSync(path, uid, gid);
43
- }
44
- function lchmodSync(_path, _mode) {}
45
- function lchmod(_path, _mode, callback) {
46
- callback(null);
47
- }
48
- async function lchmodAsync(_path, _mode) {}
49
-
50
- //#endregion
51
- export { lchmod, lchmodAsync, lchmodSync, lchown, lchownAsync, lchownSync, lutimes, lutimesAsync, lutimesSync, utimes, utimesAsync, utimesSync };
1
+ import{normalizePath as e}from"./utils.js";import t from"@girs/glib-2.0";import n from"@girs/gio-2.0";function r(e){let n=e instanceof Date?e.getTime():typeof e==`bigint`?Number(e):typeof e==`string`?Date.parse(e):e*1e3;return t.DateTime.new_from_unix_utc(Math.floor(n/1e3))}function i(e,t,i,a){let o=n.File.new_for_path(e),s=new n.FileInfo;s.set_modification_date_time(r(i)),s.set_access_date_time(r(t)),o.set_attributes_from_info(s,a,null)}function a(t,r,a){i(e(t),r,a,n.FileQueryInfoFlags.NONE)}function o(e,t,n,r){Promise.resolve().then(()=>a(e,t,n)).then(()=>r(null),r)}async function s(e,t,n){a(e,t,n)}function c(t,r,a){i(e(t),r,a,n.FileQueryInfoFlags.NOFOLLOW_SYMLINKS)}function l(e,t,n,r){Promise.resolve().then(()=>c(e,t,n)).then(()=>r(null),r)}async function u(e,t,n){c(e,t,n)}function d(n,r,i){t.spawn_command_line_sync(`chown -h ${r}:${i} ${e(n)}`)}function f(e,t,n,r){Promise.resolve().then(()=>d(e,t,n)).then(()=>r(null),r)}async function p(e,t,n){d(e,t,n)}function m(e,t){}function h(e,t,n){n(null)}async function g(e,t){}export{h as lchmod,g as lchmodAsync,m as lchmodSync,f as lchown,p as lchownAsync,d as lchownSync,l as lutimes,u as lutimesAsync,c as lutimesSync,o as utimes,s as utimesAsync,a as utimesSync};
@@ -1,101 +1 @@
1
- import { normalizePath } from "./utils.js";
2
- import { close, open, write } from "./callback.js";
3
- import { Writable } from "node:stream";
4
-
5
- //#region src/write-stream.ts
6
- const kIsPerformingIO = Symbol("kIsPerformingIO");
7
- const kIoDone = Symbol("kIoDone");
8
- function toPathIfFileURL(fileURLOrPath) {
9
- return normalizePath(fileURLOrPath);
10
- }
11
- var WriteStream = class extends Writable {
12
- /**
13
- * Closes `writeStream`. Optionally accepts a
14
- * callback that will be executed once the `writeStream`is closed.
15
- * @since v0.9.4
16
- */
17
- close(callback, err = null) {
18
- if (!this.fd) {
19
- callback(err);
20
- } else {
21
- close(this.fd, (er) => {
22
- callback(er || err);
23
- });
24
- this.fd = null;
25
- }
26
- }
27
- /**
28
- * The number of bytes written so far. Does not include data that is still queued
29
- * for writing.
30
- * @since v0.4.7
31
- */
32
- bytesWritten = 0;
33
- /**
34
- * The path to the file the stream is writing to as specified in the first
35
- * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a
36
- * `Buffer`.
37
- * @since v0.1.93
38
- */
39
- path;
40
- /**
41
- * This property is `true` if the underlying file has not been opened yet,
42
- * i.e. before the `'ready'` event is emitted.
43
- * @since v11.2.0
44
- */
45
- pending;
46
- fd = null;
47
- flags = "w";
48
- mode = 438;
49
- pos = 0;
50
- [kIsPerformingIO] = false;
51
- constructor(path, opts = {}) {
52
- super(opts);
53
- this.path = toPathIfFileURL(path);
54
- if (opts.encoding) {
55
- this.setDefaultEncoding(opts.encoding);
56
- }
57
- }
58
- _construct(callback) {
59
- open(this.path.toString(), this.flags, this.mode, (err, fd) => {
60
- if (err) {
61
- callback(err);
62
- return;
63
- }
64
- this.fd = fd;
65
- callback();
66
- this.emit("open", this.fd);
67
- this.emit("ready");
68
- });
69
- }
70
- _write(data, _encoding, cb) {
71
- this[kIsPerformingIO] = true;
72
- write(this.fd, data, 0, data.length, this.pos, (er, bytes) => {
73
- this[kIsPerformingIO] = false;
74
- if (this.destroyed) {
75
- cb(er);
76
- return this.emit(kIoDone, er);
77
- }
78
- if (er) {
79
- return cb(er);
80
- }
81
- this.bytesWritten += bytes;
82
- cb();
83
- });
84
- if (this.pos !== undefined) {
85
- this.pos += data.length;
86
- }
87
- }
88
- _destroy(err, cb) {
89
- if (this[kIsPerformingIO]) {
90
- this.once(kIoDone, (er) => this.close(cb, err || er));
91
- } else {
92
- this.close(cb, err);
93
- }
94
- }
95
- };
96
- function createWriteStream(path, opts) {
97
- return new WriteStream(path, opts);
98
- }
99
-
100
- //#endregion
101
- export { WriteStream, createWriteStream, toPathIfFileURL };
1
+ import{normalizePath as e}from"./utils.js";import{close as t,open as n,write as r}from"./callback.js";import{Writable as i}from"node:stream";const a=Symbol(`kIsPerformingIO`),o=Symbol(`kIoDone`);function s(t){return e(t)}var c=class extends i{close(e,n=null){this.fd?(t(this.fd,t=>{e(t||n)}),this.fd=null):e(n)}bytesWritten=0;path;pending;fd=null;flags=`w`;mode=438;pos=0;[a]=!1;constructor(e,t={}){super(t),this.path=s(e),t.encoding&&this.setDefaultEncoding(t.encoding)}_construct(e){n(this.path.toString(),this.flags,this.mode,(t,n)=>{if(t){e(t);return}this.fd=n,e(),this.emit(`open`,this.fd),this.emit(`ready`)})}_write(e,t,n){this[a]=!0,r(this.fd,e,0,e.length,this.pos,(e,t)=>{if(this[a]=!1,this.destroyed)return n(e),this.emit(o,e);if(e)return n(e);this.bytesWritten+=t,n()}),this.pos!==void 0&&(this.pos+=e.length)}_destroy(e,t){this[a]?this.once(o,n=>this.close(t,e||n)):this.close(t,e)}};function l(e,t){return new c(e,t)}export{c as WriteStream,l as createWriteStream,s as toPathIfFileURL};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gjsify/fs",
3
- "version": "0.3.16",
3
+ "version": "0.3.18",
4
4
  "description": "Node.js fs module for Gjs",
5
5
  "module": "lib/esm/index.js",
6
6
  "types": "lib/types/index.d.ts",
@@ -34,18 +34,18 @@
34
34
  "fs"
35
35
  ],
36
36
  "devDependencies": {
37
- "@gjsify/cli": "^0.3.16",
38
- "@gjsify/unit": "^0.3.16",
39
- "@types/node": "^25.6.0",
37
+ "@gjsify/cli": "^0.3.18",
38
+ "@gjsify/unit": "^0.3.18",
39
+ "@types/node": "^25.6.2",
40
40
  "typescript": "^6.0.3"
41
41
  },
42
42
  "dependencies": {
43
- "@girs/gio-2.0": "2.88.0-4.0.0-rc.9",
44
- "@girs/glib-2.0": "2.88.0-4.0.0-rc.9",
45
- "@gjsify/buffer": "^0.3.16",
46
- "@gjsify/events": "^0.3.16",
47
- "@gjsify/stream": "^0.3.16",
48
- "@gjsify/url": "^0.3.16",
49
- "@gjsify/utils": "^0.3.16"
43
+ "@girs/gio-2.0": "2.88.0-4.0.0-rc.14",
44
+ "@girs/glib-2.0": "2.88.0-4.0.0-rc.14",
45
+ "@gjsify/buffer": "^0.3.18",
46
+ "@gjsify/events": "^0.3.18",
47
+ "@gjsify/stream": "^0.3.18",
48
+ "@gjsify/url": "^0.3.18",
49
+ "@gjsify/utils": "^0.3.18"
50
50
  }
51
51
  }