Repository navigation
Expand file tree
/
Copy pathgjs-typelib-installer.js
More file actions
693 lines (596 loc) · 21.8 KB
/
Copy pathgjs-typelib-installer.js
File metadata and controls
693 lines (596 loc) · 21.8 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
/**
* Find and install OS packages for missing `gi://` imports.
*
* @module gjs-typelib-installer.js
*/
// SPDX-FileCopyrightText: 2025 Aleksandr Mezin <mezin.alexander@gmail.com>
//
// SPDX-License-Identifier: MIT
import GLib from 'gi://GLib';
import Gio from 'gi://Gio';
import Gi from 'gi';
/**
* Extract the version prefix by removing the last component.
*
* @private
* @param {string} version - The version string.
* @returns {string} The version prefix without the last component, or an empty string.
*/
function getVersionPrefix(version) {
const index = version.lastIndexOf('.');
return index === -1 ? '' : version.slice(0, index);
}
/**
* Get the list of OS identifiers (from /etc/os-release) for package resolution.
* Generates version-specific IDs (e.g., "debian:12", "debian:11")
* and includes ID_LIKE entries for derivative distributions.
*
* @private
* @returns {string[]} The list of OS identifiers.
*/
function getOsIds() {
const osIds = [];
const osId = GLib.get_os_info('ID');
const osVersionId = GLib.get_os_info('VERSION_ID');
if (!osId)
throw new Error('Can not query OS info');
for (let prefix = osVersionId; prefix; prefix = getVersionPrefix(prefix))
osIds.push(`${osId}:${prefix}`);
osIds.push(osId);
const osLike = GLib.get_os_info('ID_LIKE');
if (osLike) {
for (const like of osLike.split(' ')) {
if (like)
osIds.push(like);
}
}
if (osIds.includes('ubuntu') && !osIds.includes('debian'))
osIds.push('debian');
return osIds;
}
/**
* The cached list of OS identifiers for package resolution.
*
* @private
* @type {string[]|undefined}
*/
let cachedOsIds;
/**
* Get the cached list of OS identifiers for package resolution.
*
* @private
* @returns {string[]} The cached list of OS identifiers.
*/
function getOsIdsCached() {
cachedOsIds ??= getOsIds();
return cachedOsIds;
}
/**
* Information about a typelib dependency - an object with the typelib file name
* and an optional list of OS packages to install.
*
* @typedef TypelibInfo
* @property {string} filename - The file name of the library.
* @property {string[]|null} [packages] - The list of OS packages that need to be
* installed to use this library.
*/
/**
* A function that resolves typelib package name(s) for the current distro.
*
* @callback TypelibResolver
* @returns {TypelibInfo} The typelib file name and an optional package list.
*/
/**
* Resolve a typelib file name to package information based on the OS ID.
* Iterates through the cached OS IDs and returns the first matching distro entry.
*
* @private
* @param {string} filename - The typelib filename to resolve.
* @param {Partial<Record<string,string[]|null>>} distros - A mapping of OS IDs to package lists.
* @returns {TypelibInfo} The typelib information with filename and optional packages.
*/
function resolveByOsId(filename, distros) {
for (const osId of getOsIdsCached()) {
const packages = distros[osId];
if (packages !== undefined)
return {packages, filename};
}
return {filename};
}
/**
* Package definitions for GObject introspection typelibs.
* Organized by namespace and version, each entry maps to a resolver function
* that returns the appropriate package names for the current OS.
*
* @example Get the package name for Gtk 4.0 on the current OS
* {@includeCode examples/gtk4-pkg-name.js#example}
*/
export const packages = {
Adw: {
'1': () => resolveByOsId('Adw-1.typelib', {
alpine: ['libadwaita'],
arch: ['libadwaita'],
debian: ['gir1.2-adw-1'],
fedora: ['libadwaita'],
suse: ['typelib-1_0-Adw-1'],
}),
},
Gdk: {
'3.0': () => resolveByOsId('Gdk-3.0.typelib', {
alpine: ['gtk+3.0'],
arch: ['gtk3'],
debian: ['gir1.2-gtk-3.0'],
fedora: ['gtk3'],
suse: ['typelib-1_0-Gtk-3_0'],
}),
'4.0': () => resolveByOsId('Gdk-4.0.typelib', {
alpine: ['gtk4.0'],
arch: ['gtk4'],
debian: ['gir1.2-gtk-4.0'],
fedora: ['gtk4'],
suse: ['typelib-1_0-Gtk-4_0'],
}),
},
Gtk: {
'3.0': () => resolveByOsId('Gtk-3.0.typelib', {
alpine: ['gtk+3.0'],
arch: ['gtk3'],
debian: ['gir1.2-gtk-3.0'],
fedora: ['gtk3'],
suse: ['typelib-1_0-Gtk-3_0'],
}),
'4.0': () => resolveByOsId('Gtk-4.0.typelib', {
alpine: ['gtk4.0'],
arch: ['gtk4'],
debian: ['gir1.2-gtk-4.0'],
fedora: ['gtk4'],
suse: ['typelib-1_0-Gtk-4_0'],
}),
},
Handy: {
'1': () => resolveByOsId('Handy-1.typelib', {
alpine: ['libhandy1'],
arch: ['libhandy'],
debian: ['gir1.2-handy-1'],
fedora: ['libhandy'],
suse: ['typelib-1_0-Handy-1_0'],
}),
},
cairo: {
'1.0': () => resolveByOsId('cairo-1.0.typelib', {
alpine: ['gobject-introspection'],
arch: ['gobject-introspection-runtime'],
debian: ['gir1.2-freedesktop'],
fedora: ['gobject-introspection'],
suse: ['girepository-1_0'],
}),
},
Pango: {
'1.0': () => resolveByOsId('Pango-1.0.typelib', {
alpine: ['pango'],
arch: ['pango'],
debian: ['gir1.2-pango-1.0'],
fedora: ['pango'],
suse: ['typelib-1_0-Pango-1_0'],
}),
},
Vte: {
'2.91': () => resolveByOsId('Vte-2.91.typelib', {
alpine: ['vte3'],
arch: ['vte3'],
debian: ['gir1.2-vte-2.91'],
fedora: ['vte291'],
suse: ['typelib-1_0-Vte-2_91'],
}),
'3.91': () => resolveByOsId('Vte-3.91.typelib', {
alpine: ['vte3-gtk4'],
// https://gitlab.alpinelinux.org/alpine/aports/-/issues/17029
'alpine:3.20': ['vte3', 'vte3-gtk4'],
'alpine:3.21': ['vte3', 'vte3-gtk4'],
arch: ['vte4'],
debian: ['gir1.2-vte-3.91'],
fedora: ['vte291-gtk4'],
suse: ['typelib-1_0-Vte-3_91'],
}),
},
GioUnix: {
'2.0': () => resolveByOsId('GioUnix-2.0.typelib', {
alpine: ['glib'],
arch: ['glib2'],
debian: ['gir1.2-glib-2.0'],
fedora: ['glib2'],
'opensuse-leap:15': null,
suse: ['typelib-1_0-Gio-2_0'],
}),
},
GLibUnix: {
'2.0': () => resolveByOsId('GLibUnix-2.0.typelib', {
alpine: ['glib'],
arch: ['glib2'],
debian: ['gir1.2-glib-2.0'],
fedora: ['glib2'],
'opensuse-leap:15': null,
suse: ['typelib-1_0-GLibUnix-2_0'],
}),
},
Template: {
'1.0': () => resolveByOsId('Template-1.0.typelib', {
alpine: ['template-glib'],
arch: ['template-glib'],
debian: ['gir1.2-template-1.0'],
fedora: ['template-glib'],
rhel: null,
suse: ['typelib-1_0-Template-1_0'],
}),
},
};
/**
* An error thrown when GObject typelibs are missing.
* This error is thrown by {@link require} when one or more typelibs cannot be
* loaded and their corresponding packages or files are identified as missing.
*/
export class MissingDependencies extends Error {
/**
* The set of missing package names.
*
* @type {Set<string>}
*/
packages;
/**
* The set of missing typelib filenames.
*
* @type {Set<string>}
*/
files;
/**
* Create a MissingDependencies error.
*
* @param {Set<string>} pkgs - Missing package names.
* @param {Set<string>} files - Missing typelib filenames.
*/
constructor(pkgs, files) {
const msgParts = [];
if (pkgs.size > 0)
msgParts.push(`Missing packages: ${Array.from(pkgs).join(', ')}.`);
if (files.size > 0)
msgParts.push(`Missing files: ${Array.from(files).join(', ')}.`);
super(msgParts.join(' '));
this.name = 'MissingDependencies';
this.packages = pkgs;
this.files = files;
}
};
/* eslint-disable jsdoc/reject-any-type */
/**
* Import multiple GObject libraries and return the imported modules.
*
* @param {Partial<Record<string, string>>} versions - An object with
* namespaces as keys and versions as values.
* @returns {Partial<Record<string, any>>} Imported modules.
* @throws {MissingDependencies} If a known library is not installed, see
* {@link MissingDependencies}.
* @throws {Error} If an unknown library is requested.
*
* @example Import Template-GLib or ask the user to install packages
* {@includeCode examples/require-template.js#example}
*/
export function require(versions) {
/** @type {Partial<Record<string, any>>} */
const found = {};
/** @type {Set<string>} */
const missingPackages = new Set();
/** @type {Set<string>} */
const missingFiles = new Set();
for (const [namespace, version] of Object.entries(versions)) {
if (typeof version !== 'string')
throw new Error(`Version for namespace ${namespace} is not a string`);
/** @type {Partial<Record<string, Partial<Record<string, TypelibResolver>>>>} */
const resolvers = packages;
const resolver = resolvers[namespace]?.[version];
if (!resolver) {
throw new Error([
`No definition for namespace ${namespace}, version ${version} found.`,
'If you use gjs-typelib-installer as Meson subproject,',
'try removing the build directory and restarting the build from scratch',
].join(' '));
}
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
found[namespace] = Gi.require(namespace, version);
} catch (error) {
if (!(error instanceof Error))
throw error;
if (!error.message.includes(`Requiring ${namespace}, version ${version}:`))
throw error;
const {packages: pkgs, filename} = resolver();
if (pkgs) {
for (const pkg of pkgs)
missingPackages.add(pkg);
} else {
missingFiles.add(filename);
}
}
}
if (missingPackages.size > 0 || missingFiles.size > 0)
throw new MissingDependencies(missingPackages, missingFiles);
return found;
}
/* eslint-enable jsdoc/reject-any-type */
/**
* Quote and join command line arguments for shell execution.
*
* @private
* @param {Iterable<string>|Array<string>} argv - Command line arguments.
* @returns {string} The shell-quoted and joined command string.
*/
function shellJoin(argv) {
if (!Array.isArray(argv))
return shellJoin(Array.from(argv));
return argv.map(arg => GLib.shell_quote(arg)).join(' ');
}
/**
* @private
* @param {Gio.Subprocess} subprocess - The subprocess to wait for.
* @param {Gio.Cancellable | null} cancellable - The cancellable object or null.
* @returns {Promise<void>}
*/
function waitCheck(subprocess, cancellable) {
return new Promise((resolve, reject) => {
subprocess.wait_check_async(cancellable, (source, result) => {
try {
Gio.Subprocess.prototype.wait_check_finish.call(source, result);
resolve();
} catch (error) {
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
reject(error);
}
});
});
}
/**
* @private
* @param {Gio.Subprocess} subprocess - The subprocess to communicate with.
* @param {string | null} stdinBuf - The data to send to stdin or null.
* @param {Gio.Cancellable | null} cancellable - Optional cancellable for aborting the operation.
* @returns {Promise<[string, string | null]>} - Stdout and nullable stderr as [stdout, stderr].
*/
function communicateUtf8(subprocess, stdinBuf, cancellable) {
return new Promise((resolve, reject) => {
subprocess.communicate_utf8_async(stdinBuf, cancellable, (source, result) => {
try {
const [, stdout, stderr] =
Gio.Subprocess.prototype.communicate_utf8_finish.call(source, result);
resolve([stdout, stderr]);
} catch (error) {
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
reject(error);
}
});
});
}
/**
* Spawn a subprocess, wait for it to terminate, and get its stdout as a string.
*
* @private
* @param {string[]} argv - The command line.
* @param {Gio.Cancellable|null} cancellable - Optional cancellable for aborting the operation.
* @returns {Promise<string>} The subprocess stdout as a string.
*/
async function getSubprocessOutput(argv, cancellable = null) {
cancellable?.set_error_if_cancelled();
const launcher = Gio.SubprocessLauncher.new(Gio.SubprocessFlags.STDOUT_PIPE);
launcher.setenv('LC_ALL', 'C.UTF-8', true);
const subprocess = launcher.spawnv(argv);
try {
const [stdout] = await communicateUtf8(subprocess, null, cancellable);
await waitCheck(subprocess, cancellable);
return stdout;
} finally {
if (subprocess.get_identifier())
subprocess.force_exit();
}
}
/**
* Parse the JSON output from the 'pkgcli --json backend' command.
* Extracts and validates the roles array from the JSON response.
*
* @private
* @param {string} stdout - The output of 'pkgcli --json backend'.
* @returns {unknown[]} The roles as an array.
*/
function parsePkgCliRoles(stdout) {
const json = /** @type {unknown} */ (JSON.parse(stdout));
if (!json || typeof json !== 'object')
throw new Error(`Expected output to contain a JSON object: ${stdout}`);
if (!('roles' in json))
throw new Error(`Expected output to contain 'roles' key: ${stdout}`);
const {roles} = json;
if (typeof roles === 'string')
return roles.split(';');
if (Array.isArray(roles))
return roles;
throw new Error(`Expected 'roles' to be a string or an array: ${stdout}`);
}
/**
* A function that, given a list of packages, generates the installation command.
*
* @callback InstallCommandResolver
* @param {Iterable<string>} pkgs - The list of package names to install.
* @returns {string[]} The command line, as an argument list (argv).
*/
/**
* Finds the command to install OS packages using PackageKit.
* Checks for the pkgcli and pkcon utilities, returning a function that generates
* the appropriate installation command with cache refresh if supported.
*
* @private
* @param {Gio.Cancellable|null} cancellable - Optional cancellable for
* aborting the operation.
* @returns {Promise<InstallCommandResolver|null>} A function that generates
* the command line, or null if no working PackageKit CLI is found.
*/
async function findPackageKitInstallCommand(cancellable = null) {
cancellable?.set_error_if_cancelled();
const pkgcli = GLib.find_program_in_path('pkgcli');
if (pkgcli) {
const argv = [pkgcli, '--json', 'backend'];
try {
const stdout = await getSubprocessOutput(argv, cancellable);
const roles = parsePkgCliRoles(stdout);
if (roles.includes('install-packages')) {
if (roles.includes('refresh-cache')) {
return pkgs => ['sh', '-c', [
shellJoin([pkgcli, 'refresh', 'force']),
shellJoin(['exec', pkgcli, 'install', ...pkgs]),
].join(' && ')];
} else {
return pkgs => [pkgcli, 'install', ...pkgs];
}
} else {
console.warn(
"%s output doesn't include 'install-packages':",
shellJoin(argv),
stdout
);
}
} catch (ex) {
if (ex instanceof GLib.Error &&
ex.matches(Gio.io_error_quark(), Gio.IOErrorEnum.CANCELLED))
throw ex;
console.warn("%s doesn't seem to work:", shellJoin(argv), ex);
}
}
const pkcon = GLib.find_program_in_path('pkcon');
if (pkcon) {
const argv = [pkcon, '--plain', 'get-roles'];
try {
const stdout = await getSubprocessOutput(argv, cancellable);
const roles = stdout.split('\n');
if (roles.includes('install-packages')) {
if (roles.includes('refresh-cache')) {
return pkgs => ['sh', '-c', [
shellJoin([pkcon, 'refresh', 'force']),
shellJoin(['exec', pkcon, 'install', ...pkgs]),
].join(' && ')];
} else {
return pkgs => [pkcon, 'install', ...pkgs];
}
} else {
console.warn(
"%s output doesn't include 'install-packages':",
shellJoin(argv),
stdout
);
}
} catch (ex) {
if (ex instanceof GLib.Error &&
ex.matches(Gio.io_error_quark(), Gio.IOErrorEnum.CANCELLED))
throw ex;
console.warn("%s doesn't seem to work:", shellJoin(argv), ex);
}
}
return null;
}
/**
* Finds the command to install OS packages. Prefers PackageKit pkgcli/pkcon
* when available. Falls back to native package managers with pkexec.
*
* @param {Gio.Cancellable|null} cancellable - Optional cancellable
* for aborting the operation.
* @returns {Promise<InstallCommandResolver|null>} A function that generates
* the command line, or null if no suitable installation method is found.
*/
export async function findInstallCommand(cancellable = null) {
cancellable?.set_error_if_cancelled();
const packageKit = await findPackageKitInstallCommand(cancellable);
if (packageKit)
return packageKit;
const pkexec = GLib.find_program_in_path('pkexec');
if (!pkexec)
return null;
for (const os of getOsIdsCached()) {
if (os === 'alpine') {
const apk = GLib.find_program_in_path('apk');
if (apk)
return pkgs => [pkexec, apk, '-U', 'add', ...pkgs];
} else if (os === 'arch') {
const pacman = GLib.find_program_in_path('pacman');
if (pacman)
return pkgs => [pkexec, pacman, '-Sy', ...pkgs];
} else if (os === 'debian') {
const apt = GLib.find_program_in_path('apt') ?? GLib.find_program_in_path('apt-get');
if (apt) {
return pkgs => ['sh', '-c', [
shellJoin([pkexec, apt, 'update']),
shellJoin(['exec', pkexec, apt, 'install', ...pkgs]),
].join(' && ')];
}
} else if (os === 'fedora') {
const yum = GLib.find_program_in_path('dnf') ?? GLib.find_program_in_path('yum');
if (yum)
return pkgs => [pkexec, yum, 'install', ...pkgs];
} else if (os === 'suse') {
const zypper = GLib.find_program_in_path('zypper');
if (zypper)
return pkgs => [pkexec, zypper, 'install', ...pkgs];
}
}
return null;
}
/**
* A function that, given a list of arguments, generates the command line
* to run the specified command in a terminal emulator.
*
* @callback TerminalCommandResolver
* @param {Iterable<string>} argv - The command line arguments to run in a terminal.
* @returns {string[]} The command line, as an argument list (argv).
*/
/**
* Finds a terminal emulator to run commands in.
* Checks for GNOME Console (kgx), gnome-terminal, and xdg-terminal-exec in order.
*
* @param {Gio.Cancellable|null} cancellable - Optional cancellable for aborting the operation.
* @returns {Promise<TerminalCommandResolver|null>} A function that generates
* the command line, or null if no suitable terminal is found.
*
* @example "Hello, World!" in a new terminal
* {@includeCode examples/terminal-hello.js#example}
*/
// eslint-disable-next-line @typescript-eslint/require-await
export async function findTerminalCommand(cancellable = null) {
cancellable?.set_error_if_cancelled();
const kgx = GLib.find_program_in_path('kgx');
if (kgx)
return argv => [kgx, `--command=${shellJoin(argv)}`];
const gnomeTerminal = GLib.find_program_in_path('gnome-terminal');
if (gnomeTerminal)
return argv => [gnomeTerminal, '--', ...argv];
const xdgTerminalExec = GLib.find_program_in_path('xdg-terminal-exec');
if (xdgTerminalExec)
return argv => [xdgTerminalExec, ...argv];
return null;
}
/**
* Finds the command to install OS packages. Prefers the PackageKit CLI when
* available. Wraps the command to launch it in a terminal emulator.
* Combines the results of findTerminalCommand and findInstallCommand to create
* a complete installation command that runs in a terminal.
*
* @param {Gio.Cancellable|null} cancellable - Optional cancellable for aborting the operation.
* @returns {Promise<InstallCommandResolver|null>} A function that,
* given the list of packages, generates the installation command,
* wrapped for terminal execution, or null if no terminal or install command is found.
*
* @example Install Template-GLib package in a separate terminal window
* {@includeCode examples/install-template.js#example}
*/
export async function findTerminalInstallCommand(cancellable = null) {
cancellable?.set_error_if_cancelled();
const terminalCommand = await findTerminalCommand(cancellable);
if (!terminalCommand)
return null;
const installCommand = await findInstallCommand(cancellable);
if (!installCommand)
return null;
return pkgs => terminalCommand(installCommand(pkgs));
}