forked from atom/atom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpackage-manager.js
1034 lines (906 loc) · 29.1 KB
/
package-manager.js
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const path = require('path');
let normalizePackageData = null;
const _ = require('underscore-plus');
const { Emitter } = require('event-kit');
const fs = require('fs-plus');
const CSON = require('season');
const ServiceHub = require('service-hub');
const Package = require('./package');
const ThemePackage = require('./theme-package');
const ModuleCache = require('./module-cache');
const packageJSON = require('../package.json');
// Extended: Package manager for coordinating the lifecycle of Atom packages.
//
// An instance of this class is always available as the `atom.packages` global.
//
// Packages can be loaded, activated, and deactivated, and unloaded:
// * Loading a package reads and parses the package's metadata and resources
// such as keymaps, menus, stylesheets, etc.
// * Activating a package registers the loaded resources and calls `activate()`
// on the package's main module.
// * Deactivating a package unregisters the package's resources and calls
// `deactivate()` on the package's main module.
// * Unloading a package removes it completely from the package manager.
//
// Packages can be enabled/disabled via the `core.disabledPackages` config
// settings and also by calling `enablePackage()/disablePackage()`.
module.exports = class PackageManager {
constructor(params) {
({
config: this.config,
styleManager: this.styleManager,
notificationManager: this.notificationManager,
keymapManager: this.keymapManager,
commandRegistry: this.commandRegistry,
grammarRegistry: this.grammarRegistry,
deserializerManager: this.deserializerManager,
viewRegistry: this.viewRegistry,
uriHandlerRegistry: this.uriHandlerRegistry
} = params);
this.emitter = new Emitter();
this.activationHookEmitter = new Emitter();
this.packageDirPaths = [];
this.deferredActivationHooks = [];
this.triggeredActivationHooks = new Set();
this.packagesCache =
packageJSON._atomPackages != null ? packageJSON._atomPackages : {};
this.packageDependencies =
packageJSON.packageDependencies != null
? packageJSON.packageDependencies
: {};
this.deprecatedPackages = packageJSON._deprecatedPackages || {};
this.deprecatedPackageRanges = {};
this.initialPackagesLoaded = false;
this.initialPackagesActivated = false;
this.preloadedPackages = {};
this.loadedPackages = {};
this.activePackages = {};
this.activatingPackages = {};
this.packageStates = {};
this.serviceHub = new ServiceHub();
this.packageActivators = [];
this.registerPackageActivator(this, ['atom', 'textmate']);
}
initialize(params) {
this.devMode = params.devMode;
this.resourcePath = params.resourcePath;
if (params.configDirPath != null && !params.safeMode) {
if (this.devMode) {
this.packageDirPaths.push(
path.join(params.configDirPath, 'dev', 'packages')
);
this.packageDirPaths.push(path.join(this.resourcePath, 'packages'));
}
this.packageDirPaths.push(path.join(params.configDirPath, 'packages'));
}
}
setContextMenuManager(contextMenuManager) {
this.contextMenuManager = contextMenuManager;
}
setMenuManager(menuManager) {
this.menuManager = menuManager;
}
setThemeManager(themeManager) {
this.themeManager = themeManager;
}
async reset() {
this.serviceHub.clear();
await this.deactivatePackages();
this.loadedPackages = {};
this.preloadedPackages = {};
this.packageStates = {};
this.packagesCache =
packageJSON._atomPackages != null ? packageJSON._atomPackages : {};
this.packageDependencies =
packageJSON.packageDependencies != null
? packageJSON.packageDependencies
: {};
this.triggeredActivationHooks.clear();
this.activatePromise = null;
}
/*
Section: Event Subscription
*/
// Public: Invoke the given callback when all packages have been loaded.
//
// * `callback` {Function}
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidLoadInitialPackages(callback) {
return this.emitter.on('did-load-initial-packages', callback);
}
// Public: Invoke the given callback when all packages have been activated.
//
// * `callback` {Function}
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidActivateInitialPackages(callback) {
return this.emitter.on('did-activate-initial-packages', callback);
}
getActivatePromise() {
if (this.activatePromise) {
return this.activatePromise;
} else {
return Promise.resolve();
}
}
// Public: Invoke the given callback when a package is activated.
//
// * `callback` A {Function} to be invoked when a package is activated.
// * `package` The {Package} that was activated.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidActivatePackage(callback) {
return this.emitter.on('did-activate-package', callback);
}
// Public: Invoke the given callback when a package is deactivated.
//
// * `callback` A {Function} to be invoked when a package is deactivated.
// * `package` The {Package} that was deactivated.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidDeactivatePackage(callback) {
return this.emitter.on('did-deactivate-package', callback);
}
// Public: Invoke the given callback when a package is loaded.
//
// * `callback` A {Function} to be invoked when a package is loaded.
// * `package` The {Package} that was loaded.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidLoadPackage(callback) {
return this.emitter.on('did-load-package', callback);
}
// Public: Invoke the given callback when a package is unloaded.
//
// * `callback` A {Function} to be invoked when a package is unloaded.
// * `package` The {Package} that was unloaded.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
onDidUnloadPackage(callback) {
return this.emitter.on('did-unload-package', callback);
}
/*
Section: Package system data
*/
// Public: Get the path to the apm command.
//
// Uses the value of the `core.apmPath` config setting if it exists.
//
// Return a {String} file path to apm.
getApmPath() {
const configPath = atom.config.get('core.apmPath');
if (configPath || this.apmPath) {
return configPath || this.apmPath;
}
const commandName = process.platform === 'win32' ? 'apm.cmd' : 'apm';
const apmRoot = path.join(process.resourcesPath, 'app', 'apm');
this.apmPath = path.join(apmRoot, 'bin', commandName);
if (!fs.isFileSync(this.apmPath)) {
this.apmPath = path.join(
apmRoot,
'node_modules',
'atom-package-manager',
'bin',
commandName
);
}
return this.apmPath;
}
// Public: Get the paths being used to look for packages.
//
// Returns an {Array} of {String} directory paths.
getPackageDirPaths() {
return _.clone(this.packageDirPaths);
}
/*
Section: General package data
*/
// Public: Resolve the given package name to a path on disk.
//
// * `name` - The {String} package name.
//
// Return a {String} folder path or undefined if it could not be resolved.
resolvePackagePath(name) {
if (fs.isDirectorySync(name)) {
return name;
}
let packagePath = fs.resolve(...this.packageDirPaths, name);
if (fs.isDirectorySync(packagePath)) {
return packagePath;
}
packagePath = path.join(this.resourcePath, 'node_modules', name);
if (this.hasAtomEngine(packagePath)) {
return packagePath;
}
return null;
}
// Public: Is the package with the given name bundled with Atom?
//
// * `name` - The {String} package name.
//
// Returns a {Boolean}.
isBundledPackage(name) {
return this.getPackageDependencies().hasOwnProperty(name);
}
isDeprecatedPackage(name, version) {
const metadata = this.deprecatedPackages[name];
if (!metadata) return false;
if (!metadata.version) return true;
let range = this.deprecatedPackageRanges[metadata.version];
if (!range) {
try {
range = new ModuleCache.Range(metadata.version);
} catch (error) {
range = NullVersionRange;
}
this.deprecatedPackageRanges[metadata.version] = range;
}
return range.test(version);
}
getDeprecatedPackageMetadata(name) {
const metadata = this.deprecatedPackages[name];
if (metadata) Object.freeze(metadata);
return metadata;
}
/*
Section: Enabling and disabling packages
*/
// Public: Enable the package with the given name.
//
// * `name` - The {String} package name.
//
// Returns the {Package} that was enabled or null if it isn't loaded.
enablePackage(name) {
const pack = this.loadPackage(name);
if (pack != null) {
pack.enable();
}
return pack;
}
// Public: Disable the package with the given name.
//
// * `name` - The {String} package name.
//
// Returns the {Package} that was disabled or null if it isn't loaded.
disablePackage(name) {
const pack = this.loadPackage(name);
if (!this.isPackageDisabled(name) && pack != null) {
pack.disable();
}
return pack;
}
// Public: Is the package with the given name disabled?
//
// * `name` - The {String} package name.
//
// Returns a {Boolean}.
isPackageDisabled(name) {
return _.include(this.config.get('core.disabledPackages') || [], name);
}
/*
Section: Accessing active packages
*/
// Public: Get an {Array} of all the active {Package}s.
getActivePackages() {
return _.values(this.activePackages);
}
// Public: Get the active {Package} with the given name.
//
// * `name` - The {String} package name.
//
// Returns a {Package} or undefined.
getActivePackage(name) {
return this.activePackages[name];
}
// Public: Is the {Package} with the given name active?
//
// * `name` - The {String} package name.
//
// Returns a {Boolean}.
isPackageActive(name) {
return this.getActivePackage(name) != null;
}
// Public: Returns a {Boolean} indicating whether package activation has occurred.
hasActivatedInitialPackages() {
return this.initialPackagesActivated;
}
/*
Section: Accessing loaded packages
*/
// Public: Get an {Array} of all the loaded {Package}s
getLoadedPackages() {
return _.values(this.loadedPackages);
}
// Get packages for a certain package type
//
// * `types` an {Array} of {String}s like ['atom', 'textmate'].
getLoadedPackagesForTypes(types) {
return this.getLoadedPackages().filter(p => types.includes(p.getType()));
}
// Public: Get the loaded {Package} with the given name.
//
// * `name` - The {String} package name.
//
// Returns a {Package} or undefined.
getLoadedPackage(name) {
return this.loadedPackages[name];
}
// Public: Is the package with the given name loaded?
//
// * `name` - The {String} package name.
//
// Returns a {Boolean}.
isPackageLoaded(name) {
return this.getLoadedPackage(name) != null;
}
// Public: Returns a {Boolean} indicating whether package loading has occurred.
hasLoadedInitialPackages() {
return this.initialPackagesLoaded;
}
/*
Section: Accessing available packages
*/
// Public: Returns an {Array} of {String}s of all the available package paths.
getAvailablePackagePaths() {
return this.getAvailablePackages().map(a => a.path);
}
// Public: Returns an {Array} of {String}s of all the available package names.
getAvailablePackageNames() {
return this.getAvailablePackages().map(a => a.name);
}
// Public: Returns an {Array} of {String}s of all the available package metadata.
getAvailablePackageMetadata() {
const packages = [];
for (const pack of this.getAvailablePackages()) {
const loadedPackage = this.getLoadedPackage(pack.name);
const metadata =
loadedPackage != null
? loadedPackage.metadata
: this.loadPackageMetadata(pack, true);
packages.push(metadata);
}
return packages;
}
getAvailablePackages() {
const packages = [];
const packagesByName = new Set();
for (const packageDirPath of this.packageDirPaths) {
if (fs.isDirectorySync(packageDirPath)) {
// checks for directories.
// dirent is faster, but for checking symbolic link we need stat.
const packageNames = fs
.readdirSync(packageDirPath, { withFileTypes: true })
.filter(
dirent =>
dirent.isDirectory() ||
(dirent.isSymbolicLink() &&
fs.isDirectorySync(path.join(packageDirPath, dirent.name)))
)
.map(dirent => dirent.name);
for (const packageName of packageNames) {
if (
!packageName.startsWith('.') &&
!packagesByName.has(packageName)
) {
const packagePath = path.join(packageDirPath, packageName);
packages.push({
name: packageName,
path: packagePath,
isBundled: false
});
packagesByName.add(packageName);
}
}
}
}
for (const packageName in this.packageDependencies) {
if (!packagesByName.has(packageName)) {
packages.push({
name: packageName,
path: path.join(this.resourcePath, 'node_modules', packageName),
isBundled: true
});
}
}
return packages.sort((a, b) => a.name.localeCompare(b.name));
}
/*
Section: Private
*/
getPackageState(name) {
return this.packageStates[name];
}
setPackageState(name, state) {
this.packageStates[name] = state;
}
getPackageDependencies() {
return this.packageDependencies;
}
hasAtomEngine(packagePath) {
const metadata = this.loadPackageMetadata(packagePath, true);
return (
metadata != null &&
metadata.engines != null &&
metadata.engines.atom != null
);
}
unobserveDisabledPackages() {
if (this.disabledPackagesSubscription != null) {
this.disabledPackagesSubscription.dispose();
}
this.disabledPackagesSubscription = null;
}
observeDisabledPackages() {
if (this.disabledPackagesSubscription != null) {
return;
}
this.disabledPackagesSubscription = this.config.onDidChange(
'core.disabledPackages',
({ newValue, oldValue }) => {
const packagesToEnable = _.difference(oldValue, newValue);
const packagesToDisable = _.difference(newValue, oldValue);
packagesToDisable.forEach(name => {
if (this.getActivePackage(name)) this.deactivatePackage(name);
});
packagesToEnable.forEach(name => this.activatePackage(name));
return null;
}
);
}
unobservePackagesWithKeymapsDisabled() {
if (this.packagesWithKeymapsDisabledSubscription != null) {
this.packagesWithKeymapsDisabledSubscription.dispose();
}
this.packagesWithKeymapsDisabledSubscription = null;
}
observePackagesWithKeymapsDisabled() {
if (this.packagesWithKeymapsDisabledSubscription != null) {
return;
}
const performOnLoadedActivePackages = (
packageNames,
disabledPackageNames,
action
) => {
for (const packageName of packageNames) {
if (!disabledPackageNames.has(packageName)) {
const pack = this.getLoadedPackage(packageName);
if (pack != null) {
action(pack);
}
}
}
};
this.packagesWithKeymapsDisabledSubscription = this.config.onDidChange(
'core.packagesWithKeymapsDisabled',
({ newValue, oldValue }) => {
const keymapsToEnable = _.difference(oldValue, newValue);
const keymapsToDisable = _.difference(newValue, oldValue);
const disabledPackageNames = new Set(
this.config.get('core.disabledPackages')
);
performOnLoadedActivePackages(
keymapsToDisable,
disabledPackageNames,
p => p.deactivateKeymaps()
);
performOnLoadedActivePackages(
keymapsToEnable,
disabledPackageNames,
p => p.activateKeymaps()
);
return null;
}
);
}
preloadPackages() {
const result = [];
for (const packageName in this.packagesCache) {
result.push(
this.preloadPackage(packageName, this.packagesCache[packageName])
);
}
return result;
}
preloadPackage(packageName, pack) {
const metadata = pack.metadata || {};
if (typeof metadata.name !== 'string' || metadata.name.length < 1) {
metadata.name = packageName;
}
if (
metadata.repository != null &&
metadata.repository.type === 'git' &&
typeof metadata.repository.url === 'string'
) {
metadata.repository.url = metadata.repository.url.replace(
/(^git\+)|(\.git$)/g,
''
);
}
const options = {
path: pack.rootDirPath,
name: packageName,
preloadedPackage: true,
bundledPackage: true,
metadata,
packageManager: this,
config: this.config,
styleManager: this.styleManager,
commandRegistry: this.commandRegistry,
keymapManager: this.keymapManager,
notificationManager: this.notificationManager,
grammarRegistry: this.grammarRegistry,
themeManager: this.themeManager,
menuManager: this.menuManager,
contextMenuManager: this.contextMenuManager,
deserializerManager: this.deserializerManager,
viewRegistry: this.viewRegistry
};
pack = metadata.theme ? new ThemePackage(options) : new Package(options);
pack.preload();
this.preloadedPackages[packageName] = pack;
return pack;
}
loadPackages() {
// Ensure atom exports is already in the require cache so the load time
// of the first package isn't skewed by being the first to require atom
require('../exports/atom');
const disabledPackageNames = new Set(
this.config.get('core.disabledPackages')
);
this.config.transact(() => {
for (const pack of this.getAvailablePackages()) {
this.loadAvailablePackage(pack, disabledPackageNames);
}
});
this.initialPackagesLoaded = true;
this.emitter.emit('did-load-initial-packages');
}
loadPackage(nameOrPath) {
if (path.basename(nameOrPath)[0].match(/^\./)) {
// primarily to skip .git folder
return null;
}
const pack = this.getLoadedPackage(nameOrPath);
if (pack) {
return pack;
}
const packagePath = this.resolvePackagePath(nameOrPath);
if (packagePath) {
const name = path.basename(nameOrPath);
return this.loadAvailablePackage({
name,
path: packagePath,
isBundled: this.isBundledPackagePath(packagePath)
});
}
console.warn(`Could not resolve '${nameOrPath}' to a package path`);
return null;
}
loadAvailablePackage(availablePackage, disabledPackageNames) {
const preloadedPackage = this.preloadedPackages[availablePackage.name];
if (
disabledPackageNames != null &&
disabledPackageNames.has(availablePackage.name)
) {
if (preloadedPackage != null) {
preloadedPackage.deactivate();
delete preloadedPackage[availablePackage.name];
}
return null;
}
const loadedPackage = this.getLoadedPackage(availablePackage.name);
if (loadedPackage != null) {
return loadedPackage;
}
if (preloadedPackage != null) {
if (availablePackage.isBundled) {
preloadedPackage.finishLoading();
this.loadedPackages[availablePackage.name] = preloadedPackage;
return preloadedPackage;
} else {
preloadedPackage.deactivate();
delete preloadedPackage[availablePackage.name];
}
}
let metadata;
try {
metadata = this.loadPackageMetadata(availablePackage) || {};
} catch (error) {
this.handleMetadataError(error, availablePackage.path);
return null;
}
if (
!availablePackage.isBundled &&
this.isDeprecatedPackage(metadata.name, metadata.version)
) {
console.warn(
`Could not load ${metadata.name}@${
metadata.version
} because it uses deprecated APIs that have been removed.`
);
return null;
}
const options = {
path: availablePackage.path,
name: availablePackage.name,
metadata,
bundledPackage: availablePackage.isBundled,
packageManager: this,
config: this.config,
styleManager: this.styleManager,
commandRegistry: this.commandRegistry,
keymapManager: this.keymapManager,
notificationManager: this.notificationManager,
grammarRegistry: this.grammarRegistry,
themeManager: this.themeManager,
menuManager: this.menuManager,
contextMenuManager: this.contextMenuManager,
deserializerManager: this.deserializerManager,
viewRegistry: this.viewRegistry
};
const pack = metadata.theme
? new ThemePackage(options)
: new Package(options);
pack.load();
this.loadedPackages[pack.name] = pack;
this.emitter.emit('did-load-package', pack);
return pack;
}
unloadPackages() {
_.keys(this.loadedPackages).forEach(name => this.unloadPackage(name));
}
unloadPackage(name) {
if (this.isPackageActive(name)) {
throw new Error(`Tried to unload active package '${name}'`);
}
const pack = this.getLoadedPackage(name);
if (pack) {
delete this.loadedPackages[pack.name];
this.emitter.emit('did-unload-package', pack);
} else {
throw new Error(`No loaded package for name '${name}'`);
}
}
// Activate all the packages that should be activated.
activate() {
let promises = [];
for (let [activator, types] of this.packageActivators) {
const packages = this.getLoadedPackagesForTypes(types);
promises = promises.concat(activator.activatePackages(packages));
}
this.activatePromise = Promise.all(promises).then(() => {
this.triggerDeferredActivationHooks();
this.initialPackagesActivated = true;
this.emitter.emit('did-activate-initial-packages');
this.activatePromise = null;
});
return this.activatePromise;
}
registerURIHandlerForPackage(packageName, handler) {
return this.uriHandlerRegistry.registerHostHandler(packageName, handler);
}
// another type of package manager can handle other package types.
// See ThemeManager
registerPackageActivator(activator, types) {
this.packageActivators.push([activator, types]);
}
activatePackages(packages) {
const promises = [];
this.config.transactAsync(() => {
for (const pack of packages) {
const promise = this.activatePackage(pack.name);
if (!pack.activationShouldBeDeferred()) {
promises.push(promise);
}
}
return Promise.all(promises);
});
this.observeDisabledPackages();
this.observePackagesWithKeymapsDisabled();
return promises;
}
// Activate a single package by name
activatePackage(name) {
let pack = this.getActivePackage(name);
if (pack) {
return Promise.resolve(pack);
}
pack = this.loadPackage(name);
if (!pack) {
return Promise.reject(new Error(`Failed to load package '${name}'`));
}
this.activatingPackages[pack.name] = pack;
const activationPromise = pack.activate().then(() => {
if (this.activatingPackages[pack.name] != null) {
delete this.activatingPackages[pack.name];
this.activePackages[pack.name] = pack;
this.emitter.emit('did-activate-package', pack);
}
return pack;
});
if (this.deferredActivationHooks == null) {
this.triggeredActivationHooks.forEach(hook =>
this.activationHookEmitter.emit(hook)
);
}
return activationPromise;
}
triggerDeferredActivationHooks() {
if (this.deferredActivationHooks == null) {
return;
}
for (const hook of this.deferredActivationHooks) {
this.activationHookEmitter.emit(hook);
}
this.deferredActivationHooks = null;
}
triggerActivationHook(hook) {
if (hook == null || !_.isString(hook) || hook.length <= 0) {
return new Error('Cannot trigger an empty activation hook');
}
this.triggeredActivationHooks.add(hook);
if (this.deferredActivationHooks != null) {
this.deferredActivationHooks.push(hook);
} else {
this.activationHookEmitter.emit(hook);
}
}
onDidTriggerActivationHook(hook, callback) {
if (hook == null || !_.isString(hook) || hook.length <= 0) {
return;
}
return this.activationHookEmitter.on(hook, callback);
}
serialize() {
for (const pack of this.getActivePackages()) {
this.serializePackage(pack);
}
return this.packageStates;
}
serializePackage(pack) {
if (typeof pack.serialize === 'function') {
this.setPackageState(pack.name, pack.serialize());
}
}
// Deactivate all packages
async deactivatePackages() {
await this.config.transactAsync(() =>
Promise.all(
this.getLoadedPackages().map(pack =>
this.deactivatePackage(pack.name, true)
)
)
);
this.unobserveDisabledPackages();
this.unobservePackagesWithKeymapsDisabled();
}
// Deactivate the package with the given name
async deactivatePackage(name, suppressSerialization) {
const pack = this.getLoadedPackage(name);
if (pack == null) {
return;
}
if (!suppressSerialization && this.isPackageActive(pack.name)) {
this.serializePackage(pack);
}
const deactivationResult = pack.deactivate();
if (deactivationResult && typeof deactivationResult.then === 'function') {
await deactivationResult;
}
delete this.activePackages[pack.name];
delete this.activatingPackages[pack.name];
this.emitter.emit('did-deactivate-package', pack);
}
handleMetadataError(error, packagePath) {
const metadataPath = path.join(packagePath, 'package.json');
const detail = `${error.message} in ${metadataPath}`;
const stack = `${error.stack}\n at ${metadataPath}:1:1`;
const message = `Failed to load the ${path.basename(packagePath)} package`;
this.notificationManager.addError(message, {
stack,
detail,
packageName: path.basename(packagePath),
dismissable: true
});
}
uninstallDirectory(directory) {
const symlinkPromise = new Promise(resolve =>
fs.isSymbolicLink(directory, isSymLink => resolve(isSymLink))
);
const dirPromise = new Promise(resolve =>
fs.isDirectory(directory, isDir => resolve(isDir))
);
return Promise.all([symlinkPromise, dirPromise]).then(values => {
const [isSymLink, isDir] = values;
if (!isSymLink && isDir) {
return fs.remove(directory, function() {});
}
});
}
reloadActivePackageStyleSheets() {
for (const pack of this.getActivePackages()) {
if (
pack.getType() !== 'theme' &&
typeof pack.reloadStylesheets === 'function'
) {
pack.reloadStylesheets();
}
}
}
isBundledPackagePath(packagePath) {
if (
this.devMode &&
!this.resourcePath.startsWith(`${process.resourcesPath}${path.sep}`)
) {
return false;
}
if (this.resourcePathWithTrailingSlash == null) {
this.resourcePathWithTrailingSlash = `${this.resourcePath}${path.sep}`;
}
return (
packagePath != null &&
packagePath.startsWith(this.resourcePathWithTrailingSlash)
);
}
loadPackageMetadata(packagePathOrAvailablePackage, ignoreErrors = false) {
let isBundled, packageName, packagePath;
if (typeof packagePathOrAvailablePackage === 'object') {
const availablePackage = packagePathOrAvailablePackage;
packageName = availablePackage.name;
packagePath = availablePackage.path;
isBundled = availablePackage.isBundled;
} else {
packagePath = packagePathOrAvailablePackage;
packageName = path.basename(packagePath);
isBundled = this.isBundledPackagePath(packagePath);
}
let metadata;
if (isBundled && this.packagesCache[packageName] != null) {
metadata = this.packagesCache[packageName].metadata;
}
if (metadata == null) {
const metadataPath = CSON.resolve(path.join(packagePath, 'package'));
if (metadataPath) {
try {
metadata = CSON.readFileSync(metadataPath);
this.normalizePackageMetadata(metadata);
} catch (error) {
if (!ignoreErrors) {
throw error;
}
}
}
}
if (metadata == null) {
metadata = {};