-
Notifications
You must be signed in to change notification settings - Fork 12.5k
/
tsbuild.ts
1274 lines (1103 loc) · 52.6 KB
/
tsbuild.ts
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
namespace ts {
const minimumDate = new Date(-8640000000000000);
const maximumDate = new Date(8640000000000000);
export interface BuildHost {
verbose(diag: DiagnosticMessage, ...args: string[]): void;
error(diag: DiagnosticMessage, ...args: string[]): void;
errorDiagnostic(diag: Diagnostic): void;
message(diag: DiagnosticMessage, ...args: string[]): void;
}
/**
* A BuildContext tracks what's going on during the course of a build.
*
* Callers may invoke any number of build requests within the same context;
* until the context is reset, each project will only be built at most once.
*
* Example: In a standard setup where project B depends on project A, and both are out of date,
* a failed build of A will result in A remaining out of date. When we try to build
* B, we should immediately bail instead of recomputing A's up-to-date status again.
*
* This also matters for performing fast (i.e. fake) downstream builds of projects
* when their upstream .d.ts files haven't changed content (but have newer timestamps)
*/
export interface BuildContext {
options: BuildOptions;
/**
* Map from output file name to its pre-build timestamp
*/
unchangedOutputs: FileMap<Date>;
/**
* Map from config file name to up-to-date status
*/
projectStatus: FileMap<UpToDateStatus>;
invalidatedProjects: FileMap<true>;
queuedProjects: FileMap<true>;
missingRoots: Map<true>;
}
type Mapper = ReturnType<typeof createDependencyMapper>;
interface DependencyGraph {
buildQueue: ResolvedConfigFileName[];
dependencyMap: Mapper;
}
interface BuildOptions {
dry: boolean;
force: boolean;
verbose: boolean;
}
enum BuildResultFlags {
None = 0,
/**
* No errors of any kind occurred during build
*/
Success = 1 << 0,
/**
* None of the .d.ts files emitted by this build were
* different from the existing files on disk
*/
DeclarationOutputUnchanged = 1 << 1,
ConfigFileErrors = 1 << 2,
SyntaxErrors = 1 << 3,
TypeErrors = 1 << 4,
DeclarationEmitErrors = 1 << 5,
AnyErrors = ConfigFileErrors | SyntaxErrors | TypeErrors | DeclarationEmitErrors
}
export enum UpToDateStatusType {
Unbuildable,
UpToDate,
/**
* The project appears out of date because its upstream inputs are newer than its outputs,
* but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
* This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
*/
UpToDateWithUpstreamTypes,
OutputMissing,
OutOfDateWithSelf,
OutOfDateWithUpstream,
UpstreamOutOfDate,
UpstreamBlocked,
/**
* Projects with no outputs (i.e. "solution" files)
*/
ContainerOnly
}
export type UpToDateStatus =
| Status.Unbuildable
| Status.UpToDate
| Status.OutputMissing
| Status.OutOfDateWithSelf
| Status.OutOfDateWithUpstream
| Status.UpstreamOutOfDate
| Status.UpstreamBlocked
| Status.ContainerOnly;
export namespace Status {
/**
* The project can't be built at all in its current state. For example,
* its config file cannot be parsed, or it has a syntax error or missing file
*/
export interface Unbuildable {
type: UpToDateStatusType.Unbuildable;
reason: string;
}
/**
* This project doesn't have any outputs, so "is it up to date" is a meaningless question.
*/
export interface ContainerOnly {
type: UpToDateStatusType.ContainerOnly;
}
/**
* The project is up to date with respect to its inputs.
* We track what the newest input file is.
*/
export interface UpToDate {
type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes;
newestInputFileTime?: Date;
newestInputFileName?: string;
newestDeclarationFileContentChangedTime?: Date;
newestOutputFileTime?: Date;
newestOutputFileName?: string;
oldestOutputFileName?: string;
}
/**
* One or more of the outputs of the project does not exist.
*/
export interface OutputMissing {
type: UpToDateStatusType.OutputMissing;
/**
* The name of the first output file that didn't exist
*/
missingOutputFileName: string;
}
/**
* One or more of the project's outputs is older than its newest input.
*/
export interface OutOfDateWithSelf {
type: UpToDateStatusType.OutOfDateWithSelf;
outOfDateOutputFileName: string;
newerInputFileName: string;
}
/**
* This project depends on an out-of-date project, so shouldn't be built yet
*/
export interface UpstreamOutOfDate {
type: UpToDateStatusType.UpstreamOutOfDate;
upstreamProjectName: string;
}
/**
* This project depends an upstream project with build errors
*/
export interface UpstreamBlocked {
type: UpToDateStatusType.UpstreamBlocked;
upstreamProjectName: string;
}
/**
* One or more of the project's outputs is older than the newest output of
* an upstream project.
*/
export interface OutOfDateWithUpstream {
type: UpToDateStatusType.OutOfDateWithUpstream;
outOfDateOutputFileName: string;
newerProjectName: string;
}
}
interface FileMap<T> {
setValue(fileName: string, value: T): void;
getValue(fileName: string): T | never;
getValueOrUndefined(fileName: string): T | undefined;
hasKey(fileName: string): boolean;
removeKey(fileName: string): void;
getKeys(): string[];
}
/**
* A FileMap maintains a normalized-key to value relationship
*/
function createFileMap<T>(): FileMap<T> {
// tslint:disable-next-line:no-null-keyword
const lookup = createMap<T>();
return {
setValue,
getValue,
getValueOrUndefined,
removeKey,
getKeys,
hasKey
};
function getKeys(): string[] {
return Object.keys(lookup);
}
function hasKey(fileName: string) {
return lookup.has(normalizePath(fileName));
}
function removeKey(fileName: string) {
lookup.delete(normalizePath(fileName));
}
function setValue(fileName: string, value: T) {
lookup.set(normalizePath(fileName), value);
}
function getValue(fileName: string): T | never {
const f = normalizePath(fileName);
if (lookup.has(f)) {
return lookup.get(f)!;
}
else {
throw new Error(`No value corresponding to ${fileName} exists in this map`);
}
}
function getValueOrUndefined(fileName: string): T | undefined {
const f = normalizePath(fileName);
return lookup.get(f);
}
}
function createDependencyMapper() {
const childToParents = createFileMap<ResolvedConfigFileName[]>();
const parentToChildren = createFileMap<ResolvedConfigFileName[]>();
const allKeys = createFileMap<true>();
function addReference(childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName): void {
addEntry(childToParents, childConfigFileName, parentConfigFileName);
addEntry(parentToChildren, parentConfigFileName, childConfigFileName);
}
function getReferencesTo(parentConfigFileName: ResolvedConfigFileName): ResolvedConfigFileName[] {
return parentToChildren.getValueOrUndefined(parentConfigFileName) || [];
}
function getReferencesOf(childConfigFileName: ResolvedConfigFileName): ResolvedConfigFileName[] {
return childToParents.getValueOrUndefined(childConfigFileName) || [];
}
function getKeys(): ReadonlyArray<ResolvedConfigFileName> {
return allKeys.getKeys() as ResolvedConfigFileName[];
}
function addEntry(mapToAddTo: typeof childToParents | typeof parentToChildren, key: ResolvedConfigFileName, element: ResolvedConfigFileName) {
key = normalizePath(key) as ResolvedConfigFileName;
element = normalizePath(element) as ResolvedConfigFileName;
let arr = mapToAddTo.getValueOrUndefined(key);
if (arr === undefined) {
mapToAddTo.setValue(key, arr = []);
}
if (arr.indexOf(element) < 0) {
arr.push(element);
}
allKeys.setValue(key, true);
allKeys.setValue(element, true);
}
return {
addReference,
getReferencesTo,
getReferencesOf,
getKeys
};
}
function getOutputDeclarationFileName(inputFileName: string, configFile: ParsedCommandLine) {
const relativePath = getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath!), inputFileName, /*ignoreCase*/ true);
const outputPath = resolvePath(configFile.options.declarationDir || configFile.options.outDir || getDirectoryPath(configFile.options.configFilePath!), relativePath);
return changeExtension(outputPath, Extension.Dts);
}
function getOutputJavaScriptFileName(inputFileName: string, configFile: ParsedCommandLine) {
const relativePath = getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath!), inputFileName, /*ignoreCase*/ true);
const outputPath = resolvePath(configFile.options.outDir || getDirectoryPath(configFile.options.configFilePath!), relativePath);
const newExtension = fileExtensionIs(inputFileName, Extension.Json) ? Extension.Json :
fileExtensionIs(inputFileName, Extension.Tsx) && configFile.options.jsx === JsxEmit.Preserve ? Extension.Jsx : Extension.Js;
return changeExtension(outputPath, newExtension);
}
function getOutputFileNames(inputFileName: string, configFile: ParsedCommandLine): ReadonlyArray<string> {
// outFile is handled elsewhere; .d.ts files don't generate outputs
if (configFile.options.outFile || configFile.options.out || fileExtensionIs(inputFileName, Extension.Dts)) {
return emptyArray;
}
const outputs: string[] = [];
outputs.push(getOutputJavaScriptFileName(inputFileName, configFile));
if (getEmitDeclarations(configFile.options) && !fileExtensionIs(inputFileName, Extension.Json)) {
const dts = getOutputDeclarationFileName(inputFileName, configFile);
outputs.push(dts);
if (configFile.options.declarationMap) {
outputs.push(dts + ".map");
}
}
return outputs;
}
function getOutFileOutputs(project: ParsedCommandLine): ReadonlyArray<string> {
if (!project.options.outFile) {
return Debug.fail("outFile must be set");
}
const outputs: string[] = [];
outputs.push(project.options.outFile);
if (getEmitDeclarations(project.options)) {
const dts = changeExtension(project.options.outFile, Extension.Dts);
outputs.push(dts);
if (project.options.declarationMap) {
outputs.push(dts + ".map");
}
}
return outputs;
}
function rootDirOfOptions(opts: CompilerOptions, configFileName: string) {
return opts.rootDir || getDirectoryPath(configFileName);
}
function createConfigFileCache(host: CompilerHost) {
const cache = createFileMap<ParsedCommandLine>();
const configParseHost = parseConfigHostFromCompilerHost(host);
function parseConfigFile(configFilePath: ResolvedConfigFileName) {
const sourceFile = host.getSourceFile(configFilePath, ScriptTarget.JSON) as JsonSourceFile;
if (sourceFile === undefined) {
return undefined;
}
const parsed = parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, getDirectoryPath(configFilePath));
parsed.options.configFilePath = configFilePath;
cache.setValue(configFilePath, parsed);
return parsed;
}
function removeKey(configFilePath: ResolvedConfigFileName) {
cache.removeKey(configFilePath);
}
return {
parseConfigFile,
removeKey
};
}
function newer(date1: Date, date2: Date): Date {
return date2 > date1 ? date2 : date1;
}
function isDeclarationFile(fileName: string) {
return fileExtensionIs(fileName, Extension.Dts);
}
export function createBuildContext(options: BuildOptions): BuildContext {
const invalidatedProjects = createFileMap<true>();
const queuedProjects = createFileMap<true>();
const missingRoots = createMap<true>();
return {
options,
projectStatus: createFileMap(),
unchangedOutputs: createFileMap(),
invalidatedProjects,
missingRoots,
queuedProjects
};
}
const buildOpts: CommandLineOption[] = [
{
name: "verbose",
shortName: "v",
category: Diagnostics.Command_line_Options,
description: Diagnostics.Enable_verbose_logging,
type: "boolean"
},
{
name: "dry",
shortName: "d",
category: Diagnostics.Command_line_Options,
description: Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
type: "boolean"
},
{
name: "force",
shortName: "f",
category: Diagnostics.Command_line_Options,
description: Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
type: "boolean"
},
{
name: "clean",
category: Diagnostics.Command_line_Options,
description: Diagnostics.Delete_the_outputs_of_all_projects,
type: "boolean"
},
{
name: "watch",
category: Diagnostics.Command_line_Options,
description: Diagnostics.Watch_input_files,
type: "boolean"
}
];
export function performBuild(args: string[], compilerHost: CompilerHost, buildHost: BuildHost, system?: System): number | undefined {
let verbose = false;
let dry = false;
let force = false;
let clean = false;
let watch = false;
const projects: string[] = [];
for (const arg of args) {
switch (arg.toLowerCase()) {
case "-v":
case "--verbose":
verbose = true;
continue;
case "-d":
case "--dry":
dry = true;
continue;
case "-f":
case "--force":
force = true;
continue;
case "--clean":
clean = true;
continue;
case "--watch":
case "-w":
watch = true;
continue;
case "--?":
case "-?":
case "--help":
printHelp(buildOpts, "--build ");
return ExitStatus.Success;
}
// Not a flag, parse as filename
addProject(arg);
}
// Nonsensical combinations
if (clean && force) {
buildHost.error(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force");
return ExitStatus.DiagnosticsPresent_OutputsSkipped;
}
if (clean && verbose) {
buildHost.error(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose");
return ExitStatus.DiagnosticsPresent_OutputsSkipped;
}
if (clean && watch) {
buildHost.error(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch");
return ExitStatus.DiagnosticsPresent_OutputsSkipped;
}
if (watch && dry) {
buildHost.error(Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry");
return ExitStatus.DiagnosticsPresent_OutputsSkipped;
}
if (projects.length === 0) {
// tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
addProject(".");
}
const builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry, force, verbose }, system);
if (clean) {
return builder.cleanAllProjects();
}
if (watch) {
builder.buildAllProjects();
builder.startWatching();
return undefined;
}
return builder.buildAllProjects();
function addProject(projectSpecification: string) {
const fileName = resolvePath(compilerHost.getCurrentDirectory(), projectSpecification);
const refPath = resolveProjectReferencePath(compilerHost, { path: fileName });
if (!compilerHost.fileExists(refPath)) {
return buildHost.error(Diagnostics.File_0_does_not_exist, fileName);
}
projects.push(refPath);
}
}
/**
* A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but
* can dynamically add/remove other projects based on changes on the rootNames' references
*/
export function createSolutionBuilder(compilerHost: CompilerHost, buildHost: BuildHost, rootNames: ReadonlyArray<string>, defaultOptions: BuildOptions, system?: System) {
if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) {
throw new Error("Host must support timestamp APIs");
}
const configFileCache = createConfigFileCache(compilerHost);
let context = createBuildContext(defaultOptions);
const existingWatchersForWildcards = createMap<WildcardDirectoryWatcher>();
const upToDateHost: UpToDateHost = {
fileExists: fileName => compilerHost.fileExists(fileName),
getModifiedTime: fileName => compilerHost.getModifiedTime!(fileName),
getUnchangedTime: fileName => context.unchangedOutputs.getValueOrUndefined(fileName),
getLastStatus: fileName => context.projectStatus.getValueOrUndefined(fileName),
setLastStatus: (fileName, status) => context.projectStatus.setValue(fileName, status),
parseConfigFile: configFilePath => configFileCache.parseConfigFile(configFilePath)
};
return {
buildAllProjects,
getUpToDateStatus,
getUpToDateStatusOfFile,
cleanAllProjects,
resetBuildContext,
getBuildGraph,
invalidateProject,
buildInvalidatedProjects,
buildDependentInvalidatedProjects,
resolveProjectName,
startWatching
};
function startWatching() {
if (!system) throw new Error("System host must be provided if using --watch");
if (!system.watchFile || !system.watchDirectory || !system.setTimeout) throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch");
const graph = getGlobalDependencyGraph()!;
if (!graph.buildQueue) {
// Everything is broken - we don't even know what to watch. Give up.
return;
}
for (const resolved of graph.buildQueue) {
const cfg = configFileCache.parseConfigFile(resolved);
if (cfg) {
// Watch this file
system.watchFile(resolved, () => {
configFileCache.removeKey(resolved);
invalidateProjectAndScheduleBuilds(resolved);
});
// Update watchers for wildcard directories
if (cfg.configFileSpecs) {
updateWatchingWildcardDirectories(existingWatchersForWildcards, createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), (dir, flags) => {
return system.watchDirectory!(dir, () => {
invalidateProjectAndScheduleBuilds(resolved);
}, !!(flags & WatchDirectoryFlags.Recursive));
});
}
// Watch input files
for (const input of cfg.fileNames) {
system.watchFile(input, () => {
invalidateProjectAndScheduleBuilds(resolved);
});
}
}
}
function invalidateProjectAndScheduleBuilds(resolved: ResolvedConfigFileName) {
invalidateProject(resolved);
system!.setTimeout!(buildInvalidatedProjects, 100);
system!.setTimeout!(buildDependentInvalidatedProjects, 3000);
}
}
function resetBuildContext(opts = defaultOptions) {
context = createBuildContext(opts);
}
function getUpToDateStatusOfFile(configFileName: ResolvedConfigFileName): UpToDateStatus {
return getUpToDateStatus(configFileCache.parseConfigFile(configFileName));
}
function getBuildGraph(configFileNames: ReadonlyArray<string>) {
const resolvedNames: ResolvedConfigFileName[] | undefined = resolveProjectNames(configFileNames);
if (resolvedNames === undefined) return undefined;
return createDependencyGraph(resolvedNames);
}
function getGlobalDependencyGraph() {
return getBuildGraph(rootNames);
}
function getUpToDateStatus(project: ParsedCommandLine | undefined): UpToDateStatus {
return ts.getUpToDateStatus(upToDateHost, project);
}
function invalidateProject(configFileName: string) {
const resolved = resolveProjectName(configFileName);
if (resolved === undefined) {
// If this was a rootName, we need to track it as missing.
// Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects,
// if they exist
// TODO: do those things
return;
}
configFileCache.removeKey(resolved);
context.invalidatedProjects.setValue(resolved, true);
context.projectStatus.removeKey(resolved);
const graph = getGlobalDependencyGraph()!;
if (graph) {
queueBuildForDownstreamReferences(resolved);
}
// Mark all downstream projects of this one needing to be built "later"
function queueBuildForDownstreamReferences(root: ResolvedConfigFileName) {
const deps = graph.dependencyMap.getReferencesTo(root);
for (const ref of deps) {
// Can skip circular references
if (!context.queuedProjects.hasKey(ref)) {
context.queuedProjects.setValue(ref, true);
queueBuildForDownstreamReferences(ref);
}
}
}
}
function buildInvalidatedProjects() {
buildSomeProjects(p => context.invalidatedProjects.hasKey(p));
}
function buildDependentInvalidatedProjects() {
buildSomeProjects(p => context.queuedProjects.hasKey(p));
}
function buildSomeProjects(predicate: (projName: ResolvedConfigFileName) => boolean) {
const resolvedNames: ResolvedConfigFileName[] | undefined = resolveProjectNames(rootNames);
if (resolvedNames === undefined) return;
const graph = createDependencyGraph(resolvedNames)!;
for (const next of graph.buildQueue) {
if (!predicate(next)) continue;
const resolved = resolveProjectName(next);
if (!resolved) continue; // ??
const proj = configFileCache.parseConfigFile(resolved);
if (!proj) continue; // ?
const status = getUpToDateStatus(proj);
verboseReportProjectStatus(next, status);
if (status.type === UpToDateStatusType.UpstreamBlocked) {
if (context.options.verbose) buildHost.verbose(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName);
continue;
}
buildSingleProject(next);
}
}
function createDependencyGraph(roots: ResolvedConfigFileName[]): DependencyGraph | undefined {
const temporaryMarks: { [path: string]: true } = {};
const permanentMarks: { [path: string]: true } = {};
const circularityReportStack: string[] = [];
const buildOrder: ResolvedConfigFileName[] = [];
const graph = createDependencyMapper();
let hadError = false;
for (const root of roots) {
visit(root);
}
if (hadError) {
return undefined;
}
return {
buildQueue: buildOrder,
dependencyMap: graph
};
function visit(projPath: ResolvedConfigFileName, inCircularContext = false) {
// Already visited
if (permanentMarks[projPath]) return;
// Circular
if (temporaryMarks[projPath]) {
if (!inCircularContext) {
hadError = true;
buildHost.error(Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n"));
return;
}
}
temporaryMarks[projPath] = true;
circularityReportStack.push(projPath);
const parsed = configFileCache.parseConfigFile(projPath);
if (parsed === undefined) {
hadError = true;
return;
}
if (parsed.projectReferences) {
for (const ref of parsed.projectReferences) {
const resolvedRefPath = resolveProjectName(ref.path);
if (resolvedRefPath === undefined) {
hadError = true;
break;
}
visit(resolvedRefPath, inCircularContext || ref.circular);
graph.addReference(projPath, resolvedRefPath);
}
}
circularityReportStack.pop();
permanentMarks[projPath] = true;
buildOrder.push(projPath);
}
}
function buildSingleProject(proj: ResolvedConfigFileName): BuildResultFlags {
if (context.options.dry) {
buildHost.message(Diagnostics.A_non_dry_build_would_build_project_0, proj);
return BuildResultFlags.Success;
}
if (context.options.verbose) buildHost.verbose(Diagnostics.Building_project_0, proj);
let resultFlags = BuildResultFlags.None;
resultFlags |= BuildResultFlags.DeclarationOutputUnchanged;
const configFile = configFileCache.parseConfigFile(proj);
if (!configFile) {
// Failed to read the config file
resultFlags |= BuildResultFlags.ConfigFileErrors;
context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" });
return resultFlags;
}
if (configFile.fileNames.length === 0) {
// Nothing to build - must be a solution file, basically
return BuildResultFlags.None;
}
const programOptions: CreateProgramOptions = {
projectReferences: configFile.projectReferences,
host: compilerHost,
rootNames: configFile.fileNames,
options: configFile.options
};
const program = createProgram(programOptions);
// Don't emit anything in the presence of syntactic errors or options diagnostics
const syntaxDiagnostics = [
...program.getOptionsDiagnostics(),
...program.getConfigFileParsingDiagnostics(),
...program.getSyntacticDiagnostics()];
if (syntaxDiagnostics.length) {
resultFlags |= BuildResultFlags.SyntaxErrors;
for (const diag of syntaxDiagnostics) {
buildHost.errorDiagnostic(diag);
}
context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" });
return resultFlags;
}
// Don't emit .d.ts if there are decl file errors
if (getEmitDeclarations(program.getCompilerOptions())) {
const declDiagnostics = program.getDeclarationDiagnostics();
if (declDiagnostics.length) {
resultFlags |= BuildResultFlags.DeclarationEmitErrors;
for (const diag of declDiagnostics) {
buildHost.errorDiagnostic(diag);
}
context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" });
return resultFlags;
}
}
// Same as above but now for semantic diagnostics
const semanticDiagnostics = program.getSemanticDiagnostics();
if (semanticDiagnostics.length) {
resultFlags |= BuildResultFlags.TypeErrors;
for (const diag of semanticDiagnostics) {
buildHost.errorDiagnostic(diag);
}
context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" });
return resultFlags;
}
let newestDeclarationFileContentChangedTime = minimumDate;
let anyDtsChanged = false;
program.emit(/*targetSourceFile*/ undefined, (fileName, content, writeBom, onError) => {
let priorChangeTime: Date | undefined;
if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) {
if (compilerHost.readFile(fileName) === content) {
// Check for unchanged .d.ts files
resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName);
}
else {
anyDtsChanged = true;
}
}
compilerHost.writeFile(fileName, content, writeBom, onError, emptyArray);
if (priorChangeTime !== undefined) {
newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
context.unchangedOutputs.setValue(fileName, priorChangeTime);
}
});
const status: UpToDateStatus = {
type: UpToDateStatusType.UpToDate,
newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime
};
context.projectStatus.setValue(proj, status);
return resultFlags;
}
function updateOutputTimestamps(proj: ParsedCommandLine) {
if (context.options.dry) {
return buildHost.message(Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath!);
}
if (context.options.verbose) {
buildHost.verbose(Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath!);
}
const now = new Date();
const outputs = getAllProjectOutputs(proj);
let priorNewestUpdateTime = minimumDate;
for (const file of outputs) {
if (isDeclarationFile(file)) {
priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime!(file) || missingFileModifiedTime);
}
compilerHost.setModifiedTime!(file, now);
}
context.projectStatus.setValue(proj.options.configFilePath!, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus);
}
function getFilesToClean(configFileNames: ReadonlyArray<ResolvedConfigFileName>): string[] | undefined {
const resolvedNames: ResolvedConfigFileName[] | undefined = resolveProjectNames(configFileNames);
if (resolvedNames === undefined) return undefined;
// Get the same graph for cleaning we'd use for building
const graph = createDependencyGraph(resolvedNames);
if (graph === undefined) return undefined;
const filesToDelete: string[] = [];
for (const proj of graph.buildQueue) {
const parsed = configFileCache.parseConfigFile(proj);
if (parsed === undefined) {
// File has gone missing; fine to ignore here
continue;
}
const outputs = getAllProjectOutputs(parsed);
for (const output of outputs) {
if (compilerHost.fileExists(output)) {
filesToDelete.push(output);
}
}
}
return filesToDelete;
}
function getAllProjectsInScope(): ReadonlyArray<ResolvedConfigFileName> | undefined {
const resolvedNames = resolveProjectNames(rootNames);
if (resolvedNames === undefined) return undefined;
const graph = createDependencyGraph(resolvedNames);
if (graph === undefined) return undefined;
return graph.buildQueue;
}
function cleanAllProjects() {
const resolvedNames: ReadonlyArray<ResolvedConfigFileName> | undefined = getAllProjectsInScope();
if (resolvedNames === undefined) {
buildHost.message(Diagnostics.Skipping_clean_because_not_all_projects_could_be_located);
return ExitStatus.DiagnosticsPresent_OutputsSkipped;
}
const filesToDelete = getFilesToClean(resolvedNames);
if (filesToDelete === undefined) {
buildHost.message(Diagnostics.Skipping_clean_because_not_all_projects_could_be_located);
return ExitStatus.DiagnosticsPresent_OutputsSkipped;
}
if (context.options.dry) {
buildHost.message(Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(f => `\r\n * ${f}`).join(""));
return ExitStatus.Success;
}
// Do this check later to allow --clean --dry to function even if the host can't delete files
if (!compilerHost.deleteFile) {
throw new Error("Host does not support deleting files");
}
for (const output of filesToDelete) {
compilerHost.deleteFile(output);
}
return ExitStatus.Success;
}
function resolveProjectName(name: string): ResolvedConfigFileName | undefined {
const fullPath = resolvePath(compilerHost.getCurrentDirectory(), name);
if (compilerHost.fileExists(fullPath)) {
return fullPath as ResolvedConfigFileName;
}
const fullPathWithTsconfig = combinePaths(fullPath, "tsconfig.json");
if (compilerHost.fileExists(fullPathWithTsconfig)) {
return fullPathWithTsconfig as ResolvedConfigFileName;
}
buildHost.error(Diagnostics.File_0_not_found, relName(fullPath));
return undefined;
}
function resolveProjectNames(configFileNames: ReadonlyArray<string>): ResolvedConfigFileName[] | undefined {
const resolvedNames: ResolvedConfigFileName[] = [];
for (const name of configFileNames) {
const resolved = resolveProjectName(name);
if (resolved === undefined) {
return undefined;
}
resolvedNames.push(resolved);
}
return resolvedNames;
}
function buildAllProjects(): ExitStatus {
const graph = getGlobalDependencyGraph();
if (graph === undefined) return ExitStatus.DiagnosticsPresent_OutputsSkipped;
const queue = graph.buildQueue;
reportBuildQueue(graph);
let anyFailed = false;
for (const next of queue) {
const proj = configFileCache.parseConfigFile(next);
if (proj === undefined) {
anyFailed = true;
break;
}
const status = getUpToDateStatus(proj);
verboseReportProjectStatus(next, status);
const projName = proj.options.configFilePath!;
if (status.type === UpToDateStatusType.UpToDate && !context.options.force) {
// Up to date, skip
if (defaultOptions.dry) {
// In a dry build, inform the user of this fact
buildHost.message(Diagnostics.Project_0_is_up_to_date, projName);
}
continue;
}
if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) {
// Fake build
updateOutputTimestamps(proj);
continue;
}
if (status.type === UpToDateStatusType.UpstreamBlocked) {
if (context.options.verbose) buildHost.verbose(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName);
continue;
}
if (status.type === UpToDateStatusType.ContainerOnly) {
// Do nothing
continue;
}
const buildResult = buildSingleProject(next);
anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors);
}
return anyFailed ? ExitStatus.DiagnosticsPresent_OutputsSkipped : ExitStatus.Success;
}