Debian Codegraph @

ivette/src/dome/misc/system.ts

raw
1 /* ************************************************************************ */
2 /* */
3 /* This file is part of Frama-C. */
4 /* */
5 /* Copyright (C) 2007-2022 */
6 /* CEA (Commissariat à l'énergie atomique et aux énergies */
7 /* alternatives) */
8 /* */
9 /* you can redistribute it and/or modify it under the terms of the GNU */
10 /* Lesser General Public License as published by the Free Software */
11 /* Foundation, version 2.1. */
12 /* */
13 /* It is distributed in the hope that it will be useful, */
14 /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
15 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
16 /* GNU Lesser General Public License for more details. */
17 /* */
18 /* See the GNU Lesser General Public License version 2.1 */
19 /* for more details (enclosed in the file licenses/LGPLv2.1). */
20 /* */
21 /* ************************************************************************ */
22
23 /**
24 @packageDocumentation
25 @module dome/system
26 */
27
28 /* eslint-disable max-len */
29 /* eslint-disable no-console */
30
31 // --------------------------------------------------------------------------
32 // --- Evolved Spawn Process
33 // --------------------------------------------------------------------------
34
35 import _ from 'lodash';
36 import Emitter from 'events';
37 import Exec from 'child_process';
38 import fspath from 'path';
39 import fs from 'fs';
40
41 // --------------------------------------------------------------------------
42 // --- Platform Specificities
43 // --------------------------------------------------------------------------
44
45 let thePlatform = 'linux';
46 switch (process.platform) {
47 case 'darwin':
48 thePlatform = 'macos'; break;
49 case 'win32':
50 thePlatform = 'windows'; break;
51 case 'aix':
52 case 'freebsd':
53 case 'linux':
54 case 'openbsd':
55 case 'sunos':
56 thePlatform = 'linux'; break;
57 default:
58 console.warn(`Unkwnon '${process.platform}' (fallback to 'linux')`);
59 thePlatform = 'linux'; break;
60 }
61
62 /**
63 @summary System platform.
64 @description
65 Similar to `process.platform`, but fall into fewer categories:
66 - `'macos'` for Mac OSX,
67 - `'windows'` for Windows (32 or 64)
68 - `'linux'` for most unix-like platforms
69
70 Non-recognized platforms will fallback to `'linux'` with the
71 emission of a warning.
72 */
73 export const platform = thePlatform;
74
75 // --------------------------------------------------------------------------
76 // --- Logging
77 // --------------------------------------------------------------------------
78
79 /** Development mode flag */
80 export const DEVEL = process.env.NODE_ENV !== 'production';
81
82 // --------------------------------------------------------------------------
83 // --- System Emitter
84 // --------------------------------------------------------------------------
85
86 export const emitter = new Emitter();
87 emitter.setMaxListeners(250);
88
89 // --------------------------------------------------------------------------
90 // --- At Exit
91 // --------------------------------------------------------------------------
92
93 export type Callback = () => void;
94
95 const exitJobs: Callback[] = [];
96
97 /**
98 Executes a routine at exit.
99
100 Exceptions thrown by the function are captured and reported on the console.
101 */
102 export function atExit(callback: Callback): void {
103 exitJobs.push(callback);
104 }
105
106 /** Execute all pending exit jobs (and flush the list). */
107 export function doExit(): void {
108 exitJobs.forEach((fn) => {
109 try { fn(); }
110 catch (err) { console.error('[Dome] atExit:', err); }
111 });
112 exitJobs.length = 0;
113 }
114
115 // --------------------------------------------------------------------------
116 // --- Command Line Arguments
117 // --------------------------------------------------------------------------
118
119 let COMMAND_WDIR = '.';
120 let COMMAND_ARGV: string[] = [];
121
122 function setCommandLine(argv: string[], wdir: string): void {
123 COMMAND_ARGV = argv;
124 COMMAND_WDIR = wdir;
125 }
126
127 /**
128 Working directory (Application Window).
129
130 This the current working directory from where the application window
131 was opened.
132
133 The function returns `undefined` until the `dome.command` event has
134 been emitted from the `Main` process.
135
136 See also [[dome.onCommand]]
137 */
138 export function getWorkingDir(): string { return COMMAND_WDIR; }
139
140 /**
141 Returns the current process ID.
142 */
143 export function getPID(): number { return process.pid; }
144
145 /**
146 Command-line arguments (Application Window).
147
148 This the command-line arguments used to open the application window.
149
150 The function returns `undefined` until the `dome.command`
151 event has been emitted from the `Main` process.
152
153 See also [[dome.onCommand]]
154 */
155 export function getArguments(): string[] { return COMMAND_ARGV; }
156
157 // --------------------------------------------------------------------------
158 // --- File Join
159 // --------------------------------------------------------------------------
160
161 /**
162 @summary Join file paths.
163 @param {string} [...paths] - a sequence of path segments
164 @return {string} the joined filepath
165 @description
166 Same as [Node `path.join`](https://nodejs.org/dist/latest-v12.x/docs/api/path.html#path_path_join_paths)
167 */
168 export const { join } = fspath;
169
170 /**
171 @summary Absolute (joined) file paths.
172 @param {string} [...paths] - a sequence of path segments
173 @return {string} the corresponding absolute path
174 @description
175 Same as [Node `path.resolve`](https://nodejs.org/dist/latest-v12.x/docs/api/path.html#path_path_resolve_paths)
176 */
177 export const { resolve } = fspath;
178
179 /**
180 @summary Dirname of path.
181 @param {string} path - a file path
182 @return {string} the dirname of the path
183 @description
184 Same as [Node `path.dirname`](https://nodejs.org/dist/latest-v12.x/docs/api/path.html#path_path_dirname_path)
185 */
186 export const { dirname } = fspath;
187
188 /**
189 @summary Basename of path.
190 @param {string} path - a file path
191 @param {string} [ext] - file extension to remove
192 @return {string} the basename of the path
193 @description
194 Same as [Node `path.basename`](https://nodejs.org/dist/latest-v12.x/docs/api/path.html#path_path_basename_path_ext)
195 */
196 export const { basename } = fspath;
197
198 /**
199 @summary File extension of path.
200 @param {string} path - a file path
201 @return {string} the file extension of the path
202 @description
203 Same as [Node `path.extname`](https://nodejs.org/dist/latest-v12.x/docs/api/path.html#path_path_extname_path)
204 */
205 export const { extname } = fspath;
206
207 // --------------------------------------------------------------------------
208 // --- File Stats
209 // --------------------------------------------------------------------------
210
211 /**
212 Returns an `fs.stat()` object for the path.
213
214 Promisified [Node `fs.stat`](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_fs_stat_path_callback).
215
216 Returns a (promised) [Node `fs.Stats`](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_class_fs_stats) object,
217 including the following usefull fields and methods (and more):
218 - `stats.isFile()` returns `true` for a regular file
219 - `stats.isDirectory()` returns `true` for a directory
220 - `stats.mode` the bitfield (integer) of the file access mode
221 - `stats.size` the size of the file (in bytes)
222 - `stats.mtime` last modification time stamp (javascript `Date` object)
223
224 The promise is rejected if the file does not exists.
225 */
226 export function fileStat(path: string): Promise<fs.Stats> {
227 return new Promise((result, reject) => {
228 fs.stat(path, (err, data) => (err ? reject(err) : result(data)));
229 });
230 }
231
232 /**
233 Checks if a path exists and is a regular file
234 (Synchronous check).
235 */
236 export function isFile(path: string): boolean {
237 try {
238 return !!path && fs.statSync(path).isFile();
239 } catch (_err) {
240 return false;
241 }
242 }
243
244 /**
245 Checks if a path exists and is a directory
246 (Synchronous check).
247 */
248 export function isDirectory(path: string): boolean {
249 try {
250 return !!path && fs.statSync(path).isDirectory();
251 } catch (_err) {
252 return false;
253 }
254 }
255
256 /**
257 Checks if a path exists and is a file or directory
258 (Synchronous check).
259 */
260 export function exists(path: string): boolean {
261 try {
262 if (!path) return false;
263 const stats = fs.statSync(path);
264 return stats.isFile() || stats.isDirectory();
265 } catch (_err) {
266 return false;
267 }
268 }
269
270 // --------------------------------------------------------------------------
271 // --- Read File
272 // --------------------------------------------------------------------------
273
274 /**
275 Reads a textual file contents.
276
277 Promisified `fs.readFile` using `utf-8` encoding.
278 */
279 export function readFile(path: string): Promise<string> {
280 return fs.promises.readFile(path, { encoding: 'utf-8' });
281 }
282
283 // --------------------------------------------------------------------------
284 // --- Write File
285 // --------------------------------------------------------------------------
286
287 /**
288 Writes a textual content in a file.
289
290 Promisified `fs.writeFile` using `utf-8` encoding.
291 */
292 export async function writeFile(path: string, content: string): Promise<void> {
293 return fs.promises.writeFile(path, content, { encoding: 'utf-8' });
294 }
295
296 // --------------------------------------------------------------------------
297 // --- Copy File
298 // --------------------------------------------------------------------------
299
300 /**
301 Copy file to a new path.
302 @param srcPath - the source file path
303 @param tgtPath - the target file path
304
305 Promisified `fs.copyFile`.
306 */
307 export async function copyFile(srcPath: string, tgtPath: string): Promise<void> {
308 return fs.promises.copyFile(srcPath, tgtPath);
309 }
310
311 // --------------------------------------------------------------------------
312 // --- Read Directory
313 // --------------------------------------------------------------------------
314
315 /**
316 Reads a directory.
317 @returns directory contents (local names)
318
319 Promisified `fs.readdir`.
320
321 Uses `utf-8` encoding to obtain (relative) file names instead of byte buffers.
322 On MacOS, `.DS_Store` entries are filtered out.
323 */
324 export async function readDir(path: string): Promise<string[]> {
325 const filterDir = (f: string): boolean => f !== '.DS_Store';
326 const entries = await fs.promises.readdir(path, { encoding: 'utf-8', withFileTypes: true });
327 return entries.map((fn) => fn.name).filter(filterDir);
328 }
329
330 // --------------------------------------------------------------------------
331 // --- Make Directory
332 // --------------------------------------------------------------------------
333
334 const CREATE_DIR_OPTIONS: fs.MakeDirectoryOptions = {
335 recursive: true,
336 mode: 0o777,
337 };
338
339 /**
340 Creates a new directory. Defaults permission is recursive `0o777`.
341
342 Promisified
343 [Node `fs.mkdir`](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_fs_mkdir_path_options_callback).
344
345 */
346 export function mkDir(
347 path: string,
348 options?: number | fs.MakeDirectoryOptions,
349 ): Promise<void> {
350 return new Promise((result, reject) => {
351 fs.mkdir(path, options ?? CREATE_DIR_OPTIONS, (err) => {
352 if (err) reject(err); else result();
353 });
354 });
355 }
356
357 // --------------------------------------------------------------------------
358 // --- Remove File
359 // --------------------------------------------------------------------------
360
361 /**
362 Remove a file.
363
364 Promisified
365 [Node `fs.unlink`](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_fs_unlink_path_callback)
366 */
367 export function remove(path: string): Promise<void> {
368 return new Promise((result, reject) => {
369 fs.unlink(path, (err) => (err ? reject(err) : result()));
370 });
371 }
372
373 // --------------------------------------------------------------------------
374 // --- Remove Directory
375 // --------------------------------------------------------------------------
376
377 // Not (yet) implemented in Node for Electron
378 function rmDirNonRec(path: string): Promise<void> {
379 return new Promise((result, reject) => {
380 fs.rmdir(path, (err) => (err ? reject(err) : result()));
381 });
382 }
383
384 // Not (yet) implemented in Node for Electron
385 async function rmDirRec(path: string): Promise<void> {
386 try {
387 const stats = fs.statSync(path);
388 if (stats.isFile()) {
389 await remove(path);
390 return;
391 }
392 if (stats.isDirectory()) {
393 const rmDirSub = (name: string): void => {
394 rmDirRec(fspath.join(path, name));
395 };
396 const entries = await readDir(path);
397 await Promise.all(entries.map(rmDirSub));
398 await rmDirNonRec(path);
399 return;
400 }
401 } catch (err) {
402 if (DEVEL) console.warn('[Dome.rmDirRec]', err);
403 }
404 }
405
406 export interface RmDirOptions {
407 recursive: boolean;
408 }
409
410 /**
411 Removes a directory.
412
413 Promisified
414 [Node `fs.rmdir`](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_fs_mkdir_path_options_callback).
415
416 */
417 export function rmDir(path: string, options?: RmDirOptions): Promise<void> {
418 return (options?.recursive ?? true) ? rmDirRec(path) : rmDirNonRec(path);
419 }
420
421 // --------------------------------------------------------------------------
422 // --- Rename File
423 // --------------------------------------------------------------------------
424
425 /**
426 Renames of file of direcory.
427
428 Promisified
429 [Node `fs.rename`](https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_fs_rename_oldpath_newpath_callback)
430 */
431 export function rename(oldPath: string, newPath: string): Promise<void> {
432 return new Promise((result, reject) => {
433 fs.rename(oldPath, newPath, (err) => (err ? reject(err) : result()));
434 });
435 }
436
437 // --------------------------------------------------------------------------
438 // --- Child Process
439 // --------------------------------------------------------------------------
440
441 const childprocess = new Map<number, Exec.ChildProcess>();
442
443 atExit(() => {
444 childprocess.forEach((process, pid) => {
445 try { process.kill(); }
446 catch (err) {
447 if (DEVEL) console.warn('[Dome.atExit] killing process', pid, err);
448 }
449 });
450 });
451
452 export type StdPipe = { path?: string | undefined; mode?: number; pipe?: boolean };
453 export type StdOptions = undefined | 'null' | 'ignore' | 'pipe' | StdPipe;
454
455 type StdIO = { io: number | 'pipe' | 'ignore' | 'ipc'; fd?: number };
456
457 function stdSpec(spec: StdOptions, isOutput: boolean): StdIO {
458 switch (spec) {
459 case undefined:
460 return { io: isOutput ? 'pipe' : 'ignore' };
461 case null:
462 case 'null':
463 case 'ignore':
464 return { io: 'ignore' };
465 case 'pipe':
466 return { io: 'pipe' };
467 default: {
468 let fd: number | undefined;
469 if (spec.path) fd = fs.openSync(spec.path, spec.mode || (isOutput ? 'w' : 'r'));
470 return (isOutput && spec.pipe) ? { io: 'pipe', fd } : { io: fd ?? 'ignore' };
471 }
472 }
473 }
474
475 interface Readable {
476 pipe(out: fs.WriteStream): void;
477 unpipe(out: fs.WriteStream): void;
478 }
479
480 function pipeTee(std: Readable, fd: number): void {
481 if (!fd) return;
482 const out = fs.createWriteStream('<ignored>', { fd, encoding: 'utf-8' });
483 out.on('error', (err) => {
484 console.warn('[Dome] can not pipe:', err);
485 std.unpipe(out);
486 });
487 std.pipe(out);
488 }
489
490 export interface ProcessOptions {
491 /** Defaults to the application current working directory. */
492 cwd?: string;
493 env?: { [VAR: string]: string };
494 stdin?: StdOptions;
495 stdout?: StdOptions;
496 stderr?: StdOptions;
497 /** Use a Node child process with inter-node process RPC. */
498 fork?: boolean;
499 }
500
501 /**
502 Spawn a child process.
503
504 Based on [Node `child_process.spawn`](https://nodejs.org/dist/latest-v12.x/docs/api/child_process.html#child_process_child_process_spawn_command_args_options). The promised process object is a regular [Node `ChildProcess`](https://nodejs.org/api/child_process.html#child_process_class_childprocess) object, for which we recall the main useful methods below:
505
506 - `child.on('exit',(code) => {...})` emitted event when the process is terminated
507 - `child.on('close',(code) => {...})` emitted event when the process is fully terminated (all pipes closed)
508 - `child.on('message',(...data) => {...})` emitted from the _forked_ process (if applicable)
509 - `child.stdout.on('data',(text) => {...})` emitted when the process writes on piped stdout (receives `UTF-8` strings)
510 - `child.stderr.on('data',(text) => {...})` emitted when the process writes on piped stderr (receives `UTF-8` strings)
511 - `child.kill()` sends a `'SIGTERM'` unix message to the process
512
513 Options is an object similar to the original Node options, with small adaptations.
514 The possible option fields are described as follows:
515
516 Environment variables are _added_ to the default `process.env` environment.
517
518 All pipes have their encoding set to `UTF-8`,
519 hence all callbacks on process events will receive natural strings instead of raw byte buffers.
520
521 When specifying a file for a process standard stream, an optional mode can be specified.
522 Default is `'r'` for input streams and `'w'` for output ones.
523 If option `pipe:true` is provided (output streams only), the output of the process is
524 also piped through the Process object. The file-path is relative to the current working directory
525 of the _application_, not be confused with the `cwd` option of the spawned command.
526
527 When the `fork` flag is set, the child process is spawned using
528 [Node `child_process.fork`](https://nodejs.org/dist/latest-v12.x/docs/api/child_process.html#child_process_child_process_fork_modulepath_args_options). This enables Node inter-process communication _via_ the
529 `process.send()` and `process.on('message')` methods of the child process object.
530 */
531
532 export function spawn(
533 command: string,
534 args?: string[],
535 options?: ProcessOptions,
536 ): Promise<Exec.ChildProcess> {
537 return new Promise((result, reject) => {
538
539 const cwd = options ? options.cwd : undefined;
540 const opt = options ? options.env : undefined;
541 const env = // Forces 'PWD' env. variable for executing a non-shell process
542 (cwd || opt) ? { ...process.env, ...opt, 'PWD': cwd } : undefined;
543 const stdin = stdSpec(options && options.stdin, false);
544 const stdout = stdSpec(options && options.stdout, true);
545 const stderr = stdSpec(options && options.stderr, true);
546 const stdio = [stdin.io, stdout.io, stderr.io];
547 const fopt: Exec.ForkOptions = { cwd, env, stdio };
548 const forked = options && options.fork;
549 const cargs = args ? args.slice() : [];
550 let child: Exec.ChildProcess | undefined;
551
552 if (forked) {
553 stdio.push('ipc');
554 child = Exec.fork(command, cargs, fopt);
555 } else {
556 child = Exec.spawn(command, cargs, fopt);
557 }
558
559 if (!child) reject(new Error(
560 `[Dome] Unable to create process ('${command}')`,
561 ));
562
563 const { pid } = child;
564
565 if (!pid) {
566 // Must defer rejection, otherwise an uncaught exception is raised.
567 child.on('error', (err) => reject(err));
568 return;
569 }
570
571 childprocess.set(pid, child);
572 child.on('exit', () => childprocess.delete(pid));
573
574 const out = child.stdout;
575 const err = child.stderr;
576
577 if (out && stdout.fd) {
578 out.setEncoding('utf-8');
579 pipeTee(out, stdout.fd);
580 }
581 if (err && stderr.fd) {
582 err.setEncoding('utf-8');
583 pipeTee(err, stderr.fd);
584 }
585
586 result(child);
587 });
588 }
589
590 // --------------------------------------------------------------------------
591 // --- Window Management
592 // --------------------------------------------------------------------------
593
594 const WINDOW_APPLICATION_ARGV = '--dome-application-window';
595 const WINDOW_PREFERENCES_ARGV = '--dome-preferences-window';
596
597 // --------------------------------------------------------------------------
598 // --- Only used for inter-module initialisation
599 // --------------------------------------------------------------------------
600
601 export default {
602 setCommandLine,
603 WINDOW_APPLICATION_ARGV,
604 WINDOW_PREFERENCES_ARGV,
605 };
606
607 // --------------------------------------------------------------------------