-
-
Notifications
You must be signed in to change notification settings - Fork 227
/
project.d
2154 lines (1884 loc) · 77.9 KB
/
project.d
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
/**
Representing a full project, with a root Package and several dependencies.
Copyright: © 2012-2013 Matthias Dondorff, 2012-2016 Sönke Ludwig
License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
Authors: Matthias Dondorff, Sönke Ludwig
*/
module dub.project;
import dub.compilers.compiler;
import dub.dependency;
import dub.description;
import dub.generators.generator;
import dub.internal.utils;
import dub.internal.vibecompat.core.file;
import dub.internal.vibecompat.data.json;
import dub.internal.vibecompat.inet.path;
import dub.internal.logging;
import dub.package_;
import dub.packagemanager;
import dub.recipe.selection;
import dub.internal.configy.Read;
import std.algorithm;
import std.array;
import std.conv : to;
import std.datetime;
import std.encoding : sanitize;
import std.exception : enforce;
import std.string;
/**
Represents a full project, a root package with its dependencies and package
selection.
All dependencies must be available locally so that the package dependency
graph can be built. Use `Project.reinit` if necessary for reloading
dependencies after more packages are available.
*/
class Project {
private {
PackageManager m_packageManager;
Package m_rootPackage;
Package[] m_dependencies;
Package[string] m_dependenciesByName;
Package[][Package] m_dependees;
SelectedVersions m_selections;
string[] m_missingDependencies;
string[string] m_overriddenConfigs;
}
/** Loads a project.
Params:
package_manager = Package manager instance to use for loading
dependencies
project_path = Path of the root package to load
pack = An existing `Package` instance to use as the root package
*/
deprecated("Load the package using `PackageManager.getOrLoadPackage` then call the `(PackageManager, Package)` overload")
this(PackageManager package_manager, NativePath project_path)
{
Package pack;
auto packageFile = Package.findPackageFile(project_path);
if (packageFile.empty) {
logWarn("There was no package description found for the application in '%s'.", project_path.toNativeString());
pack = new Package(PackageRecipe.init, project_path);
} else {
pack = package_manager.getOrLoadPackage(project_path, packageFile, false, StrictMode.Warn);
}
this(package_manager, pack);
}
/// Ditto
this(PackageManager package_manager, Package pack)
{
auto selections = Project.loadSelections(pack.path, package_manager);
this(package_manager, pack, selections);
}
/// ditto
this(PackageManager package_manager, Package pack, SelectedVersions selections)
{
m_packageManager = package_manager;
m_rootPackage = pack;
m_selections = selections;
reinit();
}
/**
* Loads a project's `dub.selections.json` and returns it
*
* This function will load `dub.selections.json` from the path at which
* `pack` is located, and returned the resulting `SelectedVersions`.
* If no `dub.selections.json` is found, an empty `SelectedVersions`
* is returned.
*
* Params:
* packPath = Absolute path of the Package to load the selection file from.
*
* Returns:
* Always a non-null instance.
*/
static package SelectedVersions loadSelections(in NativePath packPath, PackageManager mgr)
{
import dub.version_;
import dub.internal.dyaml.stdsumtype;
auto lookupResult = mgr.readSelections(packPath);
if (lookupResult.isNull()) // no file, or parsing error (displayed to the user)
return new SelectedVersions();
auto r = lookupResult.get();
return r.selectionsFile.content.match!(
(Selections!0 s) {
logWarnTag("Unsupported version",
"File %s has fileVersion %s, which is not yet supported by DUB %s.",
r.absolutePath, s.fileVersion, dubVersion);
logWarn("Ignoring selections file. Use a newer DUB version " ~
"and set the appropriate toolchainRequirements in your recipe file");
return new SelectedVersions();
},
(Selections!1 s) {
auto selectionsDir = r.absolutePath.parentPath;
return new SelectedVersions(s, selectionsDir.relativeTo(packPath));
},
);
}
/** List of all resolved dependencies.
This includes all direct and indirect dependencies of all configurations
combined. Optional dependencies that were not chosen are not included.
*/
@property const(Package[]) dependencies() const { return m_dependencies; }
/// The root package of the project.
@property inout(Package) rootPackage() inout { return m_rootPackage; }
/// The versions to use for all dependencies. Call reinit() after changing these.
@property inout(SelectedVersions) selections() inout { return m_selections; }
/// Package manager instance used by the project.
deprecated("Use `Dub.packageManager` instead")
@property inout(PackageManager) packageManager() inout { return m_packageManager; }
/** Determines if all dependencies necessary to build have been collected.
If this function returns `false`, it may be necessary to add more entries
to `selections`, or to use `Dub.upgrade` to automatically select all
missing dependencies.
*/
bool hasAllDependencies() const { return m_missingDependencies.length == 0; }
/// Sorted list of missing dependencies.
string[] missingDependencies() { return m_missingDependencies; }
/** Allows iteration of the dependency tree in topological order
*/
int delegate(int delegate(ref Package)) getTopologicalPackageList(bool children_first = false, Package root_package = null, string[string] configs = null)
{
// ugly way to avoid code duplication since inout isn't compatible with foreach type inference
return cast(int delegate(int delegate(ref Package)))(cast(const)this).getTopologicalPackageList(children_first, root_package, configs);
}
/// ditto
int delegate(int delegate(ref const Package)) getTopologicalPackageList(bool children_first = false, in Package root_package = null, string[string] configs = null)
const {
const(Package) rootpack = root_package ? root_package : m_rootPackage;
int iterator(int delegate(ref const Package) del)
{
int ret = 0;
bool[const(Package)] visited;
void perform_rec(in Package p){
if( p in visited ) return;
visited[p] = true;
if( !children_first ){
ret = del(p);
if( ret ) return;
}
auto cfg = configs.get(p.name, null);
PackageDependency[] deps;
if (!cfg.length) deps = p.getAllDependencies();
else {
auto depmap = p.getDependencies(cfg);
deps = depmap.byKey.map!(k => PackageDependency(PackageName(k), depmap[k])).array;
}
deps.sort!((a, b) => a.name.toString() < b.name.toString());
foreach (d; deps) {
auto dependency = getDependency(d.name.toString(), true);
assert(dependency || d.spec.optional,
format("Non-optional dependency '%s' of '%s' not found in dependency tree!?.", d.name, p.name));
if(dependency) perform_rec(dependency);
if( ret ) return;
}
if( children_first ){
ret = del(p);
if( ret ) return;
}
}
perform_rec(rootpack);
return ret;
}
return &iterator;
}
/** Retrieves a particular dependency by name.
Params:
name = (Qualified) package name of the dependency
is_optional = If set to true, will return `null` for unsatisfiable
dependencies instead of throwing an exception.
*/
inout(Package) getDependency(string name, bool is_optional)
inout {
if (auto pp = name in m_dependenciesByName)
return *pp;
if (!is_optional) throw new Exception("Unknown dependency: "~name);
else return null;
}
/** Returns the name of the default build configuration for the specified
target platform.
Params:
platform = The target build platform
allow_non_library_configs = If set to true, will use the first
possible configuration instead of the first "executable"
configuration.
*/
string getDefaultConfiguration(in BuildPlatform platform, bool allow_non_library_configs = true)
const {
auto cfgs = getPackageConfigs(platform, null, allow_non_library_configs);
return cfgs[m_rootPackage.name];
}
/** Overrides the configuration chosen for a particular package in the
dependency graph.
Setting a certain configuration here is equivalent to removing all
but one configuration from the package.
Params:
package_ = The package for which to force selecting a certain
dependency
config = Name of the configuration to force
*/
void overrideConfiguration(string package_, string config)
{
auto p = getDependency(package_, true);
enforce(p !is null,
format("Package '%s', marked for configuration override, is not present in dependency graph.", package_));
enforce(p.configurations.canFind(config),
format("Package '%s' does not have a configuration named '%s'.", package_, config));
m_overriddenConfigs[package_] = config;
}
/** Adds a test runner configuration for the root package.
Params:
settings = The generator settings to use
generate_main = Whether to generate the main.d file
base_config = Optional base configuration
custom_main_file = Optional path to file with custom main entry point
Returns:
Name of the added test runner configuration, or null for base configurations with target type `none`
*/
string addTestRunnerConfiguration(in GeneratorSettings settings, bool generate_main = true, string base_config = "", NativePath custom_main_file = NativePath())
{
if (base_config.length == 0) {
// if a custom main file was given, favor the first library configuration, so that it can be applied
if (!custom_main_file.empty) base_config = getDefaultConfiguration(settings.platform, false);
// else look for a "unittest" configuration
if (!base_config.length && rootPackage.configurations.canFind("unittest")) base_config = "unittest";
// if not found, fall back to the first "library" configuration
if (!base_config.length) base_config = getDefaultConfiguration(settings.platform, false);
// if still nothing found, use the first executable configuration
if (!base_config.length) base_config = getDefaultConfiguration(settings.platform, true);
}
BuildSettings lbuildsettings = settings.buildSettings.dup;
addBuildSettings(lbuildsettings, settings, base_config, null, true);
if (lbuildsettings.targetType == TargetType.none) {
logInfo(`Configuration '%s' has target type "none". Skipping test runner configuration.`, base_config);
return null;
}
if (lbuildsettings.targetType == TargetType.executable && base_config == "unittest") {
if (!custom_main_file.empty) logWarn("Ignoring custom main file.");
return base_config;
}
if (lbuildsettings.sourceFiles.empty) {
logInfo(`No source files found in configuration '%s'. Falling back to default configuration for test runner.`, base_config);
if (!custom_main_file.empty) logWarn("Ignoring custom main file.");
return getDefaultConfiguration(settings.platform);
}
const config = format("%s-test-%s", rootPackage.name.replace(".", "-").replace(":", "-"), base_config);
logInfo(`Generating test runner configuration '%s' for '%s' (%s).`, config, base_config, lbuildsettings.targetType);
BuildSettingsTemplate tcinfo = rootPackage.recipe.getConfiguration(base_config).buildSettings.dup;
tcinfo.targetType = TargetType.executable;
// set targetName unless specified explicitly in unittest base configuration
if (tcinfo.targetName.empty || base_config != "unittest")
tcinfo.targetName = config;
auto mainfil = tcinfo.mainSourceFile;
if (!mainfil.length) mainfil = rootPackage.recipe.buildSettings.mainSourceFile;
string custommodname;
if (!custom_main_file.empty) {
import std.path;
tcinfo.sourceFiles[""] ~= custom_main_file.relativeTo(rootPackage.path).toNativeString();
tcinfo.importPaths[""] ~= custom_main_file.parentPath.toNativeString();
custommodname = custom_main_file.head.name.baseName(".d");
}
// prepare the list of tested modules
string[] import_modules;
if (settings.single)
lbuildsettings.importPaths ~= NativePath(mainfil).parentPath.toNativeString;
bool firstTimePackage = true;
foreach (file; lbuildsettings.sourceFiles) {
if (file.endsWith(".d")) {
auto fname = NativePath(file).head.name;
NativePath msf = NativePath(mainfil);
if (msf.absolute)
msf = msf.relativeTo(rootPackage.path);
if (!settings.single && NativePath(file).relativeTo(rootPackage.path) == msf) {
logWarn("Excluding main source file %s from test.", mainfil);
tcinfo.excludedSourceFiles[""] ~= mainfil;
continue;
}
if (fname == "package.d") {
if (firstTimePackage) {
firstTimePackage = false;
logDiagnostic("Excluding package.d file from test due to https://issues.dlang.org/show_bug.cgi?id=11847");
}
continue;
}
import_modules ~= dub.internal.utils.determineModuleName(lbuildsettings, NativePath(file), rootPackage.path);
}
}
NativePath mainfile;
if (settings.tempBuild)
mainfile = getTempFile("dub_test_root", ".d");
else {
import dub.generators.build : computeBuildName;
mainfile = packageCache(settings.cache, this.rootPackage) ~
format("code/%s/dub_test_root.d",
computeBuildName(config, settings, import_modules));
}
auto escapedMainFile = mainfile.toNativeString().replace("$", "$$");
tcinfo.sourceFiles[""] ~= escapedMainFile;
tcinfo.mainSourceFile = escapedMainFile;
if (!settings.tempBuild) {
// add the directory containing dub_test_root.d to the import paths
tcinfo.importPaths[""] ~= NativePath(escapedMainFile).parentPath.toNativeString();
}
if (generate_main && (settings.force || !existsFile(mainfile))) {
ensureDirectory(mainfile.parentPath);
const runnerCode = custommodname.length ?
format("import %s;", custommodname) : DefaultTestRunnerCode;
const content = TestRunnerTemplate.format(
import_modules, import_modules, runnerCode);
writeFile(mainfile, content);
}
rootPackage.recipe.configurations ~= ConfigurationInfo(config, tcinfo);
return config;
}
/** Performs basic validation of various aspects of the package.
This will emit warnings to `stderr` if any discouraged names or
dependency patterns are found.
*/
void validate()
{
bool isSDL = !m_rootPackage.recipePath.empty
&& m_rootPackage.recipePath.head.name.endsWith(".sdl");
// some basic package lint
m_rootPackage.warnOnSpecialCompilerFlags();
string nameSuggestion() {
string ret;
ret ~= `Please modify the "name" field in %s accordingly.`.format(m_rootPackage.recipePath.toNativeString());
if (!m_rootPackage.recipe.buildSettings.targetName.length) {
if (isSDL) {
ret ~= ` You can then add 'targetName "%s"' to keep the current executable name.`.format(m_rootPackage.name);
} else {
ret ~= ` You can then add '"targetName": "%s"' to keep the current executable name.`.format(m_rootPackage.name);
}
}
return ret;
}
if (m_rootPackage.name != m_rootPackage.name.toLower()) {
logWarn(`DUB package names should always be lower case. %s`, nameSuggestion());
} else if (!m_rootPackage.recipe.name.all!(ch => ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9' || ch == '-' || ch == '_')) {
logWarn(`DUB package names may only contain alphanumeric characters, `
~ `as well as '-' and '_'. %s`, nameSuggestion());
}
enforce(!m_rootPackage.name.canFind(' '), "Aborting due to the package name containing spaces.");
foreach (d; m_rootPackage.getAllDependencies())
if (d.spec.isExactVersion && d.spec.version_.isBranch) {
string suggestion = isSDL
? format(`dependency "%s" repository="git+<git url>" version="<commit>"`, d.name)
: format(`"%s": {"repository": "git+<git url>", "version": "<commit>"}`, d.name);
logWarn("Dependency '%s' depends on git branch '%s', which is deprecated.",
d.name.toString().color(Mode.bold),
d.spec.version_.toString.color(Mode.bold));
logWarnTag("", "Specify the git repository and commit hash in your %s:",
(isSDL ? "dub.sdl" : "dub.json").color(Mode.bold));
logWarnTag("", "%s", suggestion.color(Mode.bold));
}
// search for orphan sub configurations
void warnSubConfig(string pack, string config) {
logWarn("The sub configuration directive \"%s\" -> [%s] "
~ "references a package that is not specified as a dependency "
~ "and will have no effect.", pack.color(Mode.bold), config.color(Color.blue));
}
void checkSubConfig(in PackageName name, string config) {
auto p = getDependency(name.toString(), true);
if (p && !p.configurations.canFind(config)) {
logWarn("The sub configuration directive \"%s\" -> [%s] "
~ "references a configuration that does not exist.",
name.toString().color(Mode.bold), config.color(Color.red));
}
}
auto globalbs = m_rootPackage.getBuildSettings();
foreach (p, c; globalbs.subConfigurations) {
if (p !in globalbs.dependencies) warnSubConfig(p, c);
else checkSubConfig(PackageName(p), c);
}
foreach (c; m_rootPackage.configurations) {
auto bs = m_rootPackage.getBuildSettings(c);
foreach (p, subConf; bs.subConfigurations) {
if (p !in bs.dependencies && p !in globalbs.dependencies)
warnSubConfig(p, subConf);
else checkSubConfig(PackageName(p), subConf);
}
}
// check for version specification mismatches
bool[Package] visited;
void validateDependenciesRec(Package pack) {
// perform basic package linting
pack.simpleLint();
foreach (d; pack.getAllDependencies()) {
auto basename = d.name.main;
d.spec.visit!(
(NativePath path) { /* Valid */ },
(Repository repo) { /* Valid */ },
(VersionRange vers) {
if (m_selections.hasSelectedVersion(basename)) {
auto selver = m_selections.getSelectedVersion(basename);
if (d.spec.merge(selver) == Dependency.Invalid) {
logWarn(`Selected package %s@%s does not match ` ~
`the dependency specification %s in ` ~
`package %s. Need to "%s"?`,
basename.toString().color(Mode.bold), selver,
vers, pack.name.color(Mode.bold),
"dub upgrade".color(Mode.bold));
}
}
},
);
auto deppack = getDependency(d.name.toString(), true);
if (deppack in visited) continue;
visited[deppack] = true;
if (deppack) validateDependenciesRec(deppack);
}
}
validateDependenciesRec(m_rootPackage);
}
/**
* Reloads dependencies
*
* This function goes through the project and make sure that all
* required packages are loaded. To do so, it uses information
* both from the recipe file (`dub.json`) and from the selections
* file (`dub.selections.json`).
*
* In the process, it populates the `dependencies`, `missingDependencies`,
* and `hasAllDependencies` properties, which can only be relied on
* once this has run once (the constructor always calls this).
*/
void reinit()
{
m_dependencies = null;
m_dependenciesByName = null;
m_missingDependencies = [];
collectDependenciesRec(m_rootPackage);
foreach (p; m_dependencies) m_dependenciesByName[p.name] = p;
m_missingDependencies.sort();
}
/// Implementation of `reinit`
private void collectDependenciesRec(Package pack, int depth = 0)
{
auto indent = replicate(" ", depth);
logDebug("%sCollecting dependencies for %s", indent, pack.name);
indent ~= " ";
foreach (dep; pack.getAllDependencies()) {
Dependency vspec = dep.spec;
Package p;
auto basename = dep.name.main;
auto subname = dep.name.sub;
// non-optional and optional-default dependencies (if no selections file exists)
// need to be satisfied
bool is_desired = !vspec.optional || m_selections.hasSelectedVersion(basename) || (vspec.default_ && m_selections.bare);
if (dep.name.toString() == m_rootPackage.basePackage.name) {
vspec = Dependency(m_rootPackage.version_);
p = m_rootPackage.basePackage;
} else if (basename.toString() == m_rootPackage.basePackage.name) {
vspec = Dependency(m_rootPackage.version_);
try p = m_packageManager.getSubPackage(m_rootPackage.basePackage, subname, false);
catch (Exception e) {
logDiagnostic("%sError getting sub package %s: %s", indent, dep.name, e.msg);
if (is_desired) m_missingDependencies ~= dep.name.toString();
continue;
}
} else if (m_selections.hasSelectedVersion(basename)) {
vspec = m_selections.getSelectedVersion(basename);
p = vspec.visit!(
(NativePath path_) {
auto path = path_.absolute ? path_ : m_rootPackage.path ~ path_;
auto tmp = m_packageManager.getOrLoadPackage(path, NativePath.init, true);
return resolveSubPackage(tmp, subname, true);
},
(Repository repo) {
return m_packageManager.loadSCMPackage(dep.name, repo);
},
(VersionRange range) {
// See `dub.recipe.selection : SelectedDependency.fromYAML`
assert(range.isExactVersion());
return m_packageManager.getPackage(dep.name, vspec.version_);
},
);
} else if (m_dependencies.canFind!(d => PackageName(d.name).main == basename)) {
auto idx = m_dependencies.countUntil!(d => PackageName(d.name).main == basename);
auto bp = m_dependencies[idx].basePackage;
vspec = Dependency(bp.path);
p = resolveSubPackage(bp, subname, false);
} else {
logDiagnostic("%sVersion selection for dependency %s (%s) of %s is missing.",
indent, basename, dep.name, pack.name);
}
// We didn't find the package
if (p is null)
{
if (!vspec.repository.empty) {
p = m_packageManager.loadSCMPackage(dep.name, vspec.repository);
enforce(p !is null,
"Unable to fetch '%s@%s' using git - does the repository and version exist?".format(
dep.name, vspec.repository));
} else if (!vspec.path.empty && is_desired) {
NativePath path = vspec.path;
if (!path.absolute) path = pack.path ~ path;
logDiagnostic("%sAdding local %s in %s", indent, dep.name, path);
p = m_packageManager.getOrLoadPackage(path, NativePath.init, true);
if (p.parentPackage !is null) {
logWarn("%sSub package %s must be referenced using the path to it's parent package.", indent, dep.name);
p = p.parentPackage;
}
p = resolveSubPackage(p, subname, false);
enforce(p.name == dep.name.toString(),
format("Path based dependency %s is referenced with a wrong name: %s vs. %s",
path.toNativeString(), dep.name, p.name));
} else {
logDiagnostic("%sMissing dependency %s %s of %s", indent, dep.name, vspec, pack.name);
if (is_desired) m_missingDependencies ~= dep.name.toString();
continue;
}
}
if (!m_dependencies.canFind(p)) {
logDiagnostic("%sFound dependency %s %s", indent, dep.name, vspec.toString());
m_dependencies ~= p;
if (basename.toString() == m_rootPackage.basePackage.name)
p.warnOnSpecialCompilerFlags();
collectDependenciesRec(p, depth+1);
}
m_dependees[p] ~= pack;
//enforce(p !is null, "Failed to resolve dependency "~dep.name~" "~vspec.toString());
}
}
/// Convenience function used by `reinit`
private Package resolveSubPackage(Package p, string subname, bool silentFail) {
if (!subname.length || p is null)
return p;
return m_packageManager.getSubPackage(p, subname, silentFail);
}
/// Returns the name of the root package.
@property string name() const { return m_rootPackage ? m_rootPackage.name : "app"; }
/// Returns the names of all configurations of the root package.
@property string[] configurations() const { return m_rootPackage.configurations; }
/// Returns the names of all built-in and custom build types of the root package.
/// The default built-in build type is the first item in the list.
@property string[] builds() const { return builtinBuildTypes ~ m_rootPackage.customBuildTypes; }
/// Returns a map with the configuration for all packages in the dependency tree.
string[string] getPackageConfigs(in BuildPlatform platform, string config, bool allow_non_library = true)
const {
import std.typecons : Rebindable, rebindable;
import std.range : only;
// prepare by collecting information about all packages in the project
// qualified names and dependencies are cached, to avoid recomputing
// them multiple times during the algorithm
auto packages = collectPackageInformation();
// graph of the project's package configuration dependencies
// (package, config) -> (sub-package, sub-config)
static struct Vertex { size_t pack = size_t.max; string config; }
static struct Edge { size_t from, to; }
Vertex[] configs;
void[0][Vertex] configs_set;
Edge[] edges;
size_t createConfig(size_t pack_idx, string config) {
foreach (i, v; configs)
if (v.pack == pack_idx && v.config == config)
return i;
auto pname = packages[pack_idx].name;
assert(pname !in m_overriddenConfigs || config == m_overriddenConfigs[pname]);
logDebug("Add config %s %s", pname, config);
auto cfg = Vertex(pack_idx, config);
configs ~= cfg;
configs_set[cfg] = (void[0]).init;
return configs.length-1;
}
bool haveConfig(size_t pack_idx, string config) {
return (Vertex(pack_idx, config) in configs_set) !is null;
}
void removeConfig(size_t config_index) {
logDebug("Eliminating config %s for %s", configs[config_index].config, configs[config_index].pack);
auto had_dep_to_pack = new bool[configs.length];
auto still_has_dep_to_pack = new bool[configs.length];
// eliminate all edges that connect to config 'config_index' and
// track all connected configs
edges = edges.filterInPlace!((e) {
if (e.to == config_index) {
had_dep_to_pack[e.from] = true;
return false;
} else if (configs[e.to].pack == configs[config_index].pack) {
still_has_dep_to_pack[e.from] = true;
}
return e.from != config_index;
});
// mark config as removed
configs_set.remove(configs[config_index]);
configs[config_index] = Vertex.init;
// also remove any configs that cannot be satisfied anymore
foreach (j; 0 .. configs.length)
if (j != config_index && had_dep_to_pack[j] && !still_has_dep_to_pack[j])
removeConfig(j);
}
bool[] reachable = new bool[packages.length]; // reused to avoid continuous re-allocation
bool isReachableByAllParentPacks(size_t cidx) {
foreach (p; packages[configs[cidx].pack].parents) reachable[p] = false;
foreach (e; edges) {
if (e.to != cidx) continue;
reachable[configs[e.from].pack] = true;
}
foreach (p; packages[configs[cidx].pack].parents)
if (!reachable[p])
return false;
return true;
}
string[][] depconfigs = new string[][](packages.length);
void determineDependencyConfigs(size_t pack_idx, string c)
{
void[0][Edge] edges_set;
void createEdge(size_t from, size_t to) {
if (Edge(from, to) in edges_set)
return;
logDebug("Including %s %s -> %s %s", configs[from].pack, configs[from].config, configs[to].pack, configs[to].config);
edges ~= Edge(from, to);
edges_set[Edge(from, to)] = (void[0]).init;
}
auto pack = &packages[pack_idx];
// below we call createConfig for the main package if
// config.length is not zero. Carry on for that case,
// otherwise we've handle the pair (p, c) already
if(haveConfig(pack_idx, c) && !(config.length && pack.name == m_rootPackage.name && config == c))
return;
foreach (d; pack.dependencies) {
auto dp = packages.getPackageIndex(d.name.toString());
if (dp == size_t.max) continue;
depconfigs[dp].length = 0;
depconfigs[dp].assumeSafeAppend;
void setConfigs(R)(R configs) {
configs
.filter!(c => haveConfig(dp, c))
.each!((c) { depconfigs[dp] ~= c; });
}
if (auto pc = packages[dp].name in m_overriddenConfigs) {
setConfigs(only(*pc));
} else {
auto subconf = pack.package_.getSubConfiguration(c, packages[dp].package_, platform);
if (!subconf.empty) setConfigs(only(subconf));
else setConfigs(packages[dp].package_.getPlatformConfigurations(platform));
}
// if no valid configuration was found for a dependency, don't include the
// current configuration
if (!depconfigs[dp].length) {
logDebug("Skip %s %s (missing configuration for %s)", pack.name, c, packages[dp].name);
return;
}
}
// add this configuration to the graph
size_t cidx = createConfig(pack_idx, c);
foreach (d; pack.dependencies) {
if (auto pdp = d.name.toString() in packages)
foreach (sc; depconfigs[*pdp])
createEdge(cidx, createConfig(*pdp, sc));
}
}
string[] allconfigs_path;
void determineAllConfigs(size_t pack_idx)
{
auto pack = &packages[pack_idx];
auto idx = allconfigs_path.countUntil(pack.name);
enforce(idx < 0, format("Detected dependency cycle: %s", (allconfigs_path[idx .. $] ~ pack.name).join("->")));
allconfigs_path ~= pack.name;
scope (exit) {
allconfigs_path.length--;
allconfigs_path.assumeSafeAppend;
}
// first, add all dependency configurations
foreach (d; pack.dependencies)
if (auto pi = d.name.toString() in packages)
determineAllConfigs(*pi);
// for each configuration, determine the configurations usable for the dependencies
if (auto pc = pack.name in m_overriddenConfigs)
determineDependencyConfigs(pack_idx, *pc);
else
foreach (c; pack.package_.getPlatformConfigurations(platform, pack.package_ is m_rootPackage && allow_non_library))
determineDependencyConfigs(pack_idx, c);
}
// first, create a graph of all possible package configurations
assert(packages[0].package_ is m_rootPackage);
if (config.length) createConfig(0, config);
determineAllConfigs(0);
// then, successively remove configurations until only one configuration
// per package is left
bool changed;
do {
// remove all configs that are not reachable by all parent packages
changed = false;
foreach (i, ref c; configs) {
if (c == Vertex.init) continue; // ignore deleted configurations
if (!isReachableByAllParentPacks(i)) {
logDebug("%s %s NOT REACHABLE by all of (%s):", c.pack, c.config, packages[c.pack].parents);
removeConfig(i);
changed = true;
}
}
// when all edges are cleaned up, pick one package and remove all but one config
if (!changed) {
foreach (pidx; 0 .. packages.length) {
size_t cnt = 0;
foreach (i, ref c; configs)
if (c.pack == pidx && ++cnt > 1) {
logDebug("NON-PRIMARY: %s %s", c.pack, c.config);
removeConfig(i);
}
if (cnt > 1) {
changed = true;
break;
}
}
}
} while (changed);
// print out the resulting tree
foreach (e; edges) logDebug(" %s %s -> %s %s", configs[e.from].pack, configs[e.from].config, configs[e.to].pack, configs[e.to].config);
// return the resulting configuration set as an AA
string[string] ret;
foreach (c; configs) {
if (c == Vertex.init) continue; // ignore deleted configurations
auto pname = packages[c.pack].name;
assert(ret.get(pname, c.config) == c.config, format("Conflicting configurations for %s found: %s vs. %s", pname, c.config, ret[pname]));
logDebug("Using configuration '%s' for %s", c.config, pname);
ret[pname] = c.config;
}
// check for conflicts (packages missing in the final configuration graph)
auto visited = new bool[](packages.length);
void checkPacksRec(size_t pack_idx) {
if (visited[pack_idx]) return;
visited[pack_idx] = true;
auto pname = packages[pack_idx].name;
auto pc = pname in ret;
enforce(pc !is null, "Could not resolve configuration for package "~pname);
foreach (p, dep; packages[pack_idx].package_.getDependencies(*pc)) {
auto deppack = getDependency(p, dep.optional);
if (deppack) checkPacksRec(packages[].countUntil!(p => p.package_ is deppack));
}
}
checkPacksRec(0);
return ret;
}
/** Returns an ordered list of all packages with the additional possibility
to look up by name.
*/
private auto collectPackageInformation()
const {
static struct PackageInfo {
const(Package) package_;
size_t[] parents;
string name;
PackageDependency[] dependencies;
}
static struct PackageInfoAccessor {
private {
PackageInfo[] m_packages;
size_t[string] m_packageMap;
}
private void initialize(P)(P all_packages, size_t reserve_count)
{
m_packages.reserve(reserve_count);
foreach (p; all_packages) {
auto pname = p.name;
m_packageMap[pname] = m_packages.length;
m_packages ~= PackageInfo(p, null, pname, p.getAllDependencies());
}
foreach (pack_idx, ref pack_info; m_packages)
foreach (d; pack_info.dependencies)
if (auto pi = d.name.toString() in m_packageMap)
m_packages[*pi].parents ~= pack_idx;
}
size_t length() const { return m_packages.length; }
const(PackageInfo)[] opIndex() const { return m_packages; }
ref const(PackageInfo) opIndex(size_t package_index) const { return m_packages[package_index]; }
size_t getPackageIndex(string package_name) const { return m_packageMap.get(package_name, size_t.max); }
const(size_t)* opBinaryRight(string op = "in")(string package_name) const { return package_name in m_packageMap; }
}
PackageInfoAccessor ret;
ret.initialize(getTopologicalPackageList(), m_dependencies.length);
return ret;
}
/**
* Fills `dst` with values from this project.
*
* `dst` gets initialized according to the given platform and config.
*
* Params:
* dst = The BuildSettings struct to fill with data.
* gsettings = The generator settings to retrieve the values for.
* config = Values of the given configuration will be retrieved.
* root_package = If non null, use it instead of the project's real root package.
* shallow = If true, collects only build settings for the main package (including inherited settings) and doesn't stop on target type none and sourceLibrary.
*/
void addBuildSettings(ref BuildSettings dst, in GeneratorSettings gsettings, string config, in Package root_package = null, bool shallow = false)
const {
import dub.internal.utils : stripDlangSpecialChars;
auto configs = getPackageConfigs(gsettings.platform, config);
foreach (pkg; this.getTopologicalPackageList(false, root_package, configs)) {
auto pkg_path = pkg.path.toNativeString();
dst.addVersions(["Have_" ~ stripDlangSpecialChars(pkg.name)]);
assert(pkg.name in configs, "Missing configuration for "~pkg.name);
logDebug("Gathering build settings for %s (%s)", pkg.name, configs[pkg.name]);
auto psettings = pkg.getBuildSettings(gsettings.platform, configs[pkg.name]);
if (psettings.targetType != TargetType.none) {
if (shallow && pkg !is m_rootPackage)
psettings.sourceFiles = null;
processVars(dst, this, pkg, psettings, gsettings);
if (!gsettings.single && psettings.importPaths.empty)
logWarn(`Package %s (configuration "%s") defines no import paths, use {"importPaths": [...]} or the default package directory structure to fix this.`, pkg.name, configs[pkg.name]);
if (psettings.mainSourceFile.empty && pkg is m_rootPackage && psettings.targetType == TargetType.executable)
logWarn(`Executable configuration "%s" of package %s defines no main source file, this may cause certain build modes to fail. Add an explicit "mainSourceFile" to the package description to fix this.`, configs[pkg.name], pkg.name);
}
if (pkg is m_rootPackage) {
if (!shallow) {
enforce(psettings.targetType != TargetType.none, "Main package has target type \"none\" - stopping build.");
enforce(psettings.targetType != TargetType.sourceLibrary, "Main package has target type \"sourceLibrary\" which generates no target - stopping build.");
}
dst.targetType = psettings.targetType;
dst.targetPath = psettings.targetPath;
dst.targetName = psettings.targetName;
if (!psettings.workingDirectory.empty)
dst.workingDirectory = processVars(psettings.workingDirectory, this, pkg, gsettings, true, [dst.environments, dst.buildEnvironments]);
if (psettings.mainSourceFile.length)
dst.mainSourceFile = processVars(psettings.mainSourceFile, this, pkg, gsettings, true, [dst.environments, dst.buildEnvironments]);
}
}
// always add all version identifiers of all packages
foreach (pkg; this.getTopologicalPackageList(false, null, configs)) {
auto psettings = pkg.getBuildSettings(gsettings.platform, configs[pkg.name]);
dst.addVersions(psettings.versions);
}
}
/** Fills `dst` with build settings specific to the given build type.
Params:
dst = The `BuildSettings` instance to add the build settings to
gsettings = Target generator settings
for_root_package = Selects if the build settings are for the root
package or for one of the dependencies. Unittest flags will
only be added to the root package.
*/
void addBuildTypeSettings(ref BuildSettings dst, in GeneratorSettings gsettings, bool for_root_package = true)
{
bool usedefflags = !(dst.requirements & BuildRequirement.noDefaultFlags);
if (usedefflags) {
BuildSettings btsettings;
m_rootPackage.addBuildTypeSettings(btsettings, gsettings.platform, gsettings.buildType);
if (!for_root_package) {
// don't propagate unittest switch to dependencies, as dependent
// unit tests aren't run anyway and the additional code may
// cause linking to fail on Windows (issue #640)
btsettings.removeOptions(BuildOption.unittests);
}
processVars(dst, this, m_rootPackage, btsettings, gsettings);
}
}
/// Outputs a build description of the project, including its dependencies.
ProjectDescription describe(GeneratorSettings settings)
{
import dub.generators.targetdescription;
// store basic build parameters