-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathManagerLocal.ts
More file actions
577 lines (537 loc) · 22.8 KB
/
ManagerLocal.ts
File metadata and controls
577 lines (537 loc) · 22.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
import path from 'path';
import { Package } from './Package.js';
import { PackageVersion } from '../types/Package.js';
import { Manager } from './Manager.js';
import {
archiveExtract,
dirCreate,
dirDelete,
dirEmpty,
dirIs,
dirMove,
dirRead,
fileCreate,
fileCreateJson,
fileCreateYaml,
fileExec,
fileExists,
fileHash,
fileInstall,
fileOpen,
fileReadJson,
fileReadYaml,
filesMove,
isAdmin,
runCliAsAdmin,
} from '../helpers/file.js';
import { isValidVersion, pathGetSlug, pathGetVersion, toSlug } from '../helpers/utils.js';
import { commandExists, getArchitecture, getSystem, isTests } from '../helpers/utilsLocal.js';
import { apiBuffer } from '../helpers/api.js';
import { FileInterface } from '../types/File.js';
import { FileType } from '../types/FileType.js';
import { RegistryType } from '../types/Registry.js';
import { PluginFormat, pluginFormatDir } from '../types/PluginFormat.js';
import { ConfigInterface } from '../types/Config.js';
import { ConfigLocal } from './ConfigLocal.js';
import { packageCompatibleFiles } from '../helpers/package.js';
import { presetFormatDir } from '../types/PresetFormat.js';
import { projectFormatDir } from '../types/ProjectFormat.js';
import { FileFormat } from '../types/FileFormat.js';
import { licenses } from '../types/License.js';
import { PluginType, PluginTypeOption, pluginTypes } from '../types/PluginType.js';
import { PresetTypeOption, presetTypes } from '../types/PresetType.js';
import { ProjectTypeOption, projectTypes } from '../types/ProjectType.js';
import { SystemType } from '../types/SystemType.js';
import { packageLoadFile, packageSaveFile } from '../helpers/packageLocal.js';
import inquirer from 'inquirer';
export class ManagerLocal extends Manager {
protected typeDir: string;
constructor(type: RegistryType, config?: ConfigInterface) {
super(type, config);
this.config = new ConfigLocal(config);
this.typeDir = this.config.get(`${type}Dir`) as string;
}
isPackageInstalled(slug: string, version: string): boolean {
const versionDirs: string[] = dirRead(path.join(this.typeDir, '**', slug, version));
return versionDirs.length > 0;
}
async create() {
// TODO Rewrite this code after prototype is proven.
const pkgQuestions = [
{
name: 'org',
type: 'input',
message: 'Org id',
default: 'org-name',
validate: (value: string) => value === toSlug(value),
},
{
name: 'package',
type: 'input',
message: 'Package id',
default: 'package-name',
validate: (value: string) => value === toSlug(value),
},
{
name: 'version',
type: 'input',
message: 'Package version',
default: '1.0.0',
validate: (value: string) => isValidVersion(value),
},
];
const pkgAnswers = await inquirer.prompt(pkgQuestions as any);
let types: PluginTypeOption[] | PresetTypeOption[] | ProjectTypeOption[] = pluginTypes;
if (this.type === RegistryType.Apps) {
types = pluginTypes;
} else if (this.type === RegistryType.Presets) {
types = presetTypes;
} else if (this.type === RegistryType.Projects) {
types = projectTypes;
}
const pkgVersionQuestions = [
{ name: 'name', type: 'input', message: 'Package name' },
{ name: 'author', type: 'input', message: 'Author name' },
{ name: 'description', type: 'input', message: 'Description' },
{ name: 'license', type: 'list', message: 'License', choices: licenses },
{ name: 'type', type: 'list', message: 'Type', choices: types },
{
name: 'tags',
type: 'input',
message: 'Tags (comma-separated)',
filter: (input: string) =>
input
.split(',')
.map(tag => tag.trim())
.filter(tag => tag.length > 0),
},
{
name: 'url',
type: 'input',
message: 'Website url',
default: `https://github.com/${pkgAnswers.org}/${pkgAnswers.package}`,
},
{
name: 'donate',
type: 'input',
message: 'Donation url',
},
{
name: 'audio',
type: 'input',
message: 'Audio preview url',
default: `https://open-audio-stack.github.io/open-audio-stack-registry/${this.type}/${pkgAnswers.org}/${pkgAnswers.package}/${pkgAnswers.package}.flac`,
},
{
name: 'image',
type: 'input',
message: 'Image preview url',
default: `https://open-audio-stack.github.io/open-audio-stack-registry/${this.type}/${pkgAnswers.org}/${pkgAnswers.package}/${pkgAnswers.package}.jpg`,
},
{ name: 'date', type: 'input', message: 'Date released', default: new Date().toISOString() },
{ name: 'changes', type: 'input', message: 'List of changes' },
];
const pkgVersionAnswers = await inquirer.prompt(pkgVersionQuestions as any);
// TODO prompt for each file.
pkgVersionAnswers.files = [];
if (this.type === RegistryType.Presets || this.type === RegistryType.Projects) {
pkgVersionAnswers.plugins = [];
}
this.log(pkgVersionAnswers);
const pkg = new Package(`${pkgAnswers.org}/${pkgAnswers.package}`);
pkg.addVersion(pkgAnswers.version, pkgVersionAnswers as PackageVersion);
this.log(JSON.stringify(pkg.getReport(), null, 2));
this.addPackage(pkg);
}
scan(ext = 'json', installable = true) {
const filePaths: string[] = dirRead(path.join(this.typeDir, '**', `index.${ext}`));
filePaths.forEach((filePath: string) => {
const subPath: string = filePath.replace(`${this.typeDir}${path.sep}`, '');
const pkgJson =
ext === 'yaml' ? (fileReadYaml(filePath) as PackageVersion) : (fileReadJson(filePath) as PackageVersion);
if (installable) pkgJson.installed = true;
const pkg = new Package(pathGetSlug(subPath, path.sep));
const version = pathGetVersion(subPath, path.sep);
pkg.addVersion(version, pkgJson);
this.addPackage(pkg);
});
}
export(dir: string, ext = 'json') {
const packagesByOrg: any = {};
const filename: string = `index.${ext}`;
const saveFile = ext === 'yaml' ? fileCreateYaml : fileCreateJson;
for (const [pkgSlug, pkg] of this.packages) {
for (const [version, pkgVersion] of pkg.versions) {
dirCreate(path.join(dir, pkgSlug, version));
saveFile(path.join(dir, pkgSlug, version, filename), pkgVersion);
}
dirCreate(path.join(dir, pkgSlug));
saveFile(path.join(dir, pkgSlug, filename), pkg.toJSON());
// TODO find a more elegant way to handle org exports.
const pkgOrg: string = pkgSlug.split('/')[0];
if (!packagesByOrg[pkgOrg]) packagesByOrg[pkgOrg] = {};
packagesByOrg[pkgOrg][pkgSlug] = pkg.toJSON();
}
for (const orgId in packagesByOrg) {
dirCreate(path.join(dir, orgId));
saveFile(path.join(dir, orgId, filename), packagesByOrg[orgId]);
}
dirCreate(dir);
saveFile(path.join(dir, filename), this.toJSON());
saveFile(path.join(dir, `report.${ext}`), this.getReport());
return true;
}
async install(slug: string, version?: string) {
this.log('install', slug, version);
// Get package information from registry.
const pkg: Package | undefined = this.getPackage(slug);
if (!pkg) throw new Error(`Package ${slug} not found in registry`);
const versionNum: string = version || pkg.latestVersion();
const pkgVersion: PackageVersion | undefined = pkg?.getVersion(versionNum);
if (!pkgVersion) throw new Error(`Package ${slug} version ${versionNum} not found in registry`);
if (this.isPackageInstalled(slug, versionNum)) {
this.log(`Package ${slug} version ${versionNum} already installed`);
pkgVersion.installed = true;
return pkgVersion;
}
// Check for compatible files before running admin command
const excludedFormats: FileFormat[] = [];
const system = getSystem();
if (system === SystemType.Linux) {
const hasDpkg = await commandExists('dpkg');
const hasRpm = await commandExists('rpm');
// If both exist, prefer DEB over RPM
if (hasDpkg && hasRpm) {
excludedFormats.push(FileFormat.RedHatPackage);
} else if (!hasDpkg) {
excludedFormats.push(FileFormat.DebianPackage);
} else if (!hasRpm) {
excludedFormats.push(FileFormat.RedHatPackage);
}
}
const files: FileInterface[] = packageCompatibleFiles(
pkgVersion,
[getArchitecture()],
[getSystem()],
excludedFormats,
);
if (!files.length) throw new Error(`No compatible files found for ${slug}`);
// Elevate permissions if not running as admin.
if (!isAdmin() && !isTests()) {
let command: string = `--appDir "${this.config.get('appDir')}" --operation "install" --type "${this.type}" --id "${slug}"`;
if (version) command += ` --ver "${version}"`;
if (this.debug) command += ` --log`;
await runCliAsAdmin(command);
const returnedPkg = this.getPackage(slug)?.getVersion(versionNum);
if (returnedPkg) {
if (this.isPackageInstalled(slug, versionNum)) returnedPkg.installed = true;
else delete returnedPkg.installed;
return returnedPkg;
}
}
// Create temporary directory to store downloaded files.
const dirDownloads: string = path.join(
this.config.get('appDir') as string,
'downloads',
this.type,
slug,
versionNum,
);
dirCreate(dirDownloads);
for (const key in files) {
// Download file to temporary directory if not already downloaded.
const file: FileInterface = files[key];
const filePath: string = path.join(dirDownloads, path.basename(file.url));
if (!fileExists(filePath)) {
const fileBuffer: ArrayBuffer = await apiBuffer(file.url);
fileCreate(filePath, Buffer.from(fileBuffer));
}
// Check file hash matches expected hash.
const hash: string = await fileHash(filePath);
if (hash !== file.sha256) throw new Error(`${filePath} hash mismatch`);
// If installer, run the installer headless (without the user interface).
if (file.type === FileType.Installer) {
// Test time out if installing during tests.
if (isTests()) fileOpen(filePath);
else fileInstall(filePath);
// Currently we don't get a list of paths from the installer.
// Create empty directory and save package version information.
// Installers have to be manually uninstalled for now.
const dirTarget: string = path.join(this.typeDir, 'Installers', slug, versionNum);
dirCreate(dirTarget);
fileCreateJson(path.join(dirTarget, 'index.json'), pkgVersion);
}
// If archive, extract the archive to temporary directory, then move individual files.
if (file.type === FileType.Archive) {
const dirSource: string = path.join(
this.config.get('appDir') as string,
file.type,
this.type,
slug,
versionNum,
);
const dirSub: string = path.join(slug, versionNum);
let formatDir: Record<string, string> = pluginFormatDir;
if (this.type === RegistryType.Apps) formatDir = pluginFormatDir;
else if (this.type === RegistryType.Presets) formatDir = presetFormatDir;
else if (this.type === RegistryType.Projects) formatDir = projectFormatDir;
await archiveExtract(filePath, dirSource);
// Move entire directory, maintaining the same folder structure.
if (pkgVersion.type === PluginType.Sampler) {
const dirTarget: string = path.join(this.typeDir, 'Samplers', dirSub);
dirCreate(dirTarget);
dirMove(dirSource, dirTarget);
fileCreateJson(path.join(dirTarget, 'index.json'), pkgVersion);
} else {
// Check if archive contains installer files (pkg, dmg) that should be run
const allFiles = dirRead(`${dirSource}/**/*`).filter(f => !dirIs(f));
const installerFiles = allFiles.filter(f => {
const ext = path.extname(f).toLowerCase();
return ext === '.pkg' || ext === '.dmg';
});
if (installerFiles.length > 0) {
// Run installer files found in archive
for (const installerFile of installerFiles) {
if (isTests()) fileOpen(installerFile);
else fileInstall(installerFile);
}
// Create directory and save package info for installer
const dirTarget: string = path.join(this.typeDir, 'Installers', dirSub);
dirCreate(dirTarget);
fileCreateJson(path.join(dirTarget, 'index.json'), pkgVersion);
} else if (this.type === RegistryType.Plugins) {
// For plugins, move files into type-specific subdirectories
const filesMoved: string[] = filesMove(dirSource, this.typeDir, dirSub, formatDir);
if (filesMoved.length === 0) {
throw new Error(`No compatible files found to install for ${slug}`);
}
filesMoved.forEach((fileMoved: string) => {
const fileJson: string = path.join(path.dirname(fileMoved), 'index.json');
fileCreateJson(fileJson, pkgVersion);
});
} else {
// For apps/projects/presets, move entire directory without type subdirectories
const dirTarget: string = path.join(this.typeDir, dirSub);
dirCreate(dirTarget);
dirMove(dirSource, dirTarget);
fileCreateJson(path.join(dirTarget, 'index.json'), pkgVersion);
// Ensure executable permissions for likely executables inside moved app/project/preset
try {
const movedFiles = dirRead(path.join(dirTarget, '**', '*')).filter(f => !dirIs(f));
movedFiles.forEach((movedFile: string) => {
const ext = path.extname(movedFile).slice(1).toLowerCase();
if (['', 'elf', 'exe'].includes(ext)) {
try {
fileExec(movedFile);
} catch (err) {
this.log(`Failed to set exec on ${movedFile}:`, err);
}
}
});
} catch (err) {
this.log('Error while setting executable permissions:', err);
}
// Also handle macOS .app bundles: set exec on binaries in Contents/MacOS
try {
const appDirs = dirRead(path.join(dirTarget, '**', '*.app')).filter(d => dirIs(d));
appDirs.forEach((appDir: string) => {
try {
const macosBinPattern = path.join(appDir, 'Contents', 'MacOS', '**', '*');
const macosFiles = dirRead(macosBinPattern).filter(f => !dirIs(f));
macosFiles.forEach((binFile: string) => {
try {
fileExec(binFile);
} catch (err) {
this.log(`Failed to set exec on app binary ${binFile}:`, err);
}
});
} catch (err) {
this.log(`Error scanning .app contents for ${appDir}:`, err);
}
});
} catch (err) {
this.log(err);
}
}
}
}
}
pkgVersion.installed = true;
return pkgVersion;
}
async installAll() {
// Elevate permissions if not running as admin.
if (!isAdmin() && !isTests()) {
let command: string = `--appDir "${this.config.get('appDir')}" --operation "installAll" --type "${this.type}"`;
if (this.debug) command += ` --log`;
await runCliAsAdmin(command);
return this.listPackages();
}
// Loop through all packages and install each one.
for (const pkg of this.listPackages()) {
const versionNum: string = pkg.latestVersion();
await this.install(pkg.slug, versionNum);
}
return this.listPackages();
}
async installDependency(slug: string, version?: string, filePath?: string, type = RegistryType.Plugins) {
// Get dependency package information from registry.
const manager = new ManagerLocal(type, this.config.config);
await manager.sync();
manager.scan();
const pkg: Package | undefined = manager.getPackage(slug);
if (!pkg) throw new Error(`Package ${slug} not found in registry`);
const versionNum: string = version || pkg.latestVersion();
const pkgVersion: PackageVersion | undefined = pkg?.getVersion(versionNum);
if (!pkgVersion) throw new Error(`Package ${slug} version ${versionNum} not found in registry`);
// Get local package file.
const pkgFile = packageLoadFile(filePath) as any;
if (pkgFile[type] && pkgFile[type][slug] && pkgFile[type][slug] === versionNum) {
this.log(`Package ${slug} version ${versionNum} is already a dependency`);
pkgFile.installed = true;
return pkgFile;
}
// Install dependency.
await manager.install(slug, version);
// Add dependency to local package file and save.
if (!pkgFile[type]) pkgFile[type] = {};
pkgFile[type][slug] = versionNum;
packageSaveFile(pkgFile, filePath);
pkgFile.installed = true;
return pkgFile;
}
async installDependencies(filePath: string, type = RegistryType.Plugins) {
// Loop through dependency packages and install each one.
const pkgFile = packageLoadFile(filePath) as any;
const manager = new ManagerLocal(type, this.config.config);
await manager.sync();
manager.scan();
for (const slug in pkgFile[type]) {
await manager.install(slug, pkgFile[type][slug]);
}
pkgFile.installed = true;
return pkgFile;
}
open(slug: string, version?: string, options: string[] = []) {
this.log('open', slug, version, options);
// Get package information
const pkg = this.getPackage(slug);
if (!pkg) {
throw new Error(`Package ${slug} not found`);
}
const versionNum = version || pkg.latestVersion();
const pkgVersion = pkg.getVersion(versionNum);
if (!pkgVersion) {
throw new Error(`Package ${slug} version ${versionNum} not found`);
}
// Check if package is installed
if (!this.isPackageInstalled(slug, versionNum)) {
throw new Error(`Package ${slug} version ${versionNum} not installed`);
}
// Filter compatible files and find one with open field
const files: FileInterface[] = packageCompatibleFiles(pkgVersion, [getArchitecture()], [getSystem()], []);
const openableFile = files.find(file => (file as any).open);
if (!openableFile) {
throw new Error(`Package ${slug} has no compatible file with open command defined`);
}
try {
const openPath = (openableFile as any).open;
const fileExt: string = path.extname(openPath).slice(1).toLowerCase();
let packageDir: string;
if (this.type === RegistryType.Plugins) {
// For plugins, use type-specific subdirectories
const formatDir: string = pluginFormatDir[fileExt as PluginFormat] || 'Plugin';
packageDir = path.join(this.typeDir, formatDir, slug, versionNum);
} else {
// For apps/projects/presets, files are in direct package directory
packageDir = path.join(this.typeDir, slug, versionNum);
}
let fullPath: string;
if (path.isAbsolute(openPath)) {
fullPath = openPath;
} else if (fileExt === 'app') {
// For .app bundles, construct path to executable inside Contents/MacOS/
const appName = path.basename(openPath, '.app');
fullPath = path.join(packageDir, openPath, 'Contents', 'MacOS', appName);
} else {
fullPath = path.join(packageDir, openPath);
}
const command = `"${fullPath}" ${options.join(' ')}`;
this.log(`Running: ${command}`);
fileOpen(fullPath, options);
return true;
} catch (error) {
this.log(`Error opening package ${slug}:`, error);
return false;
}
}
async uninstall(slug: string, version?: string) {
// Get package information from registry.
const pkg: Package | undefined = this.getPackage(slug);
if (!pkg) throw new Error(`Package ${slug} not found in registry`);
const versionNum: string = version || pkg.latestVersion();
const pkgVersion: PackageVersion | undefined = pkg?.getVersion(versionNum);
if (!pkgVersion) throw new Error(`Package ${slug} version ${versionNum} not found in registry`);
if (!this.isPackageInstalled(slug, versionNum))
throw new Error(`Package ${slug} version ${versionNum} not installed`);
// Elevate permissions if not running as admin.
if (!isAdmin() && !isTests()) {
let command: string = `--appDir "${this.config.get('appDir')}" --operation "uninstall" --type "${this.type}" --id "${slug}"`;
if (version) command += ` --ver "${version}"`;
if (this.debug) command += ` --log`;
await runCliAsAdmin(command);
const returnedPkg = this.getPackage(slug)?.getVersion(versionNum);
if (returnedPkg) {
if (this.isPackageInstalled(slug, versionNum)) returnedPkg.installed = true;
else delete returnedPkg.installed;
return returnedPkg;
}
}
// Delete all directories for this package version.
const versionDirs: string[] = dirRead(path.join(this.typeDir, '**', slug, versionNum));
versionDirs.forEach((versionDir: string) => {
dirDelete(versionDir);
});
// Delete all empty directories for this package.
const pkgDirs: string[] = dirRead(path.join(this.typeDir, '**', slug));
pkgDirs.forEach((pkgDir: string) => {
if (dirEmpty(pkgDir)) dirDelete(pkgDir);
});
// Delete all empty directories for the org.
const orgDirs: string[] = dirRead(path.join(this.typeDir, '**', slug.split('/')[0]));
orgDirs.forEach((orgDir: string) => {
if (dirEmpty(orgDir)) dirDelete(orgDir);
});
delete pkgVersion.installed;
return pkgVersion;
}
async uninstallDependency(slug: string, version?: string, filePath?: string, type = RegistryType.Plugins) {
// Get local package file.
const pkgFile = packageLoadFile(filePath) as any;
if (!pkgFile[type]) throw new Error(`Package ${type} is missing`);
if (!pkgFile[type][slug]) throw new Error(`Package ${type} ${slug} is not a dependency`);
// Uninstall dependency.
const manager = new ManagerLocal(type, this.config.config);
await manager.sync();
manager.scan();
await manager.uninstall(slug, version || pkgFile[type][slug]);
// Remove dependency from local package file and save.
if (!pkgFile[type]) pkgFile[type] = {};
delete pkgFile[type][slug];
packageSaveFile(pkgFile, filePath);
pkgFile.installed = true;
return pkgFile;
}
async uninstallDependencies(filePath?: string, type = RegistryType.Plugins) {
// Loop through dependency packages and uninstall each one.
const pkgFile = packageLoadFile(filePath) as any;
const manager = new ManagerLocal(type, this.config.config);
await manager.sync();
manager.scan();
for (const slug in pkgFile[type]) {
await manager.uninstall(slug, pkgFile[type][slug]);
}
pkgFile.installed = true;
return pkgFile;
}
}