forked from meteor/meteor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
project-context.js
1751 lines (1509 loc) · 60.9 KB
/
project-context.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
var assert = require("assert");
var _ = require('underscore');
var archinfo = require('./utils/archinfo.js');
var buildmessage = require('./utils/buildmessage.js');
var catalog = require('./packaging/catalog/catalog.js');
var catalogLocal = require('./packaging/catalog/catalog-local.js');
var Console = require('./console/console.js').Console;
var files = require('./fs/files.js');
var isopackCacheModule = require('./isobuild/isopack-cache.js');
import { loadIsopackage } from './tool-env/isopackets.js';
var packageMapModule = require('./packaging/package-map.js');
var release = require('./packaging/release.js');
var tropohouse = require('./packaging/tropohouse.js');
var utils = require('./utils/utils.js');
var watch = require('./fs/watch.js');
var Profile = require('./tool-env/profile.js').Profile;
import { KNOWN_ISOBUILD_FEATURE_PACKAGES } from './isobuild/compiler.js';
import {
optimisticReadJsonOrNull,
optimisticHashOrNull,
} from "./fs/optimistic.js";
import {
mapWhereToArches,
} from "./isobuild/package-api.js";
import Resolver from "./isobuild/resolver.js";
// The ProjectContext represents all the context associated with an app:
// metadata files in the `.meteor` directory, the choice of package versions
// used by it, etc. Any time you want to work with an app, create a
// ProjectContext and call prepareProjectForBuild on it (in a buildmessage
// context).
//
// Note that this should only be used by parts of the code that truly require a
// full project to exist; you won't find any reference to ProjectContext in
// compiler.js or isopack.js, which work on individual files (though they will
// get references to some of the objects which can be stored in a ProjectContext
// such as PackageMap and IsopackCache). Parts of the code that should deal
// with ProjectContext include command implementations, the parts of bundler.js
// that deal with creating a full project, PackageSource.initFromAppDir, stats
// reporting, etc.
//
// Classes in this file follow the standard protocol where names beginning with
// _ should not be externally accessed.
function ProjectContext(options) {
var self = this;
assert.ok(self instanceof ProjectContext);
if (!options.projectDir)
throw Error("missing projectDir!");
self.originalOptions = options;
self.reset();
}
exports.ProjectContext = ProjectContext;
// The value is the name of the method to call to continue.
var STAGE = {
INITIAL: '_readProjectMetadata',
READ_PROJECT_METADATA: '_initializeCatalog',
INITIALIZE_CATALOG: '_resolveConstraints',
RESOLVE_CONSTRAINTS: '_downloadMissingPackages',
DOWNLOAD_MISSING_PACKAGES: '_buildLocalPackages',
BUILD_LOCAL_PACKAGES: '_saveChangedMetadata',
SAVE_CHANGED_METADATA: 'DONE'
};
_.extend(ProjectContext.prototype, {
reset: function (moreOptions, resetOptions) {
var self = this;
// Allow overriding some options until the next call to reset;
var options = _.extend({}, self.originalOptions, moreOptions);
// This is options that are actually directed at reset itself.
resetOptions = resetOptions || {};
self.projectDir = options.projectDir;
self.tropohouse = options.tropohouse || tropohouse.default;
self._includePackages = options.includePackages;
self._packageMapFilename = options.packageMapFilename ||
files.pathJoin(self.projectDir, '.meteor', 'versions');
self._serverArchitectures = options.serverArchitectures || [];
// We always need to download host versions of packages, at least for
// plugins.
self._serverArchitectures.push(archinfo.host());
self._serverArchitectures = _.uniq(self._serverArchitectures);
// test-packages overrides this to load local packages from your real app
// instead of from test-runner-app.
self._projectDirForLocalPackages = options.projectDirForLocalPackages ||
options.projectDir;
self._explicitlyAddedLocalPackageDirs =
options.explicitlyAddedLocalPackageDirs;
// Used to override the directory that Meteor's build process
// writes to; used by `meteor test` so that you can test your
// app in parallel to writing it, with an isolated database.
// You can override the default .meteor/local by specifying
// METEOR_LOCAL_DIR. You can use relative path if you want it
// relative to your project directory.
self.projectLocalDir = process.env.METEOR_LOCAL_DIR ?
files.pathResolve(options.projectDir,
files.convertToStandardPath(process.env.METEOR_LOCAL_DIR))
: (options.projectLocalDir ||
files.pathJoin(self.projectDir, '.meteor', 'local'));
// Used by 'meteor rebuild'; true to rebuild all packages, or a list of
// package names. Deletes the isopacks and their plugin caches.
self._forceRebuildPackages = options.forceRebuildPackages;
// Set in a few cases where we really want to only get packages from
// checkout.
self._ignorePackageDirsEnvVar = options.ignorePackageDirsEnvVar;
// Set by some tests where we want to pretend that we don't have packages in
// the git checkout (because they're using a fake warehouse).
self._ignoreCheckoutPackages = options.ignoreCheckoutPackages;
// Set by some tests to override the official catalog.
self._officialCatalog = options.officialCatalog || catalog.official;
if (options.alwaysWritePackageMap && options.neverWritePackageMap)
throw Error("always or never?");
// Set by 'meteor create' and 'meteor update' to ensure that
// .meteor/versions is always written even if release.current does not match
// the project's release.
self._alwaysWritePackageMap = options.alwaysWritePackageMap;
// Set by a few special-case commands that call
// projectConstraintsFile.addConstraints for internal reasons without
// intending to actually write .meteor/packages and .meteor/versions (eg,
// 'publish' wants to make sure making sure the test is built, and
// --get-ready wants to build every conceivable package).
self._neverWriteProjectConstraintsFile =
options.neverWriteProjectConstraintsFile;
self._neverWritePackageMap = options.neverWritePackageMap;
// Set by 'meteor update' to specify which packages may be updated. Array of
// package names.
self._upgradePackageNames = options.upgradePackageNames;
// Set by 'meteor update' to mean that we should upgrade the
// "patch" (and wrapNum, etc.) parts of indirect dependencies.
self._upgradeIndirectDepPatchVersions =
options.upgradeIndirectDepPatchVersions;
// Set by publishing commands to ensure that published packages always have
// a web.cordova slice (because we aren't yet smart enough to just default
// to using the web.browser slice instead or make a common 'web' slice).
self._forceIncludeCordovaUnibuild = options.forceIncludeCordovaUnibuild;
// If explicitly specified as null, use no release for constraints.
// If specified non-null, should be a release version catalog record.
// If not specified, defaults to release.current.
//
// Note that NONE of these cases are "use the release from
// self.releaseFile"; after all, if you are explicitly running `meteor
// --release foo` it will override what is found in .meteor/releases.
if (_.has(options, 'releaseForConstraints')) {
self._releaseForConstraints = options.releaseForConstraints || null;
} else if (release.current.isCheckout()) {
self._releaseForConstraints = null;
} else {
self._releaseForConstraints = release.current.getCatalogReleaseData();
}
if (resetOptions.preservePackageMap && self.packageMap) {
self._cachedVersionsBeforeReset = self.packageMap.toVersionMap();
// packageMapFile should always exist if packageMap does
self._oldPackageMapFileHash = self.packageMapFile.fileHash;
} else {
self._cachedVersionsBeforeReset = null;
self._oldPackageMapFileHash = null;
}
// The --allow-incompatible-update command-line switch, which allows
// the version solver to choose versions of root dependencies that are
// incompatible with the previously chosen versions (i.e. to downgrade
// them or change their major version).
self._allowIncompatibleUpdate = options.allowIncompatibleUpdate;
// If set, we run the linter on the app and local packages. Set by 'meteor
// lint', and the runner commands (run/test-packages/debug) when --no-lint
// is not passed.
self.lintAppAndLocalPackages = options.lintAppAndLocalPackages;
// If set, we run the linter on just one local package, with this
// source root. Set by 'meteor lint' in a package, and 'meteor publish'.
self._lintPackageWithSourceRoot = options.lintPackageWithSourceRoot;
// Initialized by readProjectMetadata.
self.releaseFile = null;
self.projectConstraintsFile = null;
self.packageMapFile = null;
self.platformList = null;
self.cordovaPluginsFile = null;
self.appIdentifier = null;
self.finishedUpgraders = null;
// Initialized by initializeCatalog.
self.projectCatalog = null;
self.localCatalog = null;
// Once the catalog is read and the names of the "explicitly
// added" packages are determined, they will be listed here.
// (See explicitlyAddedLocalPackageDirs.)
// "Explicitly added" packages are typically present in non-app
// projects, like the one created by `meteor publish`. This list
// is used to avoid pinning such packages to their previous
// versions when we run the version solver, which prevents an
// error telling you to pass `--allow-incompatible-update` when
// you publish your package after bumping the major version.
self.explicitlyAddedPackageNames = null;
// Initialized by _resolveConstraints.
self.packageMap = null;
self.packageMapDelta = null;
if (resetOptions.softRefreshIsopacks && self.isopackCache) {
// Make sure we only hold on to one old isopack cache, not a linked list
// of all of them.
self.isopackCache.forgetPreviousIsopackCache();
self._previousIsopackCache = self.isopackCache;
} else {
self._previousIsopackCache = null;
}
// Initialized by _buildLocalPackages.
self.isopackCache = null;
self._completedStage = STAGE.INITIAL;
// The resolverResultCache is used by the constraint solver; to
// us it's just an opaque object. If we pass it into repeated
// calls to the constraint solver, the constraint solver can be
// more efficient by caching or memoizing its work. We choose not
// to reset this when reset() is called more than once.
self._readResolverResultCache();
},
readProjectMetadata: function () {
// don't generate a profiling report for this stage (Profile.run),
// because all we do here is read a handful of files.
this._completeStagesThrough(STAGE.READ_PROJECT_METADATA);
},
initializeCatalog: function () {
Profile.run('ProjectContext initializeCatalog', () => {
this._completeStagesThrough(STAGE.INITIALIZE_CATALOG);
});
},
resolveConstraints: function () {
Profile.run('ProjectContext resolveConstraints', () => {
this._completeStagesThrough(STAGE.RESOLVE_CONSTRAINTS);
});
},
downloadMissingPackages: function () {
Profile.run('ProjectContext downloadMissingPackages', () => {
this._completeStagesThrough(STAGE.DOWNLOAD_MISSING_PACKAGES);
});
},
buildLocalPackages: function () {
Profile.run('ProjectContext buildLocalPackages', () => {
this._completeStagesThrough(STAGE.BUILD_LOCAL_PACKAGES);
});
},
saveChangedMetadata: function () {
Profile.run('ProjectContext saveChangedMetadata', () => {
this._completeStagesThrough(STAGE.SAVE_CHANGED_METADATA);
});
},
prepareProjectForBuild: function () {
// This is the same as saveChangedMetadata, but if we insert stages after
// that one it will continue to mean "fully finished".
Profile.run('ProjectContext prepareProjectForBuild', () => {
this._completeStagesThrough(STAGE.SAVE_CHANGED_METADATA);
});
},
_completeStagesThrough: function (targetStage) {
var self = this;
buildmessage.assertInCapture();
buildmessage.enterJob('preparing project', function () {
while (self._completedStage !== targetStage) {
// This error gets thrown if you request to go to a stage that's earlier
// than where you started. Note that the error will be mildly confusing
// because the key of STAGE does not match the value.
if (self.completedStage === STAGE.SAVE_CHANGED_METADATA)
throw Error("can't find requested stage " + targetStage);
// The actual value of STAGE.FOO is the name of the method that takes
// you to the next step after FOO.
self[self._completedStage]();
if (buildmessage.jobHasMessages())
return;
}
});
},
getProjectLocalDirectory: function (subdirectory) {
var self = this;
return files.pathJoin(self.projectLocalDir, subdirectory);
},
getMeteorShellDirectory: function(projectDir) {
return this.getProjectLocalDirectory("shell");
},
// You can call this manually (that is, the public version without
// an `_`) if you want to do some work before resolving constraints,
// or you can let prepareProjectForBuild do it for you.
//
// This should be pretty fast --- for example, we shouldn't worry about
// needing to wait for it to be done before we open the runner proxy.
_readProjectMetadata: Profile('_readProjectMetadata', function () {
var self = this;
buildmessage.assertInCapture();
buildmessage.enterJob('reading project metadata', function () {
// Ensure this is actually a project directory.
self._ensureProjectDir();
if (buildmessage.jobHasMessages())
return;
// Read .meteor/release.
self.releaseFile = new exports.ReleaseFile({
projectDir: self.projectDir,
catalog: self._officialCatalog,
});
if (buildmessage.jobHasMessages())
return;
// Read .meteor/packages.
self.projectConstraintsFile = new exports.ProjectConstraintsFile({
projectDir: self.projectDir,
includePackages: self._includePackages
});
if (buildmessage.jobHasMessages())
return;
// Read .meteor/versions.
self.packageMapFile = new exports.PackageMapFile({
filename: self._packageMapFilename
});
if (buildmessage.jobHasMessages())
return;
// Read .meteor/cordova-plugins.
self.cordovaPluginsFile = new exports.CordovaPluginsFile({
projectDir: self.projectDir
});
if (buildmessage.jobHasMessages())
return;
// Read .meteor/platforms, creating it if necessary.
self.platformList = new exports.PlatformList({
projectDir: self.projectDir
});
if (buildmessage.jobHasMessages())
return;
// Read .meteor/.id, creating it if necessary.
self._ensureAppIdentifier();
if (buildmessage.jobHasMessages())
return;
// Set up an object that knows how to read and write
// .meteor/.finished-upgraders.
self.finishedUpgraders = new exports.FinishedUpgraders({
projectDir: self.projectDir
});
if (buildmessage.jobHasMessages())
return;
self.meteorConfig = new MeteorConfig({
appDirectory: self.projectDir,
});
if (buildmessage.jobHasMessages()) {
return;
}
});
self._completedStage = STAGE.READ_PROJECT_METADATA;
}),
// Write the new release to .meteor/release and create a
// .meteor/dev_bundle symlink to the corresponding dev_bundle.
writeReleaseFileAndDevBundleLink(releaseName) {
assert.strictEqual(files.inCheckout(), false);
this.releaseFile.write(releaseName);
},
_ensureProjectDir: function () {
var self = this;
files.mkdir_p(files.pathJoin(self.projectDir, '.meteor'));
// This file existing is what makes a project directory a project directory,
// so let's make sure it exists!
var constraintFilePath = files.pathJoin(self.projectDir, '.meteor', 'packages');
if (! files.exists(constraintFilePath)) {
files.writeFileAtomically(constraintFilePath, '');
}
// Let's also make sure we have a minimal gitignore.
var gitignorePath = files.pathJoin(self.projectDir, '.meteor', '.gitignore');
if (! files.exists(gitignorePath)) {
files.writeFileAtomically(gitignorePath, 'local\n');
}
},
// This is a WatchSet that ends up being the WatchSet for the app's
// initFromAppDir PackageSource. Changes to this will cause the whole app to
// be rebuilt (client and server).
getProjectWatchSet: function () {
// We don't cache a projectWatchSet on this object, since some of the
// metadata files can be written by us (eg .meteor/versions
// post-constraint-solve).
var self = this;
var watchSet = new watch.WatchSet;
_.each(
[self.releaseFile, self.projectConstraintsFile, self.packageMapFile,
self.platformList, self.cordovaPluginsFile],
function (metadataFile) {
metadataFile && watchSet.merge(metadataFile.watchSet);
});
if (self.localCatalog) {
watchSet.merge(self.localCatalog.packageLocationWatchSet);
}
return watchSet;
},
// This WatchSet encompasses everything that users can change to restart an
// app. We only watch this for failed bundles; for successful bundles, we have
// more precise server-specific and client-specific WatchSets that add up to
// this one.
getProjectAndLocalPackagesWatchSet: function () {
var self = this;
var watchSet = self.getProjectWatchSet();
// Include the loaded local packages (ie, the non-metadata files) but only
// if we've actually gotten to the buildLocalPackages step.
if (self.isopackCache) {
watchSet.merge(self.isopackCache.allLoadedLocalPackagesWatchSet);
}
return watchSet;
},
getLintingMessagesForLocalPackages: function () {
var self = this;
return self.isopackCache.getLintingMessagesForLocalPackages();
},
_ensureAppIdentifier: function () {
var self = this;
var identifierFile = files.pathJoin(self.projectDir, '.meteor', '.id');
// Find the first non-empty line, ignoring comments. We intentionally don't
// put this in a WatchSet, since changing this doesn't affect the built app
// much (and there's no real reason to update it anyway).
var lines = files.getLinesOrEmpty(identifierFile);
var appId = _.find(_.map(lines, files.trimSpaceAndComments), _.identity);
// If the file doesn't exist or has no non-empty lines, regenerate the
// token.
if (!appId) {
appId = [
utils.randomIdentifier(),
utils.randomIdentifier()
].join(".");
var comment = (
"# This file contains a token that is unique to your project.\n" +
"# Check it into your repository along with the rest of this directory.\n" +
"# It can be used for purposes such as:\n" +
"# - ensuring you don't accidentally deploy one app on top of another\n" +
"# - providing package authors with aggregated statistics\n" +
"\n");
files.writeFileAtomically(identifierFile, comment + appId + '\n');
}
self.appIdentifier = appId;
},
_resolveConstraints: Profile('_resolveConstraints', function () {
var self = this;
buildmessage.assertInJob();
var depsAndConstraints = self._getRootDepsAndConstraints();
// If this is in the runner and we have reset this ProjectContext for a
// rebuild, use the versions we calculated last time in this process (which
// may not have been written to disk if our release doesn't match the
// project's release on disk)... unless the actual file on disk has changed
// out from under us. Otherwise use the versions from .meteor/versions.
var cachedVersions;
if (self._cachedVersionsBeforeReset &&
self._oldPackageMapFileHash === self.packageMapFile.fileHash) {
// The file on disk hasn't change; reuse last time's results.
cachedVersions = self._cachedVersionsBeforeReset;
} else {
// We don't have a last time, or the file has changed; use
// .meteor/versions.
cachedVersions = self.packageMapFile.getCachedVersions();
}
var anticipatedPrereleases = self._getAnticipatedPrereleases(
depsAndConstraints.constraints, cachedVersions);
if (self.explicitlyAddedPackageNames.length) {
cachedVersions = _.clone(cachedVersions);
_.each(self.explicitlyAddedPackageNames, function (p) {
delete cachedVersions[p];
});
}
var resolverRunCount = 0;
// Nothing before this point looked in the official or project catalog!
// However, the resolver does, so it gets run in the retry context.
catalog.runAndRetryWithRefreshIfHelpful(function (canRetry) {
buildmessage.enterJob("selecting package versions", function () {
var resolver = self._buildResolver();
var resolveOptions = {
previousSolution: cachedVersions,
anticipatedPrereleases: anticipatedPrereleases,
allowIncompatibleUpdate: self._allowIncompatibleUpdate,
// Not finding an exact match for a previous version in the catalog
// is considered an error if we haven't refreshed yet, and will
// trigger a refresh and another attempt. That way, if a previous
// version exists, you'll get it, even if we don't have a record
// of it yet. It's not actually fatal, though, for previousSolution
// to refer to package versions that we don't have access to or don't
// exist. They'll end up getting changed or removed if possible.
missingPreviousVersionIsError: canRetry,
supportedIsobuildFeaturePackages: KNOWN_ISOBUILD_FEATURE_PACKAGES,
};
if (self._upgradePackageNames) {
resolveOptions.upgrade = self._upgradePackageNames;
}
if (self._upgradeIndirectDepPatchVersions) {
resolveOptions.upgradeIndirectDepPatchVersions = true;
}
resolverRunCount++;
var solution;
try {
Profile.time(
"Select Package Versions" +
(resolverRunCount > 1 ? (" (Try " + resolverRunCount + ")") : ""),
function () {
solution = resolver.resolve(
depsAndConstraints.deps, depsAndConstraints.constraints,
resolveOptions);
});
} catch (e) {
if (!e.constraintSolverError && !e.versionParserError)
throw e;
// If the contraint solver gave us an error, refreshing
// might help to get new packages (see the comment on
// missingPreviousVersionIsError above). If it's a
// package-version-parser error, print a nice message,
// but don't bother refreshing.
buildmessage.error(
e.message,
{ tags: { refreshCouldHelp: !!e.constraintSolverError }});
}
if (buildmessage.jobHasMessages())
return;
self.packageMap = new packageMapModule.PackageMap(solution.answer, {
localCatalog: self.localCatalog
});
self.packageMapDelta = new packageMapModule.PackageMapDelta({
cachedVersions: cachedVersions,
packageMap: self.packageMap,
usedRCs: solution.usedRCs,
neededToUseUnanticipatedPrereleases:
solution.neededToUseUnanticipatedPrereleases,
anticipatedPrereleases: anticipatedPrereleases
});
self._saveResolverResultCache();
self._completedStage = STAGE.RESOLVE_CONSTRAINTS;
});
});
}),
_readResolverResultCache() {
if (! this._resolverResultCache) {
try {
this._resolverResultCache =
JSON.parse(files.readFile(files.pathJoin(
this.projectLocalDir,
"resolver-result-cache.json"
)));
} catch (e) {
if (e.code !== "ENOENT") throw e;
this._resolverResultCache = {};
}
}
return this._resolverResultCache;
},
_saveResolverResultCache() {
files.writeFileAtomically(
files.pathJoin(
this.projectLocalDir,
"resolver-result-cache.json"
),
JSON.stringify(this._resolverResultCache) + "\n"
);
},
// When running test-packages for an app with local packages, this
// method will return the original app dir, as opposed to the temporary
// testRunnerAppDir created for the tests.
getOriginalAppDirForTestPackages() {
const appDir = this._projectDirForLocalPackages;
if (_.isString(appDir) && appDir !== this.projectDir) {
return appDir;
}
},
_localPackageSearchDirs: function () {
const self = this;
let searchDirs = [
files.pathJoin(self._projectDirForLocalPackages, 'packages'),
];
// User can provide additional package directories to search in
// METEOR_PACKAGE_DIRS (semi-colon/colon-separated, depending on OS),
// PACKAGE_DIRS Deprecated in 2016-10
// Warn users to migrate from PACKAGE_DIRS to METEOR_PACKAGE_DIRS
if (process.env.PACKAGE_DIRS) {
Console.warn('For compatibility, the PACKAGE_DIRS environment variable',
'is deprecated and will be removed in a future Meteor release.');
Console.warn('Developers should now use METEOR_PACKAGE_DIRS and',
'Windows projects should now use a semi-colon (;) to separate paths.');
}
function packageDirsFromEnvVar(envVar, delimiter = files.pathOsDelimiter) {
return process.env[envVar] && process.env[envVar].split(delimiter) || [];
}
const envPackageDirs = [
// METEOR_PACKAGE_DIRS should use the arch-specific delimiter
...(packageDirsFromEnvVar('METEOR_PACKAGE_DIRS')),
// PACKAGE_DIRS (deprecated) always used ':' separator (yes, even Windows)
...(packageDirsFromEnvVar('PACKAGE_DIRS', ':')),
];
if (! self._ignorePackageDirsEnvVar && envPackageDirs.length) {
// path.delimiter was added in v0.9.3
envPackageDirs.forEach( p => searchDirs.push(files.pathResolve(p)) );
}
if (! self._ignoreCheckoutPackages && files.inCheckout()) {
// Running from a checkout, so use the Meteor core packages from the
// checkout.
const packagesDir =
files.pathJoin(files.getCurrentToolsDir(), 'packages');
searchDirs.push(
// Include packages like packages/ecmascript.
packagesDir,
// Include packages like packages/non-core/coffeescript.
files.pathJoin(packagesDir, "non-core"),
// Include packages like packages/non-core/blaze/packages/blaze.
files.pathJoin(packagesDir, "non-core", "*", "packages"),
);
}
return searchDirs;
},
// Returns a layered catalog with information about the packages that can be
// used in this project. Processes the package.js file from all local packages
// but does not compile the packages.
//
// Must be run in a buildmessage context. On build error, returns null.
_initializeCatalog: Profile('_initializeCatalog', function () {
var self = this;
buildmessage.assertInJob();
catalog.runAndRetryWithRefreshIfHelpful(function () {
buildmessage.enterJob(
"scanning local packages",
function () {
self.localCatalog = new catalogLocal.LocalCatalog;
self.projectCatalog = new catalog.LayeredCatalog(
self.localCatalog, self._officialCatalog);
var searchDirs = self._localPackageSearchDirs();
self.localCatalog.initialize({
localPackageSearchDirs: searchDirs,
explicitlyAddedLocalPackageDirs: self._explicitlyAddedLocalPackageDirs
});
if (buildmessage.jobHasMessages()) {
// Even if this fails, we want to leave self.localCatalog assigned,
// so that it gets counted included in the projectWatchSet.
return;
}
self.explicitlyAddedPackageNames = [];
_.each(self._explicitlyAddedLocalPackageDirs, function (dir) {
var localVersionRecord =
self.localCatalog.getVersionBySourceRoot(dir);
if (localVersionRecord) {
self.explicitlyAddedPackageNames.push(localVersionRecord.packageName);
}
});
self._completedStage = STAGE.INITIALIZE_CATALOG;
}
);
});
}),
_getRootDepsAndConstraints: function () {
var self = this;
var depsAndConstraints = {deps: [], constraints: []};
self._addAppConstraints(depsAndConstraints);
self._addLocalPackageConstraints(depsAndConstraints);
self._addReleaseConstraints(depsAndConstraints);
return depsAndConstraints;
},
_addAppConstraints: function (depsAndConstraints) {
var self = this;
self.projectConstraintsFile.eachConstraint(function (constraint) {
// Add a dependency ("this package must be used") and a constraint
// ("... at this version (maybe 'any reasonable')").
depsAndConstraints.deps.push(constraint.package);
depsAndConstraints.constraints.push(constraint);
});
},
_addLocalPackageConstraints: function (depsAndConstraints) {
var self = this;
_.each(self.localCatalog.getAllPackageNames(), function (packageName) {
var versionRecord = self.localCatalog.getLatestVersion(packageName);
var constraint = utils.parsePackageConstraint(
packageName + "@=" + versionRecord.version);
// Add a constraint ("this is the only version available") but no
// dependency (we don't automatically use all local packages!)
depsAndConstraints.constraints.push(constraint);
});
},
_addReleaseConstraints: function (depsAndConstraints) {
var self = this;
if (! self._releaseForConstraints)
return;
_.each(self._releaseForConstraints.packages, function (version, packageName) {
var constraint = utils.parsePackageConstraint(
// Note that this used to be an exact name@=version constraint,
// before #7084 eliminated these constraints completely. They
// were reinstated in Meteor 1.4.3 as name@version constraints,
// and further refined to name@~version constraints in 1.5.2.
packageName + "@~" + version);
// Add a constraint but no dependency (we don't automatically use
// all local packages!):
depsAndConstraints.constraints.push(constraint);
});
},
_getAnticipatedPrereleases: function (rootConstraints, cachedVersions) {
var self = this;
var anticipatedPrereleases = {};
var add = function (packageName, version) {
if (! /-/.test(version)) {
return;
}
if (! _.has(anticipatedPrereleases, packageName)) {
anticipatedPrereleases[packageName] = {};
}
anticipatedPrereleases[packageName][version] = true;
};
// Pre-release versions that are root constraints (in .meteor/packages, in
// the release, or the version of a local package) are anticipated.
_.each(rootConstraints, function (constraintObject) {
_.each(constraintObject.versionConstraint.alternatives, function (alt) {
var version = alt.versionString;
version && add(constraintObject.package, version);
});
});
// Pre-release versions we decided to use in the past are anticipated.
_.each(cachedVersions, function (version, packageName) {
add(packageName, version);
});
return anticipatedPrereleases;
},
_buildResolver: function () {
const { ConstraintSolver } = loadIsopackage('constraint-solver');
return new ConstraintSolver.PackagesResolver(this.projectCatalog, {
nudge() {
Console.nudge(true);
},
Profile: Profile,
resultCache: this._resolverResultCache
});
},
_downloadMissingPackages: Profile('_downloadMissingPackages', function () {
var self = this;
buildmessage.assertInJob();
if (!self.packageMap)
throw Error("which packages to download?");
catalog.runAndRetryWithRefreshIfHelpful(function () {
buildmessage.enterJob("downloading missing packages", function () {
self.tropohouse.downloadPackagesMissingFromMap(self.packageMap, {
serverArchitectures: self._serverArchitectures
});
if (buildmessage.jobHasMessages())
return;
self._completedStage = STAGE.DOWNLOAD_MISSING_PACKAGES;
});
});
}),
_buildLocalPackages: Profile('_buildLocalPackages', function () {
var self = this;
buildmessage.assertInCapture();
self.isopackCache = new isopackCacheModule.IsopackCache({
packageMap: self.packageMap,
includeCordovaUnibuild: (self._forceIncludeCordovaUnibuild
|| self.platformList.usesCordova()),
cacheDir: self.getProjectLocalDirectory('isopacks'),
pluginCacheDirRoot: self.getProjectLocalDirectory('plugin-cache'),
tropohouse: self.tropohouse,
previousIsopackCache: self._previousIsopackCache,
lintLocalPackages: self.lintAppAndLocalPackages,
lintPackageWithSourceRoot: self._lintPackageWithSourceRoot
});
if (self._forceRebuildPackages) {
self.isopackCache.wipeCachedPackages(
self._forceRebuildPackages === true
? null : self._forceRebuildPackages);
}
buildmessage.enterJob('building local packages', function () {
self.isopackCache.buildLocalPackages();
});
self._completedStage = STAGE.BUILD_LOCAL_PACKAGES;
}),
_saveChangedMetadata: Profile('_saveChangedMetadata', function () {
var self = this;
// Save any changes to .meteor/packages.
if (! self._neverWriteProjectConstraintsFile)
self.projectConstraintsFile.writeIfModified();
// Write .meteor/versions if the command always wants to (create/update),
// or if the release of the app matches the release of the process.
if (! self._neverWritePackageMap &&
(self._alwaysWritePackageMap ||
(release.current.isCheckout() && self.releaseFile.isCheckout()) ||
(! release.current.isCheckout() &&
release.current.name === self.releaseFile.fullReleaseName))) {
self.packageMapFile.write(self.packageMap);
}
self._completedStage = STAGE.SAVE_CHANGED_METADATA;
})
});
// Represents .meteor/packages.
exports.ProjectConstraintsFile = function (options) {
var self = this;
buildmessage.assertInCapture();
self.filename = files.pathJoin(options.projectDir, '.meteor', 'packages');
self.watchSet = null;
// List of packages that should be included if not provided in .meteor/packages
self._includePackages = options.includePackages || [];
// Have we modified the in-memory representation since reading from disk?
self._modified = null;
// List of each line in the file; object with keys:
// - leadingSpace (string of spaces before the constraint)
// - constraint (as returned by utils.parsePackageConstraint)
// - trailingSpaceAndComment (string of spaces/comments after the constraint)
// This allows us to rewrite the file preserving comments.
self._constraintLines = null;
// Maps from package name to entry in _constraintLines.
self._constraintMap = null;
self._readFile();
};
_.extend(exports.ProjectConstraintsFile.prototype, {
_readFile: function () {
var self = this;
buildmessage.assertInCapture();
self.watchSet = new watch.WatchSet;
self._modified = false;
self._constraintMap = {};
self._constraintLines = [];
var contents = watch.readAndWatchFile(self.watchSet, self.filename);
// No .meteor/packages? This isn't a very good project directory. In fact,
// that's the definition of a project directory! (And that should have been
// fixed by _ensureProjectDir!)
if (contents === null)
throw Error("packages file missing: " + self.filename);
var extraConstraintMap = {};
_.each(self._includePackages, function (pkg) {
var lineRecord = {
constraint: utils.parsePackageConstraint(pkg.trim()),
skipOnWrite: true
};
extraConstraintMap[lineRecord.constraint.package] = lineRecord;
});
var lines = files.splitBufferToLines(contents);
// Don't keep a record for the space at the end of the file.
if (lines.length && _.last(lines) === '')
lines.pop();
_.each(lines, function (line) {
var lineRecord =
{ leadingSpace: '', constraint: null, trailingSpaceAndComment: '' };
self._constraintLines.push(lineRecord);
// Strip comment.
var match = line.match(/^([^#]*)(#.*)$/);
if (match) {
line = match[1];
lineRecord.trailingSpaceAndComment = match[2];
}
// Strip trailing space.
match = line.match(/^((?:.*\S)?)(\s*)$/);
line = match[1];
lineRecord.trailingSpaceAndComment =
match[2] + lineRecord.trailingSpaceAndComment;
// Strip leading space.
match = line.match(/^(\s*)((?:\S.*)?)$/);
lineRecord.leadingSpace = match[1];
line = match[2];
// No constraint? Leave lineRecord.constraint null and continue.
if (line === '')
return;
lineRecord.constraint = utils.parsePackageConstraint(line, {
useBuildmessage: true,
buildmessageFile: self.filename
});
if (! lineRecord.constraint)
return; // recover by ignoring
// Mark as not iterable if already included in self._includePackages
if (_.has(extraConstraintMap, lineRecord.constraint.package))
lineRecord.skipOnRead = true;
if (_.has(self._constraintMap, lineRecord.constraint.package)) {
buildmessage.error(
"Package name appears twice: " + lineRecord.constraint.package, {
// XXX should this be relative?
file: self.filename
});
return; // recover by ignoring
}
self._constraintMap[lineRecord.constraint.package] = lineRecord;
});
_.each(_.keys(extraConstraintMap), function (key) {
var lineRecord = extraConstraintMap[key];
self._constraintLines.push(lineRecord);
self._constraintMap[lineRecord.constraint.package] = lineRecord;
});
},
writeIfModified: function () {