Repository navigation
Expand file tree
/
Copy pathvm.plugins.file.node.js
More file actions
414 lines (409 loc) · 17 KB
/
Copy pathvm.plugins.file.node.js
File metadata and controls
414 lines (409 loc) · 17 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
"use strict";
/*
* Copyright (c) 2013-2025 Vanessa Freudenberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
var fs = require("fs");
var path = require("path");
var previousWriteBuffers = [
"", // stdin, unused
"", // stdout
"", // stderr
];
var openFileDescriptors = [];
Object.extend(Squeak.Primitives.prototype,
'FilePlugin', {
primitiveDirectoryCreate: function(argCount) {
var dirNameObj = this.stackNonInteger(0);
if (!this.success) return false;
var dirName = dirNameObj.bytesAsString();
try {
fs.mkdirSync(dirName);
} catch(e) {
// an existing directory counts as created (same as the browser backend's
// dirCreate): Cuis re-creates each path component when checking a path,
// and failing here aborts its whole startup
var isDir = false;
if (e.code === "EEXIST") {
try { isDir = fs.statSync(dirName).isDirectory(); } catch(e2) {}
}
if (!isDir) {
console.error("Failed to create directory: " + dirName);
return false;
}
}
return this.popNIfOK(argCount); // Answer self
},
primitiveDirectoryDelete: function(argCount) {
var dirNameObj = this.stackNonInteger(0);
if (!this.success) return false;
var dirName = dirName.bytesAsString();
try {
fs.rmdirSync(dirName);
} catch(e) {
console.error("Failed to delete directory: " + dirName);
return false;
}
return this.popNIfOK(argCount); // Answer self
},
primitiveDirectoryDelimitor: function(argCount) {
var delimitor = this.emulateMac ? ':' : path.sep;
return this.popNandPushIfOK(argCount + 1, this.charFromInt(delimitor.charCodeAt(0)));
},
primitiveDirectoryEntry: function(argCount) {
// look up ONE entry by name (answer nil if absent). Without this primitive an
// image checking "does /some/dir exist?" falls back to enumerating the parent,
// and a Cuis image that cannot see its own directories retries creating them
// forever at startup.
var fileNameObj = this.stackNonInteger(0),
dirNameObj = this.stackNonInteger(1);
if (!this.success) return false;
var fileName = fileNameObj.bytesAsString(),
dirName = dirNameObj.bytesAsString(),
fullName = fileName === "/" && dirName === "/" ? "/"
: dirName + (dirName[dirName.length - 1] === path.sep ? "" : path.sep) + fileName;
var entry = null;
try {
var stats;
try { stats = fs.statSync(fullName); }
catch(e) { stats = fs.lstatSync(fullName); } // dangling symlink: report the link
entry = [
fileName, // Name
Math.floor((stats.ctimeMs - Squeak.Epoch) / 1000), // Creation time (seconds sinds Smalltalk epoch)
Math.floor((stats.mtimeMs - Squeak.Epoch) / 1000), // Modification time (seconds sinds Smalltalk epoch)
stats.isDirectory(), // Directory flag
stats.isFile() ? stats.size : 0 // File size
];
} catch(e) {
// no such entry: answer nil (only a missing PARENT is a primitive failure)
}
this.popNandPushIfOK(argCount + 1, this.makeStObject(entry)); // entry or nil
return true;
},
primitiveDirectoryLookup: function(argCount) {
var index = this.stackInteger(0),
dirNameObj = this.stackNonInteger(1);
if (!this.success) return false;
var dirName = dirNameObj.bytesAsString();
var entry = null;
try {
var dirEntries = fs.readdirSync(dirName);
if (index < 1 || index > dirEntries.length) return false;
var dirEntry = dirEntries[index - 1];
var stats;
try {
stats = fs.statSync(dirName + path.sep + dirEntry);
} catch(e) {
// an unstattable entry (e.g. a dangling symlink like /.VolumeIcon.icns)
// must not end the whole enumeration: to the image a failed lookup means
// "no more entries", so one bad file would hide the rest of the directory
try { stats = fs.lstatSync(dirName + path.sep + dirEntry); }
catch(e2) { stats = null; }
}
entry = [
dirEntry, // Name
stats ? Math.floor((stats.ctimeMs - Squeak.Epoch) / 1000) : 0, // Creation time (seconds sinds Smalltalk epoch)
stats ? Math.floor((stats.mtimeMs - Squeak.Epoch) / 1000) : 0, // Modification time (seconds sinds Smalltalk epoch)
stats ? stats.isDirectory() : false, // Directory flag
stats && stats.isFile() ? stats.size : 0 // File size
];
} catch(e) {
if (e.errno !== -20) {
console.error("Failed to read directory: " + dirName);
}
return false;
}
this.popNandPushIfOK(argCount + 1, this.makeStObject(entry)); // entry or nil
return true;
},
primitiveFileStdioHandles: function(argCount) {
var handles = [
this.makeFileHandle('/dev/stdin', 0, false),
this.makeFileHandle('/dev/stdout', 1, true),
this.makeFileHandle('/dev/stderr', 2, true),
];
this.popNandPushIfOK(argCount + 1, this.makeStArray(handles));
return true;
},
primitiveFileDescriptorType: function(argCount) {
// Pharo probes stdio at startup: fileDescriptorIsAvailable: is
// (fileDescriptorType: fd) between: 1 and: 3 (1=tty, 2=pipe, 3=file).
// Under Node stdio is real — report stdin/stdout/stderr as pipes.
var fd = this.stackInteger(0);
if (!this.success) return false;
var type = (fd >= 0 && fd <= 2) ? 2 : 0;
return this.popNandPushIfOK(argCount + 1, type);
},
primitiveGetWorkingDirectory: function(argCount) {
// see vm.plugins.file.browser.js — Pharo/Cuis read the cwd at startup
var cwd = Squeak.workingDirectory || Squeak.vmPath || "/";
return this.popNandPushIfOK(argCount + 1, this.makeStString(this.filenameToSqueak(cwd)));
},
primitiveSetWorkingDirectory: function(argCount) {
var dirNameObj = this.stackNonInteger(0);
if (!this.success) return false;
Squeak.workingDirectory = this.filenameFromSqueak(dirNameObj.bytesAsString());
return this.popNIfOK(argCount);
},
primitiveFileOpen: function(argCount) {
var writeFlag = this.stackBoolean(0),
fileNameObj = this.stackNonInteger(1);
if (!this.success) return false;
var fileName = fileNameObj.bytesAsString();
var fd;
try {
fd = fs.openSync(fileName, writeFlag ? "a+" : "r");
if (fd < 0) return false;
} catch(e) {
console.error("Failed to open file: " + fileName);
return false;
}
var handle = this.makeFileHandle(fileName, fd, writeFlag);
openFileDescriptors.push(fd);
this.popNandPushIfOK(argCount + 1, handle);
return true;
},
primitiveFileSize: function(argCount) {
var handle = this.stackNonInteger(0);
if (!this.success) return false;
var fileSize;
try {
fileSize = fs.fstatSync(handle.fd).size;
} catch(e) {
console.error("Failed to get file size");
return false;
}
this.popNandPushIfOK(argCount + 1, this.makeLargeIfNeeded(fileSize));
return true;
},
primitiveFileGetPosition: function(argCount) {
var handle = this.stackNonInteger(0);
if (!this.success) return false;
this.popNandPushIfOK(argCount + 1, this.makeLargeIfNeeded(handle.filePos));
return true;
},
primitiveFileSetPosition: function(argCount) {
var pos = this.stackPos32BitInt(0),
handle = this.stackNonInteger(1);
if (!this.success) return false;
handle.filePos = pos;
return this.popNIfOK(argCount); // Answer self
},
primitiveFileAtEnd: function(argCount) {
var handle = this.stackNonInteger(0);
if (!this.success) return false;
var fileAtEnd;
try {
fileAtEnd = handle.filePos >= fs.fstatSync(handle.fd).size;
} catch(e) {
console.error("Failed to decide if at end of file");
return false;
}
this.popNandPushIfOK(argCount + 1, this.makeStObject(fileAtEnd));
return true;
},
primitiveDirectorySetMacTypeAndCreator: function(argCount) {
return this.popNIfOK(argCount); // Answer self
},
primitiveFileRead: function(argCount) {
var count = this.stackInteger(0),
startIndex = this.stackInteger(1) - 1, // make zero based
arrayObj = this.stackNonInteger(2),
handle = this.stackNonInteger(3);
if (!this.success || !arrayObj.isWordsOrBytes()) return false;
if (!count) return this.popNandPushIfOK(argCount + 1, 0);
var array = arrayObj.bytes;
if (!array) {
array = arrayObj.wordsAsUint8Array();
startIndex *= 4;
count *= 4;
}
if (startIndex < 0 || startIndex + count > array.length)
return false;
if (handle.fd === 0) {
console.warn("File reading on stdin not implemented yet");
return false;
}
var bytesRead;
try {
bytesRead = fs.readSync(handle.fd, array, startIndex, count, handle.filePos);
handle.filePos += bytesRead;
} catch(e) {
console.error("Failed to read from file");
return false;
}
count = arrayObj.bytes ? bytesRead : bytesRead >> 2; // words
this.popNandPushIfOK(argCount + 1, count);
return true;
},
primitiveFileWrite: function(argCount) {
var count = this.stackInteger(0),
startIndex = this.stackInteger(1) - 1, // make zero based
arrayObj = this.stackNonInteger(2),
handle = this.stackNonInteger(3);
if (!this.success || !handle.fileWrite) return false;
if (!count) return this.popNandPushIfOK(argCount + 1, 0);
var array = arrayObj.bytes;
if (!array) {
array = arrayObj.wordsAsUint8Array();
startIndex *= 4;
count *= 4;
}
if (!array) return false;
if (startIndex < 0 || startIndex + count > array.length)
return false;
var bytesWritten;
if (handle.fd === 1 || handle.fd === 2) {
var logger = handle.fd === 1 ? console.log : console.error;
var buffer = array.slice(startIndex, startIndex + count);
while (count > 0 && buffer.length > 0) {
var linefeedIndex = buffer.indexOf(10);
if (linefeedIndex >= 0) {
logger(previousWriteBuffers[handle.fd] + String.fromCharCode.apply(null, buffer.slice(0, linefeedIndex)));
previousWriteBuffers[handle.fd] = "";
buffer = buffer.slice(linefeedIndex + 1);
bytesWritten += linefeedIndex + 1; // incl. the linefeed character
count -= linefeedIndex + 1;
handle.filePos += linefeedIndex + 1;
} else {
previousWriteBuffers[handle.fd] += String.fromCharCode.apply(null, buffer);
bytesWritten += buffer.length;
count -= buffer.length;
handle.filePos += buffer.length;
}
}
} else {
try {
bytesWritten = fs.writeSync(handle.fd, array, startIndex, count, handle.filePos);
handle.filePos += bytesWritten;
} catch(e) {
console.error("Failed to write to file");
return false;
}
}
if (!arrayObj.bytes) bytesWritten = bytesWritten >> 2; // words
this.popNandPushIfOK(argCount + 1, bytesWritten);
return true;
},
primitiveFileFlush: function(argCount) {
var handle = this.stackNonInteger(0);
if (!this.success) return false;
if (handle.fd === 1 || handle.fd === 2) {
var logger = handle.fd === 1 ? console.log : console.error;
logger(previousWriteBuffers[handle.fd]);
previousWriteBuffers[handle.fd] = "";
} else {
try {
fs.fsyncSync(handle.fd);
} catch(e) {
console.error("Failed to flush file");
return false;
}
}
return this.popNIfOK(argCount); // Answer self
},
primitiveFileTruncate: function(argCount) {
var pos = this.stackPos32BitInt(0),
handle = this.stackNonInteger(1);
if (!this.success || !handle.fileWrite) return false;
try {
var fileSize = fs.fstatSync(handle.fd).size;
if (fileSize > pos) {
fs.ftruncateSync(handle.fd, pos);
if (handle.filePos > pos) handle.filePos = pos;
}
} catch(e) {
console.error("Failed to truncate file");
return false;
}
return this.popNIfOK(argCount); // Answer self
},
primitiveFileClose: function(argCount) {
var handle = this.stackNonInteger(0);
if (!this.success) return false;
try {
fs.closeSync(handle.fd);
openFileDescriptors = openFileDescriptors.filter(function(fd) { return fd !== handle.fd; });
} catch(e) {
console.error("Failed to close file");
return false;
}
return this.popNIfOK(argCount); // Answer self
},
primitiveFileRename: function(argCount) {
var oldNameObj = this.stackNonInteger(1),
newNameObj = this.stackNonInteger(0);
if (!this.success) return false;
var oldName = oldNameObj.bytesAsString(),
newName = newNameObj.bytesAsString();
try {
fs.renameSync(oldName, newName);
} catch(e) {
console.error("Failed to rename file from: " + oldName + " to: " + newName);
return false;
}
return this.popNIfOK(argCount); // Answer self
},
primitiveFileDelete: function(argCount) {
var fileNameObj = this.stackNonInteger(0);
if (!this.success) return false;
var fileName = fileNameObj.bytesAsString();
try {
fs.unlinkSync(fileName);
} catch(e) {
console.error("Failed to delete file: " + fileName);
return false;
}
return this.popNIfOK(argCount); // Answer self
},
makeFileHandle: function(filename, fd, writeFlag) {
var handle = this.makeStString("squeakjs:" + filename);
handle.fd = fd; // shared between handles
handle.fileWrite = writeFlag; // specific to this handle
handle.filePos = 0; // specific to this handle
return handle;
},
filenameToSqueak: function(unixpath) {
return unixpath;
},
filenameFromSqueak: function(filepath) {
return filepath;
},
});
Object.extend(Squeak, {
flushAllFiles: function() {
openFileDescriptors.forEach(function(fd) {
try {
fs.fsyncSync(fd);
} catch(e) {
console.error("Failed to flush one of the files");
}
});
},
filePut: function(fileName, buffer) {
try {
// Node does not support ArrayBuffer and Bun does not support DataView,
// use a TypedArray as argument to writeFileSync.
fs.writeFileSync(fileName, new Uint8Array(buffer));
} catch(e) {
console.error("Failed to create file with content: " + fileName);
}
},
});