-
-
Notifications
You must be signed in to change notification settings - Fork 227
/
dub.d
2054 lines (1740 loc) · 72.9 KB
/
dub.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
/**
A package manager.
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.dub;
import dub.compilers.compiler;
import dub.dependency;
import dub.dependencyresolver;
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.packagesuppliers;
import dub.project;
import dub.generators.generator;
import dub.init;
import std.algorithm;
import std.array : array, replace;
import std.conv : to;
import std.exception : enforce;
import std.file;
import std.process : environment;
import std.range : assumeSorted, empty;
import std.string;
import std.encoding : sanitize;
// Set output path and options for coverage reports
version (DigitalMars) version (D_Coverage)
{
shared static this()
{
import core.runtime, std.file, std.path, std.stdio;
dmd_coverSetMerge(true);
auto path = buildPath(dirName(thisExePath()), "../cov");
if (!path.exists)
mkdir(path);
dmd_coverDestPath(path);
}
}
static this()
{
import dub.compilers.dmd : DMDCompiler;
import dub.compilers.gdc : GDCCompiler;
import dub.compilers.ldc : LDCCompiler;
registerCompiler(new DMDCompiler);
registerCompiler(new GDCCompiler);
registerCompiler(new LDCCompiler);
}
deprecated("use defaultRegistryURLs") enum defaultRegistryURL = defaultRegistryURLs[0];
/// The URL to the official package registry and it's default fallback registries.
static immutable string[] defaultRegistryURLs = [
"https://code.dlang.org/",
"https://codemirror.dlang.org/",
"https://dub.bytecraft.nl/",
"https://code-mirror.dlang.io/",
];
/** Returns a default list of package suppliers.
This will contain a single package supplier that points to the official
package registry.
See_Also: `defaultRegistryURLs`
*/
PackageSupplier[] defaultPackageSuppliers()
{
logDiagnostic("Using dub registry url '%s'", defaultRegistryURLs[0]);
return [new FallbackPackageSupplier(defaultRegistryURLs.map!getRegistryPackageSupplier.array)];
}
/** Returns a registry package supplier according to protocol.
Allowed protocols are dub+http(s):// and maven+http(s)://.
*/
PackageSupplier getRegistryPackageSupplier(string url)
{
switch (url.startsWith("dub+", "mvn+", "file://"))
{
case 1:
return new RegistryPackageSupplier(URL(url[4..$]));
case 2:
return new MavenRegistryPackageSupplier(URL(url[4..$]));
case 3:
return new FileSystemPackageSupplier(NativePath(url[7..$]));
default:
return new RegistryPackageSupplier(URL(url));
}
}
unittest
{
auto dubRegistryPackageSupplier = getRegistryPackageSupplier("dub+https://code.dlang.org");
assert(dubRegistryPackageSupplier.description.canFind(" https://code.dlang.org"));
dubRegistryPackageSupplier = getRegistryPackageSupplier("https://code.dlang.org");
assert(dubRegistryPackageSupplier.description.canFind(" https://code.dlang.org"));
auto mavenRegistryPackageSupplier = getRegistryPackageSupplier("mvn+http://localhost:8040/maven/libs-release/dubpackages");
assert(mavenRegistryPackageSupplier.description.canFind(" http://localhost:8040/maven/libs-release/dubpackages"));
auto fileSystemPackageSupplier = getRegistryPackageSupplier("file:///etc/dubpackages");
assert(fileSystemPackageSupplier.description.canFind(" " ~ NativePath("/etc/dubpackages").toNativeString));
}
/** Provides a high-level entry point for DUB's functionality.
This class provides means to load a certain project (a root package with
all of its dependencies) and to perform high-level operations as found in
the command line interface.
*/
class Dub {
private {
bool m_dryRun = false;
PackageManager m_packageManager;
PackageSupplier[] m_packageSuppliers;
NativePath m_rootPath;
SpecialDirs m_dirs;
DubConfig m_config;
NativePath m_projectPath;
Project m_project;
NativePath m_overrideSearchPath;
string m_defaultCompiler;
string m_defaultArchitecture;
bool m_defaultLowMemory;
string[string] m_defaultEnvironments;
string[string] m_defaultBuildEnvironments;
string[string] m_defaultRunEnvironments;
string[string] m_defaultPreGenerateEnvironments;
string[string] m_defaultPostGenerateEnvironments;
string[string] m_defaultPreBuildEnvironments;
string[string] m_defaultPostBuildEnvironments;
string[string] m_defaultPreRunEnvironments;
string[string] m_defaultPostRunEnvironments;
}
/** The default placement location of fetched packages.
This property can be altered, so that packages which are downloaded as part
of the normal upgrade process are stored in a certain location. This is
how the "--local" and "--system" command line switches operate.
*/
PlacementLocation defaultPlacementLocation = PlacementLocation.user;
/** Initializes the instance for use with a specific root package.
Note that a package still has to be loaded using one of the
`loadPackage` overloads.
Params:
root_path = Path to the root package
additional_package_suppliers = A list of package suppliers to try
before the suppliers found in the configurations files and the
`defaultPackageSuppliers`.
skip_registry = Can be used to skip using the configured package
suppliers, as well as the default suppliers.
*/
this(string root_path = ".", PackageSupplier[] additional_package_suppliers = null,
SkipPackageSuppliers skip_registry = SkipPackageSuppliers.none)
{
m_rootPath = NativePath(root_path);
if (!m_rootPath.absolute) m_rootPath = NativePath(getcwd()) ~ m_rootPath;
init(m_rootPath);
m_packageSuppliers = getPackageSuppliers(additional_package_suppliers, skip_registry);
m_packageManager = new PackageManager(m_rootPath, m_dirs.localRepository, m_dirs.systemSettings);
auto ccps = m_config.customCachePaths;
if (ccps.length)
m_packageManager.customCachePaths = ccps;
updatePackageSearchPath();
}
unittest
{
scope (exit) environment.remove("DUB_REGISTRY");
auto dub = new Dub(".", null, SkipPackageSuppliers.configured);
assert(dub.m_packageSuppliers.length == 0);
environment["DUB_REGISTRY"] = "http://example.com/";
dub = new Dub(".", null, SkipPackageSuppliers.configured);
assert(dub.m_packageSuppliers.length == 1);
environment["DUB_REGISTRY"] = "http://example.com/;http://foo.com/";
dub = new Dub(".", null, SkipPackageSuppliers.configured);
assert(dub.m_packageSuppliers.length == 2);
dub = new Dub(".", [new RegistryPackageSupplier(URL("http://bar.com/"))], SkipPackageSuppliers.configured);
assert(dub.m_packageSuppliers.length == 3);
}
/** Get the list of package suppliers.
Params:
additional_package_suppliers = A list of package suppliers to try
before the suppliers found in the configurations files and the
`defaultPackageSuppliers`.
skip_registry = Can be used to skip using the configured package
suppliers, as well as the default suppliers.
*/
public PackageSupplier[] getPackageSuppliers(PackageSupplier[] additional_package_suppliers, SkipPackageSuppliers skip_registry)
{
PackageSupplier[] ps = additional_package_suppliers;
if (skip_registry < SkipPackageSuppliers.all)
{
ps ~= environment.get("DUB_REGISTRY", null)
.splitter(";")
.map!(url => getRegistryPackageSupplier(url))
.array;
}
if (skip_registry < SkipPackageSuppliers.configured)
{
ps ~= m_config.registryURLs
.map!(url => getRegistryPackageSupplier(url))
.array;
}
if (skip_registry < SkipPackageSuppliers.standard)
ps ~= defaultPackageSuppliers();
return ps;
}
/// ditto
public PackageSupplier[] getPackageSuppliers(PackageSupplier[] additional_package_suppliers)
{
return getPackageSuppliers(additional_package_suppliers, m_config.skipRegistry);
}
unittest
{
scope (exit) environment.remove("DUB_REGISTRY");
auto dub = new Dub(".", null, SkipPackageSuppliers.none);
dub.m_config = new DubConfig(Json(["skipRegistry": Json("none")]), null);
assert(dub.getPackageSuppliers(null).length == 1);
dub.m_config = new DubConfig(Json(["skipRegistry": Json("configured")]), null);
assert(dub.getPackageSuppliers(null).length == 0);
dub.m_config = new DubConfig(Json(["skipRegistry": Json("standard")]), null);
assert(dub.getPackageSuppliers(null).length == 0);
environment["DUB_REGISTRY"] = "http://example.com/";
assert(dub.getPackageSuppliers(null).length == 1);
}
/** Initializes the instance with a single package search path, without
loading a package.
This constructor corresponds to the "--bare" option of the command line
interface. Use
*/
this(NativePath override_path)
{
init(NativePath());
m_overrideSearchPath = override_path;
m_packageManager = new PackageManager(override_path);
}
private void init(NativePath root_path)
{
import std.file : tempDir;
version(Windows) {
m_dirs.systemSettings = NativePath(environment.get("ProgramData")) ~ "dub/";
immutable appDataDir = environment.get("APPDATA");
m_dirs.userSettings = NativePath(appDataDir) ~ "dub/";
m_dirs.localRepository = NativePath(environment.get("LOCALAPPDATA", appDataDir)) ~ "dub";
} else version(Posix){
m_dirs.systemSettings = NativePath("/var/lib/dub/");
m_dirs.userSettings = NativePath(environment.get("HOME")) ~ ".dub/";
if (!m_dirs.userSettings.absolute)
m_dirs.userSettings = NativePath(getcwd()) ~ m_dirs.userSettings;
m_dirs.localRepository = m_dirs.userSettings;
}
m_dirs.temp = NativePath(tempDir);
m_config = new DubConfig(jsonFromFile(m_dirs.systemSettings ~ "settings.json", true), m_config);
auto dubFolderPath = NativePath(thisExePath).parentPath;
m_config = new DubConfig(jsonFromFile(dubFolderPath ~ "../etc/dub/settings.json", true), m_config);
version (Posix) {
if (dubFolderPath.absolute && dubFolderPath.startsWith(NativePath("usr"))) {
m_config = new DubConfig(jsonFromFile(NativePath("/etc/dub/settings.json"), true), m_config);
}
}
m_config = new DubConfig(jsonFromFile(m_dirs.userSettings ~ "settings.json", true), m_config);
if (!root_path.empty)
m_config = new DubConfig(jsonFromFile(root_path ~ "dub.settings.json", true), m_config);
determineDefaultCompiler();
m_defaultArchitecture = m_config.defaultArchitecture;
m_defaultLowMemory = m_config.defaultLowMemory;
m_defaultEnvironments = m_config.defaultEnvironments;
m_defaultBuildEnvironments = m_config.defaultBuildEnvironments;
m_defaultRunEnvironments = m_config.defaultRunEnvironments;
m_defaultPreGenerateEnvironments = m_config.defaultPreGenerateEnvironments;
m_defaultPostGenerateEnvironments = m_config.defaultPostGenerateEnvironments;
m_defaultPreBuildEnvironments = m_config.defaultPreBuildEnvironments;
m_defaultPostBuildEnvironments = m_config.defaultPostBuildEnvironments;
m_defaultPreRunEnvironments = m_config.defaultPreRunEnvironments;
m_defaultPostRunEnvironments = m_config.defaultPostRunEnvironments;
}
@property void dryRun(bool v) { m_dryRun = v; }
/** Returns the root path (usually the current working directory).
*/
@property NativePath rootPath() const { return m_rootPath; }
/// ditto
@property void rootPath(NativePath root_path)
{
m_rootPath = root_path;
if (!m_rootPath.absolute) m_rootPath = NativePath(getcwd()) ~ m_rootPath;
}
/// Returns the name listed in the dub.json of the current
/// application.
@property string projectName() const { return m_project.name; }
@property NativePath projectPath() const { return m_projectPath; }
@property string[] configurations() const { return m_project.configurations; }
@property inout(PackageManager) packageManager() inout { return m_packageManager; }
@property inout(Project) project() inout { return m_project; }
/** Returns the default compiler binary to use for building D code.
If set, the "defaultCompiler" field of the DUB user or system
configuration file will be used. Otherwise the PATH environment variable
will be searched for files named "dmd", "gdc", "gdmd", "ldc2", "ldmd2"
(in that order, taking into account operating system specific file
extensions) and the first match is returned. If no match is found, "dmd"
will be used.
*/
@property string defaultCompiler() const { return m_defaultCompiler; }
/** Returns the default architecture to use for building D code.
If set, the "defaultArchitecture" field of the DUB user or system
configuration file will be used. Otherwise null will be returned.
*/
@property string defaultArchitecture() const { return m_defaultArchitecture; }
/** Returns the default low memory option to use for building D code.
If set, the "defaultLowMemory" field of the DUB user or system
configuration file will be used. Otherwise false will be returned.
*/
@property bool defaultLowMemory() const { return m_defaultLowMemory; }
@property const(string[string]) defaultEnvironments() const { return m_defaultEnvironments; }
@property const(string[string]) defaultBuildEnvironments() const { return m_defaultBuildEnvironments; }
@property const(string[string]) defaultRunEnvironments() const { return m_defaultRunEnvironments; }
@property const(string[string]) defaultPreGenerateEnvironments() const { return m_defaultPreGenerateEnvironments; }
@property const(string[string]) defaultPostGenerateEnvironments() const { return m_defaultPostGenerateEnvironments; }
@property const(string[string]) defaultPreBuildEnvironments() const { return m_defaultPreBuildEnvironments; }
@property const(string[string]) defaultPostBuildEnvironments() const { return m_defaultPostBuildEnvironments; }
@property const(string[string]) defaultPreRunEnvironments() const { return m_defaultPreRunEnvironments; }
@property const(string[string]) defaultPostRunEnvironments() const { return m_defaultPostRunEnvironments; }
/** Loads the package that resides within the configured `rootPath`.
*/
void loadPackage()
{
loadPackage(m_rootPath);
}
/// Loads the package from the specified path as the main project package.
void loadPackage(NativePath path)
{
m_projectPath = path;
updatePackageSearchPath();
m_project = new Project(m_packageManager, m_projectPath);
}
/// Loads a specific package as the main project package (can be a sub package)
void loadPackage(Package pack)
{
m_projectPath = pack.path;
updatePackageSearchPath();
m_project = new Project(m_packageManager, pack);
}
/** Loads a single file package.
Single-file packages are D files that contain a package receipe comment
at their top. A recipe comment must be a nested `/+ ... +/` style
comment, containing the virtual recipe file name and a colon, followed by the
recipe contents (what would normally be in dub.sdl/dub.json).
Example:
---
/+ dub.sdl:
name "test"
dependency "vibe-d" version="~>0.7.29"
+/
import vibe.http.server;
void main()
{
auto settings = new HTTPServerSettings;
settings.port = 8080;
listenHTTP(settings, &hello);
}
void hello(HTTPServerRequest req, HTTPServerResponse res)
{
res.writeBody("Hello, World!");
}
---
The script above can be invoked with "dub --single test.d".
*/
void loadSingleFilePackage(NativePath path)
{
import dub.recipe.io : parsePackageRecipe;
import std.file : mkdirRecurse, readText;
import std.path : baseName, stripExtension;
path = makeAbsolute(path);
string file_content = readText(path.toNativeString());
if (file_content.startsWith("#!")) {
auto idx = file_content.indexOf('\n');
enforce(idx > 0, "The source fine doesn't contain anything but a shebang line.");
file_content = file_content[idx+1 .. $];
}
file_content = file_content.strip();
string recipe_content;
if (file_content.startsWith("/+")) {
file_content = file_content[2 .. $];
auto idx = file_content.indexOf("+/");
enforce(idx >= 0, "Missing \"+/\" to close comment.");
recipe_content = file_content[0 .. idx].strip();
} else throw new Exception("The source file must start with a recipe comment.");
auto nidx = recipe_content.indexOf('\n');
auto idx = recipe_content.indexOf(':');
enforce(idx > 0 && (nidx < 0 || nidx > idx),
"The first line of the recipe comment must list the recipe file name followed by a colon (e.g. \"/+ dub.sdl:\").");
auto recipe_filename = recipe_content[0 .. idx];
recipe_content = recipe_content[idx+1 .. $];
auto recipe_default_package_name = path.toString.baseName.stripExtension.strip;
auto recipe = parsePackageRecipe(recipe_content, recipe_filename, null, recipe_default_package_name);
import dub.internal.vibecompat.core.log; logInfo("parsePackageRecipe %s", recipe_filename);
enforce(recipe.buildSettings.sourceFiles.length == 0, "Single-file packages are not allowed to specify source files.");
enforce(recipe.buildSettings.sourcePaths.length == 0, "Single-file packages are not allowed to specify source paths.");
enforce(recipe.buildSettings.importPaths.length == 0, "Single-file packages are not allowed to specify import paths.");
recipe.buildSettings.sourceFiles[""] = [path.toNativeString()];
recipe.buildSettings.sourcePaths[""] = [];
recipe.buildSettings.importPaths[""] = [];
recipe.buildSettings.mainSourceFile = path.toNativeString();
if (recipe.buildSettings.targetType == TargetType.autodetect)
recipe.buildSettings.targetType = TargetType.executable;
auto pack = new Package(recipe, path.parentPath, null, "~master");
loadPackage(pack);
}
/// ditto
void loadSingleFilePackage(string path)
{
loadSingleFilePackage(NativePath(path));
}
deprecated("Instantiate a Dub instance with the single-argument constructor: `new Dub(path)`")
void overrideSearchPath(NativePath path)
{
if (!path.absolute) path = NativePath(getcwd()) ~ path;
m_overrideSearchPath = path;
updatePackageSearchPath();
}
/** Gets the default configuration for a particular build platform.
This forwards to `Project.getDefaultConfiguration` and requires a
project to be loaded.
*/
string getDefaultConfiguration(BuildPlatform platform, bool allow_non_library_configs = true) const { return m_project.getDefaultConfiguration(platform, allow_non_library_configs); }
/** Attempts to upgrade the dependency selection of the loaded project.
Params:
options = Flags that control how the upgrade is carried out
packages_to_upgrade = Optional list of packages. If this list
contains one or more packages, only those packages will
be upgraded. Otherwise, all packages will be upgraded at
once.
*/
void upgrade(UpgradeOptions options, string[] packages_to_upgrade = null)
{
// clear non-existent version selections
if (!(options & UpgradeOptions.upgrade)) {
next_pack:
foreach (p; m_project.selections.selectedPackages) {
auto dep = m_project.selections.getSelectedVersion(p);
if (!dep.path.empty) {
auto path = dep.path;
if (!path.absolute) path = this.rootPath ~ path;
try if (m_packageManager.getOrLoadPackage(path)) continue;
catch (Exception e) { logDebug("Failed to load path based selection: %s", e.toString().sanitize); }
} else if (!dep.repository.empty) {
if (m_packageManager.loadSCMPackage(getBasePackageName(p), dep))
continue;
} else {
if (m_packageManager.getPackage(p, dep.version_)) continue;
foreach (ps; m_packageSuppliers) {
try {
auto versions = ps.getVersions(p);
if (versions.canFind!(v => dep.matches(v)))
continue next_pack;
} catch (Exception e) {
logWarn("Error querying versions for %s, %s: %s", p, ps.description, e.msg);
logDebug("Full error: %s", e.toString().sanitize());
}
}
}
logWarn("Selected package %s %s doesn't exist. Using latest matching version instead.", p, dep);
m_project.selections.deselectVersion(p);
}
}
Dependency[string] versions;
auto resolver = new DependencyVersionResolver(this, options);
foreach (p; packages_to_upgrade)
resolver.addPackageToUpgrade(p);
versions = resolver.resolve(m_project.rootPackage, m_project.selections);
if (options & UpgradeOptions.dryRun) {
bool any = false;
string rootbasename = getBasePackageName(m_project.rootPackage.name);
foreach (p, ver; versions) {
if (!ver.path.empty || !ver.repository.empty) continue;
auto basename = getBasePackageName(p);
if (basename == rootbasename) continue;
if (!m_project.selections.hasSelectedVersion(basename)) {
logInfo("Package %s would be selected with version %s.",
basename, ver);
any = true;
continue;
}
auto sver = m_project.selections.getSelectedVersion(basename);
if (!sver.path.empty || !sver.repository.empty) continue;
if (ver.version_ <= sver.version_) continue;
logInfo("Package %s would be upgraded from %s to %s.",
basename, sver, ver);
any = true;
}
if (any) logInfo("Use \"dub upgrade\" to perform those changes.");
return;
}
foreach (p; versions.byKey) {
auto ver = versions[p]; // Workaround for DMD 2.070.0 AA issue (crashes in aaApply2 if iterating by key+value)
assert(!p.canFind(":"), "Resolved packages contain a sub package!?: "~p);
Package pack;
if (!ver.path.empty) {
try pack = m_packageManager.getOrLoadPackage(ver.path);
catch (Exception e) {
logDebug("Failed to load path based selection: %s", e.toString().sanitize);
continue;
}
} else if (!ver.repository.empty) {
pack = m_packageManager.loadSCMPackage(p, ver);
} else {
pack = m_packageManager.getBestPackage(p, ver);
if (pack && m_packageManager.isManagedPackage(pack)
&& ver.version_.isBranch && (options & UpgradeOptions.upgrade) != 0)
{
// TODO: only re-install if there is actually a new commit available
logInfo("Re-installing branch based dependency %s %s", p, ver.toString());
m_packageManager.remove(pack);
pack = null;
}
}
FetchOptions fetchOpts;
fetchOpts |= (options & UpgradeOptions.preRelease) != 0 ? FetchOptions.usePrerelease : FetchOptions.none;
if (!pack) fetch(p, ver, defaultPlacementLocation, fetchOpts, "getting selected version");
if ((options & UpgradeOptions.select) && p != m_project.rootPackage.name) {
if (!ver.repository.empty) {
m_project.selections.selectVersionWithRepository(p, ver.repository, ver.versionSpec);
} else if (ver.path.empty) {
m_project.selections.selectVersion(p, ver.version_);
} else {
NativePath relpath = ver.path;
if (relpath.absolute) relpath = relpath.relativeTo(m_project.rootPackage.path);
m_project.selections.selectVersion(p, relpath);
}
}
}
string[] missingDependenciesBeforeReinit = m_project.missingDependencies;
m_project.reinit();
if (!m_project.hasAllDependencies) {
auto resolvedDependencies = setDifference(
assumeSorted(missingDependenciesBeforeReinit),
assumeSorted(m_project.missingDependencies)
);
if (!resolvedDependencies.empty)
upgrade(options, m_project.missingDependencies);
}
if ((options & UpgradeOptions.select) && !(options & (UpgradeOptions.noSaveSelections | UpgradeOptions.dryRun)))
m_project.saveSelections();
}
/** Generate project files for a specified generator.
Any existing project files will be overridden.
*/
void generateProject(string ide, GeneratorSettings settings)
{
auto generator = createProjectGenerator(ide, m_project);
if (m_dryRun) return; // TODO: pass m_dryRun to the generator
generator.generate(settings);
}
/** Executes tests on the current project.
Throws an exception, if unittests failed.
*/
void testProject(GeneratorSettings settings, string config, NativePath custom_main_file)
{
if (!custom_main_file.empty && !custom_main_file.absolute) custom_main_file = getWorkingDirectory() ~ custom_main_file;
if (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) config = m_project.getDefaultConfiguration(settings.platform, false);
// else look for a "unittest" configuration
if (!config.length && m_project.rootPackage.configurations.canFind("unittest")) config = "unittest";
// if not found, fall back to the first "library" configuration
if (!config.length) config = m_project.getDefaultConfiguration(settings.platform, false);
// if still nothing found, use the first executable configuration
if (!config.length) config = m_project.getDefaultConfiguration(settings.platform, true);
}
auto generator = createProjectGenerator("build", m_project);
auto test_config = format("%s-test-%s", m_project.rootPackage.name.replace(".", "-").replace(":", "-"), config);
BuildSettings lbuildsettings = settings.buildSettings;
m_project.addBuildSettings(lbuildsettings, settings, config, null, true);
if (lbuildsettings.targetType == TargetType.none) {
logInfo(`Configuration '%s' has target type "none". Skipping test.`, config);
return;
}
if (lbuildsettings.targetType == TargetType.executable && config == "unittest") {
logInfo("Running custom 'unittest' configuration.", config);
if (!custom_main_file.empty) logWarn("Ignoring custom main file.");
settings.config = config;
} else if (lbuildsettings.sourceFiles.empty) {
logInfo(`No source files found in configuration '%s'. Falling back to "dub -b unittest".`, config);
if (!custom_main_file.empty) logWarn("Ignoring custom main file.");
settings.config = m_project.getDefaultConfiguration(settings.platform);
} else {
import std.algorithm : remove;
logInfo(`Generating test runner configuration '%s' for '%s' (%s).`, test_config, config, lbuildsettings.targetType);
BuildSettingsTemplate tcinfo = m_project.rootPackage.recipe.getConfiguration(config).buildSettings;
tcinfo.targetType = TargetType.executable;
tcinfo.targetName = test_config;
auto mainfil = tcinfo.mainSourceFile;
if (!mainfil.length) mainfil = m_project.rootPackage.recipe.buildSettings.mainSourceFile;
string custommodname;
if (!custom_main_file.empty) {
import std.path;
tcinfo.sourceFiles[""] ~= custom_main_file.relativeTo(m_project.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(m_project.rootPackage.path);
if (!settings.single && NativePath(file).relativeTo(m_project.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), m_project.rootPackage.path);
}
}
NativePath mainfile;
if (settings.tempBuild)
mainfile = getTempFile("dub_test_root", ".d");
else {
import dub.generators.build : computeBuildName;
mainfile = m_project.rootPackage.path ~ format(".dub/code/%s_dub_test_root.d", computeBuildName(test_config, settings, import_modules));
}
mkdirRecurse(mainfile.parentPath.toNativeString());
bool regenerateMainFile = settings.force || !existsFile(mainfile);
auto escapedMainFile = mainfile.toNativeString().replace("$", "$$");
// generate main file
tcinfo.sourceFiles[""] ~= escapedMainFile;
tcinfo.mainSourceFile = escapedMainFile;
if (!m_dryRun && regenerateMainFile) {
auto fil = openFile(mainfile, FileMode.createTrunc);
scope(exit) fil.close();
fil.write("module dub_test_root;\n");
fil.write("import std.typetuple;\n");
foreach (mod; import_modules) fil.write(format("static import %s;\n", mod));
fil.write("alias allModules = TypeTuple!(");
foreach (i, mod; import_modules) {
if (i > 0) fil.write(", ");
fil.write(mod);
}
fil.write(");\n");
if (custommodname.length) {
fil.write(format("import %s;\n", custommodname));
} else {
fil.write(q{
import std.stdio;
import core.runtime;
void main() { writeln("All unit tests have been run successfully."); }
shared static this() {
version (Have_tested) {
import tested;
import core.runtime;
import std.exception;
Runtime.moduleUnitTester = () => true;
enforce(runUnitTests!allModules(new ConsoleTestResultWriter), "Unit tests failed.");
}
}
});
}
}
m_project.rootPackage.recipe.configurations ~= ConfigurationInfo(test_config, tcinfo);
m_project = new Project(m_packageManager, m_project.rootPackage);
settings.config = test_config;
}
generator.generate(settings);
}
/** Executes D-Scanner tests on the current project. **/
void lintProject(string[] args)
{
import std.path : buildPath, buildNormalizedPath;
if (m_dryRun) return;
auto tool = "dscanner";
auto tool_pack = m_packageManager.getBestPackage(tool, ">=0.0.0");
if (!tool_pack) tool_pack = m_packageManager.getBestPackage(tool, "~master");
if (!tool_pack) {
logInfo("%s is not present, getting and storing it user wide", tool);
tool_pack = fetch(tool, Dependency(">=0.0.0"), defaultPlacementLocation, FetchOptions.none);
}
auto dscanner_dub = new Dub(null, m_packageSuppliers);
dscanner_dub.loadPackage(tool_pack.path);
dscanner_dub.upgrade(UpgradeOptions.select);
auto compiler_binary = this.defaultCompiler;
GeneratorSettings settings;
settings.config = "application";
settings.compiler = getCompiler(compiler_binary);
settings.platform = settings.compiler.determinePlatform(settings.buildSettings, compiler_binary, m_defaultArchitecture);
settings.buildType = "debug";
if (m_defaultLowMemory) settings.buildSettings.options |= BuildOption.lowmem;
if (m_defaultEnvironments) settings.buildSettings.addEnvironments(m_defaultEnvironments);
if (m_defaultBuildEnvironments) settings.buildSettings.addBuildEnvironments(m_defaultBuildEnvironments);
if (m_defaultRunEnvironments) settings.buildSettings.addRunEnvironments(m_defaultRunEnvironments);
if (m_defaultPreGenerateEnvironments) settings.buildSettings.addPreGenerateEnvironments(m_defaultPreGenerateEnvironments);
if (m_defaultPostGenerateEnvironments) settings.buildSettings.addPostGenerateEnvironments(m_defaultPostGenerateEnvironments);
if (m_defaultPreBuildEnvironments) settings.buildSettings.addPreBuildEnvironments(m_defaultPreBuildEnvironments);
if (m_defaultPostBuildEnvironments) settings.buildSettings.addPostBuildEnvironments(m_defaultPostBuildEnvironments);
if (m_defaultPreRunEnvironments) settings.buildSettings.addPreRunEnvironments(m_defaultPreRunEnvironments);
if (m_defaultPostRunEnvironments) settings.buildSettings.addPostRunEnvironments(m_defaultPostRunEnvironments);
settings.run = true;
foreach (dependencyPackage; m_project.dependencies)
{
auto cfgs = m_project.getPackageConfigs(settings.platform, null, true);
auto buildSettings = dependencyPackage.getBuildSettings(settings.platform, cfgs[dependencyPackage.name]);
foreach (importPath; buildSettings.importPaths) {
settings.runArgs ~= ["-I", buildNormalizedPath(dependencyPackage.path.toNativeString(), importPath.idup)];
}
}
string configFilePath = buildPath(m_project.rootPackage.path.toNativeString(), "dscanner.ini");
if (!args.canFind("--config") && exists(configFilePath)) {
settings.runArgs ~= ["--config", configFilePath];
}
settings.runArgs ~= args ~ [m_project.rootPackage.path.toNativeString()];
dscanner_dub.generateProject("build", settings);
}
/** Prints the specified build settings necessary for building the root package.
*/
void listProjectData(GeneratorSettings settings, string[] requestedData, ListBuildSettingsFormat list_type)
{
import std.stdio;
import std.ascii : newline;
// Split comma-separated lists
string[] requestedDataSplit =
requestedData
.map!(a => a.splitter(",").map!strip)
.joiner()
.array();
auto data = m_project.listBuildSettings(settings, requestedDataSplit, list_type);
string delimiter;
final switch (list_type) with (ListBuildSettingsFormat) {
case list: delimiter = newline ~ newline; break;
case listNul: delimiter = "\0\0"; break;
case commandLine: delimiter = " "; break;
case commandLineNul: delimiter = "\0\0"; break;
}
write(data.joiner(delimiter));
if (delimiter != "\0\0") writeln();
}
/// Cleans intermediate/cache files of the given package
void cleanPackage(NativePath path)
{
logInfo("Cleaning package at %s...", path.toNativeString());
enforce(!Package.findPackageFile(path).empty, "No package found.", path.toNativeString());
// TODO: clear target files and copy files
if (existsFile(path ~ ".dub/build")) rmdirRecurse((path ~ ".dub/build").toNativeString());
if (existsFile(path ~ ".dub/metadata_cache.json")) std.file.remove((path ~ ".dub/metadata_cache.json").toNativeString());
auto p = Package.load(path);
if (p.getBuildSettings().targetType == TargetType.none) {
foreach (sp; p.subPackages.filter!(sp => !sp.path.empty)) {
cleanPackage(path ~ sp.path);
}
}
}
/// Fetches the package matching the dependency and places it in the specified location.
Package fetch(string packageId, const Dependency dep, PlacementLocation location, FetchOptions options, string reason = "")
{
auto basePackageName = getBasePackageName(packageId);
Json pinfo;
PackageSupplier supplier;
foreach(ps; m_packageSuppliers){
try {
pinfo = ps.fetchPackageRecipe(basePackageName, dep, (options & FetchOptions.usePrerelease) != 0);
if (pinfo.type == Json.Type.null_)
continue;
supplier = ps;
break;
} catch(Exception e) {
logWarn("Package %s not found for %s: %s", packageId, ps.description, e.msg);
logDebug("Full error: %s", e.toString().sanitize());
}
}
enforce(pinfo.type != Json.Type.undefined, "No package "~packageId~" was found matching the dependency "~dep.toString());
string ver = pinfo["version"].get!string;
NativePath placement;
final switch (location) {
case PlacementLocation.local: placement = m_rootPath ~ ".dub/packages/"; break;
case PlacementLocation.user: placement = m_dirs.localRepository ~ "packages/"; break;
case PlacementLocation.system: placement = m_dirs.systemSettings ~ "packages/"; break;
}
// always upgrade branch based versions - TODO: actually check if there is a new commit available
Package existing;
try existing = m_packageManager.getPackage(packageId, ver, placement);
catch (Exception e) {
logWarn("Failed to load existing package %s: %s", ver, e.msg);
logDiagnostic("Full error: %s", e.toString().sanitize);
}
if (options & FetchOptions.printOnly) {
if (existing && existing.version_ != Version(ver))
logInfo("A new version for %s is available (%s -> %s). Run \"dub upgrade %s\" to switch.",
packageId, existing.version_, ver, packageId);
return null;
}
if (existing) {
if (!ver.startsWith("~") || !(options & FetchOptions.forceBranchUpgrade) || location == PlacementLocation.local) {
// TODO: support git working trees by performing a "git pull" instead of this
logDiagnostic("Package %s %s (%s) is already present with the latest version, skipping upgrade.",
packageId, ver, placement);
return existing;
} else {
logInfo("Removing %s %s to prepare replacement with a new version.", packageId, ver);
if (!m_dryRun) m_packageManager.remove(existing);
}
}
if (reason.length) logInfo("Fetching %s %s (%s)...", packageId, ver, reason);
else logInfo("Fetching %s %s...", packageId, ver);
if (m_dryRun) return null;
logDebug("Acquiring package zip file");
auto clean_package_version = ver[ver.startsWith("~") ? 1 : 0 .. $];
clean_package_version = clean_package_version.replace("+", "_"); // + has special meaning for Optlink
if (!placement.existsFile())
mkdirRecurse(placement.toNativeString());
NativePath dstpath = placement ~ (basePackageName ~ "-" ~ clean_package_version);
if (!dstpath.existsFile())
mkdirRecurse(dstpath.toNativeString());
// Support libraries typically used with git submodules like ae.
// Such libraries need to have ".." as import path but this can create
// import path leakage.
dstpath = dstpath ~ basePackageName;
import std.datetime : seconds;
auto lock = lockFile(dstpath.toNativeString() ~ ".lock", 30.seconds); // possibly wait for other dub instance
if (dstpath.existsFile())
{
m_packageManager.refresh(false);
return m_packageManager.getPackage(packageId, ver, dstpath);
}
// repeat download on corrupted zips, see #1336
foreach_reverse (i; 0..3)
{
import std.zip : ZipException;
auto path = getTempFile(basePackageName, ".zip");
supplier.fetchPackage(path, basePackageName, dep, (options & FetchOptions.usePrerelease) != 0); // Q: continue on fail?
scope(exit) std.file.remove(path.toNativeString());
logDiagnostic("Placing to %s...", placement.toNativeString());
try {
m_packageManager.storeFetchedPackage(path, pinfo, dstpath);
return m_packageManager.getPackage(packageId, ver, dstpath);
} catch (ZipException e) {
logInfo("Failed to extract zip archive for %s %s...", packageId, ver);
// rethrow the exception at the end of the loop
if (i == 0)
throw e;
}
}
assert(0, "Should throw a ZipException instead.");
}