-
-
Notifications
You must be signed in to change notification settings - Fork 227
/
project.d
1496 lines (1296 loc) · 51.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.internal.utils;
import dub.internal.vibecompat.core.file;
import dub.internal.vibecompat.core.log;
import dub.internal.vibecompat.data.json;
import dub.internal.vibecompat.inet.url;
import dub.package_;
import dub.packagemanager;
import dub.packagesupplier;
import dub.generators.generator;
// todo: cleanup imports.
import std.algorithm;
import std.array;
import std.conv;
import std.datetime;
import std.exception;
import std.file;
import std.process;
import std.string;
import std.typecons;
import std.zip;
import std.encoding : sanitize;
/**
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;
Json m_packageSettings;
Package m_rootPackage;
Package[] m_dependencies;
Package[][Package] m_dependees;
SelectedVersions m_selections;
}
/** 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
*/
this(PackageManager package_manager, Path 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);
}
this(package_manager, pack);
}
/// ditto
this(PackageManager package_manager, Package pack)
{
m_packageManager = package_manager;
m_rootPackage = pack;
m_packageSettings = Json.emptyObject;
try m_packageSettings = jsonFromFile(m_rootPackage.path ~ ".dub/dub.json", true);
catch(Exception t) logDiagnostic("Failed to read .dub/dub.json: %s", t.msg);
auto selverfile = m_rootPackage.path ~ SelectedVersions.defaultFile;
if (existsFile(selverfile)) {
try m_selections = new SelectedVersions(selverfile);
catch(Exception e) {
logWarn("Failed to load %s: %s", SelectedVersions.defaultFile, e.msg);
logDiagnostic("Full error: %s", e.toString().sanitize);
m_selections = new SelectedVersions;
}
} else m_selections = new SelectedVersions;
reinit();
}
/// Gathers information
deprecated("Will be removed for version 1.0.0.") @property string info()
const {
if(!m_rootPackage)
return "-Unrecognized application in '"~m_rootPackage.path.toNativeString()~"' (probably no dub.json in this directory)";
string s = "-Application identifier: " ~ m_rootPackage.name;
s ~= "\n" ~ m_rootPackage.generateInfoString();
s ~= "\n-Retrieved dependencies:";
foreach(p; m_dependencies)
s ~= "\n" ~ p.generateInfoString();
return s;
}
/// Gets all retrieved packages as a "packageId" = "version" associative array
deprecated("Will be removed for version 1.0.0.") @property string[string] cachedPackagesIDs() const {
string[string] pkgs;
foreach(p; m_dependencies)
pkgs[p.name] = p.version_.toString();
return pkgs;
}
/** 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.
@property inout(PackageManager) packageManager() inout { return m_packageManager; }
/** 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.keys.map!(k => PackageDependency(k, depmap[k])).array;
}
deps.sort!((a, b) => a.name < b.name);
foreach (d; deps) {
auto dependency = getDependency(d.name, 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 {
foreach(dp; m_dependencies)
if( dp.name == name )
return dp;
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(BuildPlatform platform, bool allow_non_library_configs = true)
const {
auto cfgs = getPackageConfigs(platform, null, allow_non_library_configs);
return cfgs[m_rootPackage.name];
}
/** 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()
{
// 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 (m_rootPackage.recipePath.head.toString().endsWith(".sdl")) {
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(`WARNING: 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(`WARNING: 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) {
logWarn("WARNING: A deprecated branch based version specification is used "
~ "for the dependency %s. Please use numbered versions instead. Also "
~ "note that you can still use the %s file to override a certain "
~ "dependency to use a branch instead.",
d.name, SelectedVersions.defaultFile);
}
bool[Package] visited;
void validateDependenciesRec(Package pack) {
foreach (d; pack.getAllDependencies()) {
auto basename = getBasePackageName(d.name);
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 \"dub upgrade\"?",
basename, selver, d.spec, pack.name);
}
}
auto deppack = getDependency(name, true);
if (deppack in visited) continue;
visited[deppack] = true;
if (deppack) validateDependenciesRec(deppack);
}
}
validateDependenciesRec(m_rootPackage);
}
/// Reloads dependencies.
void reinit()
{
m_dependencies = null;
m_packageManager.refresh(false);
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 = getBasePackageName(dep.name);
if (dep.name == m_rootPackage.basePackage.name) {
vspec = Dependency(m_rootPackage.version_);
p = m_rootPackage.basePackage;
} else if (basename == m_rootPackage.basePackage.name) {
vspec = Dependency(m_rootPackage.version_);
try p = m_packageManager.getSubPackage(m_rootPackage.basePackage, getSubPackageName(dep.name), false);
catch (Exception e) {
logDiagnostic("%sError getting sub package %s: %s", indent, dep.name, e.msg);
continue;
}
} else if (m_selections.hasSelectedVersion(basename)) {
vspec = m_selections.getSelectedVersion(basename);
if (vspec.path.empty) p = m_packageManager.getBestPackage(dep.name, vspec);
else {
auto path = vspec.path;
if (!path.absolute) path = m_rootPackage.path ~ path;
p = m_packageManager.getOrLoadPackage(path, Path.init, true);
}
} else if (m_dependencies.canFind!(d => getBasePackageName(d.name) == basename)) {
auto idx = m_dependencies.countUntil!(d => getBasePackageName(d.name) == basename);
auto bp = m_dependencies[idx].basePackage;
vspec = Dependency(bp.path);
p = m_packageManager.getSubPackage(bp, getSubPackageName(dep.name), false);
} else {
logDiagnostic("%sVersion selection for dependency %s (%s) of %s is missing.",
indent, basename, dep.name, pack.name);
}
if (!p && !vspec.path.empty) {
Path path = vspec.path;
if (!path.absolute) path = pack.path ~ path;
logDiagnostic("%sAdding local %s", indent, path);
p = m_packageManager.getOrLoadPackage(path, Path.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;
}
if (dep.name.canFind(':')) p = m_packageManager.getSubPackage(p, getSubPackageName(dep.name), false);
enforce(p.name == dep.name,
format("Path based dependency %s is referenced with a wrong name: %s vs. %s",
path.toNativeString(), dep.name, p.name));
}
if (!p) {
logDiagnostic("%sMissing dependency %s %s of %s", indent, dep.name, vspec, pack.name);
continue;
}
if (!m_dependencies.canFind(p)) {
logDiagnostic("%sFound dependency %s %s", indent, dep.name, vspec.toString());
m_dependencies ~= p;
p.warnOnSpecialCompilerFlags();
collectDependenciesRec(p, depth+1);
}
m_dependees[p] ~= pack;
//enforce(p !is null, "Failed to resolve dependency "~dep.name~" "~vspec.toString());
}
}
collectDependenciesRec(m_rootPackage);
}
/// 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 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 {
struct Vertex { string pack, config; }
struct Edge { size_t from, to; }
Vertex[] configs;
Edge[] edges;
string[][string] parents;
parents[m_rootPackage.name] = null;
foreach (p; getTopologicalPackageList())
foreach (d; p.getAllDependencies())
parents[d.name] ~= p.name;
size_t createConfig(string pack, string config) {
foreach (i, v; configs)
if (v.pack == pack && v.config == config)
return i;
logDebug("Add config %s %s", pack, config);
configs ~= Vertex(pack, config);
return configs.length-1;
}
bool haveConfig(string pack, string config) {
return configs.any!(c => c.pack == pack && c.config == config);
}
size_t createEdge(size_t from, size_t to) {
auto idx = edges.countUntil(Edge(from, to));
if (idx >= 0) return idx;
logDebug("Including %s %s -> %s %s", configs[from].pack, configs[from].config, configs[to].pack, configs[to].config);
edges ~= Edge(from, to);
return edges.length-1;
}
void removeConfig(size_t i) {
logDebug("Eliminating config %s for %s", configs[i].config, configs[i].pack);
configs = configs.remove(i);
edges = edges.filter!(e => e.from != i && e.to != i).array();
foreach (ref e; edges) {
if (e.from > i) e.from--;
if (e.to > i) e.to--;
}
}
bool isReachable(string pack, string conf) {
if (pack == configs[0].pack && configs[0].config == conf) return true;
foreach (e; edges)
if (configs[e.to].pack == pack && configs[e.to].config == conf)
return true;
return false;
//return (pack == configs[0].pack && conf == configs[0].config) || edges.canFind!(e => configs[e.to].pack == pack && configs[e.to].config == config);
}
bool isReachableByAllParentPacks(size_t cidx) {
bool[string] r;
foreach (p; parents[configs[cidx].pack]) r[p] = false;
foreach (e; edges) {
if (e.to != cidx) continue;
if (auto pp = configs[e.from].pack in r) *pp = true;
}
foreach (bool v; r) if (!v) return false;
return true;
}
string[] allconfigs_path;
// create a graph of all possible package configurations (package, config) -> (subpackage, subconfig)
void determineAllConfigs(in Package p)
{
auto idx = allconfigs_path.countUntil(p.name);
enforce(idx < 0, format("Detected dependency cycle: %s", (allconfigs_path[idx .. $] ~ p.name).join("->")));
allconfigs_path ~= p.name;
scope (exit) allconfigs_path.length--;
// first, add all dependency configurations
foreach (d; p.getAllDependencies) {
auto dp = getDependency(d.name, true);
if (!dp) continue;
determineAllConfigs(dp);
}
// for each configuration, determine the configurations usable for the dependencies
outer: foreach (c; p.getPlatformConfigurations(platform, p is m_rootPackage && allow_non_library)) {
string[][string] depconfigs;
foreach (d; p.getAllDependencies()) {
auto dp = getDependency(d.name, true);
if (!dp) continue;
string[] cfgs;
auto subconf = p.getSubConfiguration(c, dp, platform);
if (!subconf.empty) cfgs = [subconf];
else cfgs = dp.getPlatformConfigurations(platform);
cfgs = cfgs.filter!(c => haveConfig(d.name, c)).array;
// if no valid configuration was found for a dependency, don't include the
// current configuration
if (!cfgs.length) {
logDebug("Skip %s %s (missing configuration for %s)", p.name, c, dp.name);
continue outer;
}
depconfigs[d.name] = cfgs;
}
// add this configuration to the graph
size_t cidx = createConfig(p.name, c);
foreach (d; p.getAllDependencies())
foreach (sc; depconfigs.get(d.name, null))
createEdge(cidx, createConfig(d.name, sc));
}
}
if (config.length) createConfig(m_rootPackage.name, config);
determineAllConfigs(m_rootPackage);
// 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;
for (size_t i = 0; i < configs.length; ) {
if (!isReachableByAllParentPacks(i)) {
logDebug("NOT REACHABLE by (%s):", parents[configs[i].pack]);
removeConfig(i);
changed = true;
} else i++;
}
// when all edges are cleaned up, pick one package and remove all but one config
if (!changed) {
foreach (p; getTopologicalPackageList()) {
size_t cnt = 0;
for (size_t i = 0; i < configs.length; ) {
if (configs[i].pack == p.name) {
if (++cnt > 1) {
logDebug("NON-PRIMARY:");
removeConfig(i);
} else i++;
} else 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) {
assert(ret.get(c.pack, c.config) == c.config, format("Conflicting configurations for %s found: %s vs. %s", c.pack, c.config, ret[c.pack]));
logDebug("Using configuration '%s' for %s", c.config, c.pack);
ret[c.pack] = c.config;
}
// check for conflicts (packages missing in the final configuration graph)
void checkPacksRec(in Package pack) {
auto pc = pack.name in ret;
enforce(pc !is null, "Could not resolve configuration for package "~pack.name);
foreach (p, dep; pack.getDependencies(*pc)) {
auto deppack = getDependency(p, dep.optional);
if (deppack) checkPacksRec(deppack);
}
}
checkPacksRec(m_rootPackage);
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.
* platform = The platform 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 BuildPlatform platform, string config, in Package root_package = null, bool shallow = false)
const {
import dub.internal.utils : stripDlangSpecialChars;
auto configs = getPackageConfigs(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(platform, configs[pkg.name]);
if (psettings.targetType != TargetType.none) {
if (shallow && pkg !is m_rootPackage)
psettings.sourceFiles = null;
processVars(dst, this, pkg, psettings);
if (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, true);
if (psettings.mainSourceFile.length)
dst.mainSourceFile = processVars(psettings.mainSourceFile, this, pkg, true);
}
}
// always add all version identifiers of all packages
foreach (pkg; this.getTopologicalPackageList(false, null, configs)) {
auto psettings = pkg.getBuildSettings(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
platform = Target build platform
build_type = Name of the build type
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 BuildPlatform platform, string build_type, bool for_root_package = true)
{
bool usedefflags = !(dst.requirements & BuildRequirement.noDefaultFlags);
if (usedefflags) {
BuildSettings btsettings;
m_rootPackage.addBuildTypeSettings(btsettings, platform, build_type);
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);
}
}
/// Determines if the given dependency is already indirectly referenced by other dependencies of pack.
deprecated("Will be removed for version 1.0.0.") bool isRedundantDependency(in Package pack, in Package dependency)
const {
foreach (dep; pack.recipe.dependencies.byKey) {
auto dp = getDependency(dep, true);
if (!dp) continue;
if (dp is dependency) continue;
foreach (ddp; getTopologicalPackageList(false, dp))
if (ddp is dependency) return true;
}
return false;
}
/// Outputs a build description of the project, including its dependencies.
ProjectDescription describe(GeneratorSettings settings)
{
import dub.generators.targetdescription;
// store basic build parameters
ProjectDescription ret;
ret.rootPackage = m_rootPackage.name;
ret.configuration = settings.config;
ret.buildType = settings.buildType;
ret.compiler = settings.platform.compiler;
ret.architecture = settings.platform.architecture;
ret.platform = settings.platform.platform;
// collect high level information about projects (useful for IDE display)
auto configs = getPackageConfigs(settings.platform, settings.config);
ret.packages ~= m_rootPackage.describe(settings.platform, settings.config);
foreach (dep; m_dependencies)
ret.packages ~= dep.describe(settings.platform, configs[dep.name]);
foreach (p; getTopologicalPackageList(false, null, configs))
ret.packages[ret.packages.countUntil!(pp => pp.name == p.name)].active = true;
if (settings.buildType.length) {
// collect build target information (useful for build tools)
auto gen = new TargetDescriptionGenerator(this);
try {
gen.generate(settings);
ret.targets = gen.targetDescriptions;
ret.targetLookup = gen.targetDescriptionLookup;
} catch (Exception e) {
logDiagnostic("Skipping targets description: %s", e.msg);
logDebug("Full error: %s", e.toString().sanitize);
}
}
return ret;
}
/// ditto
deprecated("Will be removed for version 1.0.0.") void describe(ref Json dst, BuildPlatform platform, string config)
{
auto desc = describe(platform, config);
foreach (string key, value; desc.serializeToJson())
dst[key] = value;
}
/// ditto
deprecated("Use the overload taking a GeneratorSettings instance. Will be removed for version 1.0.0.")
ProjectDescription describe(BuildPlatform platform, string config, string build_type = null)
{
GeneratorSettings settings;
settings.platform = platform;
settings.compiler = getCompiler(platform.compilerBinary);
settings.config = config;
settings.buildType = build_type;
return describe(settings);
}
private string[] listBuildSetting(string attributeName)(BuildPlatform platform,
string config, ProjectDescription projectDescription, Compiler compiler, bool disableEscaping)
{
return listBuildSetting!attributeName(platform, getPackageConfigs(platform, config),
projectDescription, compiler, disableEscaping);
}
private string[] listBuildSetting(string attributeName)(BuildPlatform platform,
string[string] configs, ProjectDescription projectDescription, Compiler compiler, bool disableEscaping)
{
if (compiler)
return formatBuildSettingCompiler!attributeName(platform, configs, projectDescription, compiler, disableEscaping);
else
return formatBuildSettingPlain!attributeName(platform, configs, projectDescription);
}
// Output a build setting formatted for a compiler
private string[] formatBuildSettingCompiler(string attributeName)(BuildPlatform platform,
string[string] configs, ProjectDescription projectDescription, Compiler compiler, bool disableEscaping)
{
import std.process : escapeShellFileName;
import std.path : dirSeparator;
assert(compiler);
auto targetDescription = projectDescription.lookupTarget(projectDescription.rootPackage);
auto buildSettings = targetDescription.buildSettings;
string[] values;
switch (attributeName)
{
case "dflags":
case "linkerFiles":
case "mainSourceFile":
case "importFiles":
values = formatBuildSettingPlain!attributeName(platform, configs, projectDescription);
break;
case "lflags":
case "sourceFiles":
case "versions":
case "debugVersions":
case "importPaths":
case "stringImportPaths":
case "options":
auto bs = buildSettings.dup;
bs.dflags = null;
// Ensure trailing slash on directory paths
auto ensureTrailingSlash = (string path) => path.endsWith(dirSeparator) ? path : path ~ dirSeparator;
static if (attributeName == "importPaths")
bs.importPaths = bs.importPaths.map!(ensureTrailingSlash).array();
else static if (attributeName == "stringImportPaths")
bs.stringImportPaths = bs.stringImportPaths.map!(ensureTrailingSlash).array();
compiler.prepareBuildSettings(bs, BuildSetting.all & ~to!BuildSetting(attributeName));
values = bs.dflags;
break;
case "libs":
auto bs = buildSettings.dup;
bs.dflags = null;
bs.lflags = null;
bs.sourceFiles = null;
bs.targetType = TargetType.none; // Force Compiler to NOT omit dependency libs when package is a library.
compiler.prepareBuildSettings(bs, BuildSetting.all & ~to!BuildSetting(attributeName));
if (bs.lflags)
values = compiler.lflagsToDFlags( bs.lflags );
else if (bs.sourceFiles)
values = compiler.lflagsToDFlags( bs.sourceFiles );
else
values = bs.dflags;
break;
default: assert(0);
}
// Escape filenames and paths
if(!disableEscaping)
{
switch (attributeName)
{
case "mainSourceFile":
case "linkerFiles":
case "copyFiles":
case "importFiles":
case "stringImportFiles":
case "sourceFiles":
case "importPaths":
case "stringImportPaths":
return values.map!(escapeShellFileName).array();
default:
return values;
}
}
return values;
}
// Output a build setting without formatting for any particular compiler
private string[] formatBuildSettingPlain(string attributeName)(BuildPlatform platform, string[string] configs, ProjectDescription projectDescription)
{
import std.path : buildNormalizedPath, dirSeparator;
import std.range : only;
string[] list;
enforce(projectDescription.lookupRootPackage().targetType != TargetType.none,
"Target type is 'none'. Cannot list build settings.");
auto targetDescription = projectDescription.lookupTarget(projectDescription.rootPackage);
auto buildSettings = targetDescription.buildSettings;
// Return any BuildSetting member attributeName as a range of strings. Don't attempt to fixup values.
// allowEmptyString: When the value is a string (as opposed to string[]),
// is empty string an actual permitted value instead of
// a missing value?
auto getRawBuildSetting(Package pack, bool allowEmptyString) {
auto value = __traits(getMember, buildSettings, attributeName);
static if( is(typeof(value) == string[]) )
return value;
else static if( is(typeof(value) == string) )
{
auto ret = only(value);
// only() has a different return type from only(value), so we
// have to empty the range rather than just returning only().
if(value.empty && !allowEmptyString) {
ret.popFront();
assert(ret.empty);
}
return ret;
}
else static if( is(typeof(value) == enum) )
return only(value);
else static if( is(typeof(value) == BuildRequirements) )
return only(cast(BuildRequirement) cast(int) value.values);
else static if( is(typeof(value) == BuildOptions) )
return only(cast(BuildOption) cast(int) value.values);
else
static assert(false, "Type of BuildSettings."~attributeName~" is unsupported.");
}
// Adjust BuildSetting member attributeName as needed.
// Returns a range of strings.
auto getFixedBuildSetting(Package pack) {
// Is relative path(s) to a directory?
enum isRelativeDirectory =
attributeName == "importPaths" || attributeName == "stringImportPaths" ||
attributeName == "targetPath" || attributeName == "workingDirectory";
// Is relative path(s) to a file?
enum isRelativeFile =
attributeName == "sourceFiles" || attributeName == "linkerFiles" ||
attributeName == "importFiles" || attributeName == "stringImportFiles" ||
attributeName == "copyFiles" || attributeName == "mainSourceFile";
// For these, empty string means "main project directory", not "missing value"
enum allowEmptyString =
attributeName == "targetPath" || attributeName == "workingDirectory";
enum isEnumBitfield =
attributeName == "targetType" || attributeName == "requirements" ||
attributeName == "options";
auto values = getRawBuildSetting(pack, allowEmptyString);
string fixRelativePath(string importPath) { return buildNormalizedPath(pack.path.toString(), importPath); }
static string ensureTrailingSlash(string path) { return path.endsWith(dirSeparator) ? path : path ~ dirSeparator; }
static if(isRelativeDirectory) {
// Return full paths for the paths, making sure a
// directory separator is on the end of each path.
return values.map!(fixRelativePath).map!(ensureTrailingSlash);
}
else static if(isRelativeFile) {
// Return full paths.
return values.map!(fixRelativePath);
}
else static if(isEnumBitfield)
return bitFieldNames(values.front);
else
return values;
}
foreach(value; getFixedBuildSetting(m_rootPackage)) {
list ~= value;
}
return list;
}
// The "compiler" arg is for choosing which compiler the output should be formatted for,
// or null to imply "list" format.
private string[] listBuildSetting(BuildPlatform platform, string[string] configs,
ProjectDescription projectDescription, string requestedData, Compiler compiler, bool disableEscaping)
{
// Certain data cannot be formatter for a compiler
if (compiler)
{
switch (requestedData)
{
case "target-type":
case "target-path":
case "target-name":
case "working-directory":
case "string-import-files":
case "copy-files":
case "pre-generate-commands":
case "post-generate-commands":
case "pre-build-commands":
case "post-build-commands":
enforce(false, "--data="~requestedData~" can only be used with --data-list or --data-0.");
break;
case "requirements":
enforce(false, "--data=requirements can only be used with --data-list or --data-0. Use --data=options instead.");
break;
default: break;
}
}
import std.typetuple : TypeTuple;
auto args = TypeTuple!(platform, configs, projectDescription, compiler, disableEscaping);
switch (requestedData)
{
case "target-type": return listBuildSetting!"targetType"(args);
case "target-path": return listBuildSetting!"targetPath"(args);
case "target-name": return listBuildSetting!"targetName"(args);
case "working-directory": return listBuildSetting!"workingDirectory"(args);
case "main-source-file": return listBuildSetting!"mainSourceFile"(args);
case "dflags": return listBuildSetting!"dflags"(args);
case "lflags": return listBuildSetting!"lflags"(args);
case "libs": return listBuildSetting!"libs"(args);
case "linker-files": return listBuildSetting!"linkerFiles"(args);
case "source-files": return listBuildSetting!"sourceFiles"(args);
case "copy-files": return listBuildSetting!"copyFiles"(args);
case "versions": return listBuildSetting!"versions"(args);
case "debug-versions": return listBuildSetting!"debugVersions"(args);
case "import-paths": return listBuildSetting!"importPaths"(args);
case "string-import-paths": return listBuildSetting!"stringImportPaths"(args);
case "import-files": return listBuildSetting!"importFiles"(args);
case "string-import-files": return listBuildSetting!"stringImportFiles"(args);
case "pre-generate-commands": return listBuildSetting!"preGenerateCommands"(args);
case "post-generate-commands": return listBuildSetting!"postGenerateCommands"(args);
case "pre-build-commands": return listBuildSetting!"preBuildCommands"(args);
case "post-build-commands": return listBuildSetting!"postBuildCommands"(args);
case "requirements": return listBuildSetting!"requirements"(args);
case "options": return listBuildSetting!"options"(args);
default:
enforce(false, "--data="~requestedData~
" is not a valid option. See 'dub describe --help' for accepted --data= values.");
}
assert(0);
}
/// Outputs requested data for the project, optionally including its dependencies.
string[] listBuildSettings(GeneratorSettings settings, string[] requestedData, ListBuildSettingsFormat list_type)
{
import dub.compilers.utils : isLinkerFile;
auto projectDescription = describe(settings);
auto configs = getPackageConfigs(settings.platform, settings.config);
PackageDescription packageDescription;
foreach (pack; projectDescription.packages) {
if (pack.name == projectDescription.rootPackage)
packageDescription = pack;
}
// Copy linker files from sourceFiles to linkerFiles
auto target = projectDescription.lookupTarget(projectDescription.rootPackage);
foreach (file; target.buildSettings.sourceFiles.filter!(isLinkerFile))
target.buildSettings.addLinkerFiles(file);
// Remove linker files from sourceFiles
target.buildSettings.sourceFiles =
target.buildSettings.sourceFiles
.filter!(a => !isLinkerFile(a))
.array();
projectDescription.lookupTarget(projectDescription.rootPackage) = target;
Compiler compiler;
bool no_escape;
final switch (list_type) with (ListBuildSettingsFormat) {
case list: break;
case listNul: no_escape = true; break;
case commandLine: compiler = settings.compiler; break;
case commandLineNul: compiler = settings.compiler; no_escape = true; break;
}
auto result = requestedData
.map!(dataName => listBuildSetting(settings.platform, configs, projectDescription, dataName, compiler, no_escape));
final switch (list_type) with (ListBuildSettingsFormat) {
case list: return result.map!(l => l.join("\n")).array();
case listNul: return result.map!(l => l.join("\0")).array;
case commandLine: return result.map!(l => l.join(" ")).array;
case commandLineNul: return result.map!(l => l.join("\0")).array;