Newer
Older
dub_jkp / source / dub / generators / generator.d
@Bastiaan Veelo Bastiaan Veelo on 24 Jan 2021 31 KB Selectively import symbols from std.array.
  1. /**
  2. Generator for project files
  3.  
  4. Copyright: © 2012-2013 Matthias Dondorff, © 2013-2016 Sönke Ludwig
  5. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
  6. Authors: Matthias Dondorff
  7. */
  8. module dub.generators.generator;
  9.  
  10. import dub.compilers.compiler;
  11. import dub.generators.cmake;
  12. import dub.generators.build;
  13. import dub.generators.sublimetext;
  14. import dub.generators.visuald;
  15. import dub.internal.vibecompat.core.file;
  16. import dub.internal.vibecompat.core.log;
  17. import dub.internal.vibecompat.inet.path;
  18. import dub.package_;
  19. import dub.packagemanager;
  20. import dub.project;
  21.  
  22. import std.algorithm : map, filter, canFind, balancedParens;
  23. import std.array : array, appender, join;
  24. import std.exception;
  25. import std.file;
  26. import std.string;
  27.  
  28.  
  29. /**
  30. Common interface for project generators/builders.
  31. */
  32. class ProjectGenerator
  33. {
  34. /** Information about a single binary target.
  35.  
  36. A binary target can either be an executable or a static/dynamic library.
  37. It consists of one or more packages.
  38. */
  39. struct TargetInfo {
  40. /// The root package of this target
  41. Package pack;
  42.  
  43. /// All packages compiled into this target
  44. Package[] packages;
  45.  
  46. /// The configuration used for building the root package
  47. string config;
  48.  
  49. /** Build settings used to build the target.
  50.  
  51. The build settings include all sources of all contained packages.
  52.  
  53. Depending on the specific generator implementation, it may be
  54. necessary to add any static or dynamic libraries generated for
  55. child targets ($(D linkDependencies)).
  56. */
  57. BuildSettings buildSettings;
  58.  
  59. /** List of all dependencies.
  60.  
  61. This list includes dependencies that are not the root of a binary
  62. target.
  63. */
  64. string[] dependencies;
  65.  
  66. /** List of all binary dependencies.
  67.  
  68. This list includes all dependencies that are the root of a binary
  69. target.
  70. */
  71. string[] linkDependencies;
  72. }
  73.  
  74. protected {
  75. Project m_project;
  76. NativePath m_tempTargetExecutablePath;
  77. }
  78.  
  79. this(Project project)
  80. {
  81. m_project = project;
  82. }
  83.  
  84. /** Performs the full generator process.
  85. */
  86. final void generate(GeneratorSettings settings)
  87. {
  88. import dub.compilers.utils : enforceBuildRequirements;
  89.  
  90. if (!settings.config.length) settings.config = m_project.getDefaultConfiguration(settings.platform);
  91.  
  92. string[string] configs = m_project.getPackageConfigs(settings.platform, settings.config);
  93. TargetInfo[string] targets;
  94.  
  95. foreach (pack; m_project.getTopologicalPackageList(true, null, configs)) {
  96. BuildSettings buildSettings;
  97. auto config = configs[pack.name];
  98. buildSettings.processVars(m_project, pack, pack.getBuildSettings(settings.platform, config), settings, true);
  99.  
  100. prepareGeneration(pack, m_project, settings, buildSettings);
  101.  
  102. // Regenerate buildSettings.sourceFiles
  103. if (buildSettings.preGenerateCommands.length) {
  104. buildSettings = BuildSettings.init;
  105. buildSettings.processVars(m_project, pack, pack.getBuildSettings(settings.platform, config), settings, true);
  106. }
  107. targets[pack.name] = TargetInfo(pack, [pack], config, buildSettings);
  108. }
  109.  
  110. configurePackages(m_project.rootPackage, targets, settings);
  111.  
  112. addBuildTypeSettings(targets, settings);
  113. foreach (ref t; targets.byValue) enforceBuildRequirements(t.buildSettings);
  114.  
  115. generateTargets(settings, targets);
  116.  
  117. foreach (pack; m_project.getTopologicalPackageList(true, null, configs)) {
  118. BuildSettings buildsettings;
  119. buildsettings.processVars(m_project, pack, pack.getBuildSettings(settings.platform, configs[pack.name]), settings, true);
  120. bool generate_binary = !(buildsettings.options & BuildOption.syntaxOnly);
  121. auto bs = &targets[m_project.rootPackage.name].buildSettings;
  122. auto targetPath = (m_tempTargetExecutablePath.empty) ? NativePath(bs.targetPath) : m_tempTargetExecutablePath;
  123. finalizeGeneration(pack, m_project, settings, buildsettings, targetPath, generate_binary);
  124. }
  125.  
  126. performPostGenerateActions(settings, targets);
  127. }
  128.  
  129. /** Overridden in derived classes to implement the actual generator functionality.
  130.  
  131. The function should go through all targets recursively. The first target
  132. (which is guaranteed to be there) is
  133. $(D targets[m_project.rootPackage.name]). The recursive descent is then
  134. done using the $(D TargetInfo.linkDependencies) list.
  135.  
  136. This method is also potentially responsible for running the pre and post
  137. build commands, while pre and post generate commands are already taken
  138. care of by the $(D generate) method.
  139.  
  140. Params:
  141. settings = The generator settings used for this run
  142. targets = A map from package name to TargetInfo that contains all
  143. binary targets to be built.
  144. */
  145. protected abstract void generateTargets(GeneratorSettings settings, in TargetInfo[string] targets);
  146.  
  147. /** Overridable method to be invoked after the generator process has finished.
  148.  
  149. An examples of functionality placed here is to run the application that
  150. has just been built.
  151. */
  152. protected void performPostGenerateActions(GeneratorSettings settings, in TargetInfo[string] targets) {}
  153.  
  154. /** Configure `rootPackage` and all of it's dependencies.
  155.  
  156. 1. Merge versions, debugVersions, and inheritable build
  157. settings from dependents to their dependencies.
  158.  
  159. 2. Define version identifiers Have_dependency_xyz for all
  160. direct dependencies of all packages.
  161.  
  162. 3. Merge versions, debugVersions, and inheritable build settings from
  163. dependencies to their dependents, so that importer and importee are ABI
  164. compatible. This also transports all Have_dependency_xyz version
  165. identifiers to `rootPackage`.
  166.  
  167. 4. Filter unused versions and debugVersions from all targets. The
  168. filters have previously been upwards inherited (3.) so that versions
  169. used in a dependency are also applied to all dependents.
  170.  
  171. Note: The upwards inheritance is done at last so that siblings do not
  172. influence each other, also see https://github.com/dlang/dub/pull/1128.
  173.  
  174. Note: Targets without output are integrated into their
  175. dependents and removed from `targets`.
  176. */
  177. private void configurePackages(Package rootPackage, TargetInfo[string] targets, GeneratorSettings genSettings)
  178. {
  179. import std.algorithm : remove, sort;
  180. import std.range : repeat;
  181.  
  182. auto roottarget = &targets[rootPackage.name];
  183.  
  184. // 0. do shallow configuration (not including dependencies) of all packages
  185. TargetType determineTargetType(const ref TargetInfo ti)
  186. {
  187. TargetType tt = ti.buildSettings.targetType;
  188. if (ti.pack is rootPackage) {
  189. if (tt == TargetType.autodetect || tt == TargetType.library) tt = TargetType.staticLibrary;
  190. } else {
  191. if (tt == TargetType.autodetect || tt == TargetType.library) tt = genSettings.combined ? TargetType.sourceLibrary : TargetType.staticLibrary;
  192. else if (tt == TargetType.dynamicLibrary) {
  193. logWarn("Dynamic libraries are not yet supported as dependencies - building as static library.");
  194. tt = TargetType.staticLibrary;
  195. }
  196. }
  197. if (tt != TargetType.none && tt != TargetType.sourceLibrary && ti.buildSettings.sourceFiles.empty) {
  198. logWarn(`Configuration '%s' of package %s contains no source files. Please add {"targetType": "none"} to its package description to avoid building it.`,
  199. ti.config, ti.pack.name);
  200. tt = TargetType.none;
  201. }
  202. return tt;
  203. }
  204.  
  205. string[] mainSourceFiles;
  206. bool[string] hasOutput;
  207.  
  208. foreach (ref ti; targets.byValue)
  209. {
  210. auto bs = &ti.buildSettings;
  211. // determine the actual target type
  212. bs.targetType = determineTargetType(ti);
  213.  
  214. switch (bs.targetType)
  215. {
  216. case TargetType.none:
  217. // ignore any build settings for targetType none (only dependencies will be processed)
  218. *bs = BuildSettings.init;
  219. bs.targetType = TargetType.none;
  220. break;
  221.  
  222. case TargetType.executable:
  223. break;
  224.  
  225. case TargetType.dynamicLibrary:
  226. // set -fPIC for dynamic library builds
  227. ti.buildSettings.addOptions(BuildOption.pic);
  228. goto default;
  229.  
  230. default:
  231. // remove any mainSourceFile from non-executable builds
  232. if (bs.mainSourceFile.length) {
  233. bs.sourceFiles = bs.sourceFiles.remove!(f => f == bs.mainSourceFile);
  234. mainSourceFiles ~= bs.mainSourceFile;
  235. }
  236. break;
  237. }
  238. bool generatesBinary = bs.targetType != TargetType.sourceLibrary && bs.targetType != TargetType.none;
  239. hasOutput[ti.pack.name] = generatesBinary || ti.pack is rootPackage;
  240. }
  241.  
  242. // add main source files to root executable
  243. {
  244. auto bs = &roottarget.buildSettings;
  245. if (bs.targetType == TargetType.executable) bs.addSourceFiles(mainSourceFiles);
  246. }
  247.  
  248. if (genSettings.filterVersions)
  249. foreach (ref ti; targets.byValue)
  250. inferVersionFilters(ti);
  251.  
  252. // mark packages as visited (only used during upwards propagation)
  253. void[0][Package] visited;
  254.  
  255. // collect all dependencies
  256. void collectDependencies(Package pack, ref TargetInfo ti, TargetInfo[string] targets, size_t level = 0)
  257. {
  258. // use `visited` here as pkgs cannot depend on themselves
  259. if (pack in visited)
  260. return;
  261. // transitive dependencies must be visited multiple times, see #1350
  262. immutable transitive = !hasOutput[pack.name];
  263. if (!transitive)
  264. visited[pack] = typeof(visited[pack]).init;
  265.  
  266. auto bs = &ti.buildSettings;
  267. if (hasOutput[pack.name])
  268. logDebug("%sConfiguring target %s (%s %s %s)", ' '.repeat(2 * level), pack.name, bs.targetType, bs.targetPath, bs.targetName);
  269. else
  270. logDebug("%sConfiguring target without output %s", ' '.repeat(2 * level), pack.name);
  271.  
  272. // get specified dependencies, e.g. vibe-d ~0.8.1
  273. auto deps = pack.getDependencies(targets[pack.name].config);
  274. logDebug("deps: %s -> %(%s, %)", pack.name, deps.byKey);
  275. foreach (depname; deps.keys.sort())
  276. {
  277. auto depspec = deps[depname];
  278. // get selected package for that dependency, e.g. vibe-d 0.8.2-beta.2
  279. auto deppack = m_project.getDependency(depname, depspec.optional);
  280. if (deppack is null) continue; // optional and not selected
  281.  
  282. // if dependency has no output
  283. if (!hasOutput[depname]) {
  284. // add itself
  285. ti.packages ~= deppack;
  286. // and it's transitive dependencies to current target
  287. collectDependencies(deppack, ti, targets, level + 1);
  288. continue;
  289. }
  290. auto depti = &targets[depname];
  291. const depbs = &depti.buildSettings;
  292. if (depbs.targetType == TargetType.executable && ti.buildSettings.targetType != TargetType.none)
  293. continue;
  294.  
  295. // add to (link) dependencies
  296. ti.dependencies ~= depname;
  297. ti.linkDependencies ~= depname;
  298.  
  299. // recurse
  300. collectDependencies(deppack, *depti, targets, level + 1);
  301.  
  302. // also recursively add all link dependencies of static libraries
  303. // preserve topological sorting of dependencies for correct link order
  304. if (depbs.targetType == TargetType.staticLibrary)
  305. ti.linkDependencies = ti.linkDependencies.filter!(d => !depti.linkDependencies.canFind(d)).array ~ depti.linkDependencies;
  306. }
  307.  
  308. enforce(!(ti.buildSettings.targetType == TargetType.none && ti.dependencies.empty),
  309. "Package with target type \"none\" must have dependencies to build.");
  310. }
  311.  
  312. collectDependencies(rootPackage, *roottarget, targets);
  313. visited.clear();
  314.  
  315. // 1. downwards inherits versions, debugVersions, and inheritable build settings
  316. static void configureDependencies(const scope ref TargetInfo ti, TargetInfo[string] targets,
  317. BuildSettings[string] dependBS, size_t level = 0)
  318. {
  319.  
  320. static void applyForcedSettings(const scope ref BuildSettings forced, ref BuildSettings child) {
  321. child.addDFlags(forced.dflags);
  322. }
  323.  
  324. // do not use `visited` here as dependencies must inherit
  325. // configurations from *all* of their parents
  326. logDebug("%sConfigure dependencies of %s, deps:%(%s, %)", ' '.repeat(2 * level), ti.pack.name, ti.dependencies);
  327. foreach (depname; ti.dependencies)
  328. {
  329. BuildSettings forcedSettings;
  330. auto pti = &targets[depname];
  331. mergeFromDependent(ti.buildSettings, pti.buildSettings);
  332.  
  333. if (auto matchedSettings = depname in dependBS)
  334. forcedSettings = *matchedSettings;
  335. else if (auto matchedSettings = "*" in dependBS)
  336. forcedSettings = *matchedSettings;
  337.  
  338. applyForcedSettings(forcedSettings, pti.buildSettings);
  339. configureDependencies(*pti, targets, ["*" : forcedSettings], level + 1);
  340. }
  341. }
  342.  
  343. BuildSettings[string] dependencyBuildSettings;
  344. foreach (key, value; rootPackage.recipe.buildSettings.dependencyBuildSettings)
  345. {
  346. BuildSettings buildSettings;
  347. if (auto target = key in targets)
  348. {
  349. value.getPlatformSettings(buildSettings, genSettings.platform, target.pack.path);
  350. buildSettings.processVars(m_project, target.pack, buildSettings, genSettings, true);
  351. dependencyBuildSettings[key] = buildSettings;
  352. }
  353. }
  354. configureDependencies(*roottarget, targets, dependencyBuildSettings);
  355.  
  356. // 2. add Have_dependency_xyz for all direct dependencies of a target
  357. // (includes incorporated non-target dependencies and their dependencies)
  358. foreach (ref ti; targets.byValue)
  359. {
  360. import std.range : chain;
  361. import dub.internal.utils : stripDlangSpecialChars;
  362.  
  363. auto bs = &ti.buildSettings;
  364. auto pkgnames = ti.packages.map!(p => p.name).chain(ti.dependencies);
  365. bs.addVersions(pkgnames.map!(pn => "Have_" ~ stripDlangSpecialChars(pn)).array);
  366. }
  367.  
  368. // 3. upwards inherit full build configurations (import paths, versions, debugVersions, versionFilters, importPaths, ...)
  369. void configureDependents(ref TargetInfo ti, TargetInfo[string] targets, size_t level = 0)
  370. {
  371. // use `visited` here as pkgs cannot depend on themselves
  372. if (ti.pack in visited)
  373. return;
  374. visited[ti.pack] = typeof(visited[ti.pack]).init;
  375.  
  376. logDiagnostic("%sConfiguring dependent %s, deps:%(%s, %)", ' '.repeat(2 * level), ti.pack.name, ti.dependencies);
  377. // embedded non-binary dependencies
  378. foreach (deppack; ti.packages[1 .. $])
  379. ti.buildSettings.add(targets[deppack.name].buildSettings);
  380. // binary dependencies
  381. foreach (depname; ti.dependencies)
  382. {
  383. auto pdepti = &targets[depname];
  384. configureDependents(*pdepti, targets, level + 1);
  385. mergeFromDependency(pdepti.buildSettings, ti.buildSettings, genSettings.platform);
  386. }
  387. }
  388.  
  389. configureDependents(*roottarget, targets);
  390. visited.clear();
  391.  
  392. // 4. Filter applicable version and debug version identifiers
  393. if (genSettings.filterVersions)
  394. {
  395. foreach (name, ref ti; targets)
  396. {
  397. import std.algorithm.sorting : partition;
  398.  
  399. auto bs = &ti.buildSettings;
  400.  
  401. auto filtered = bs.versions.partition!(v => bs.versionFilters.canFind(v));
  402. logDebug("Filtering out unused versions for %s: %s", name, filtered);
  403. bs.versions = bs.versions[0 .. $ - filtered.length];
  404.  
  405. filtered = bs.debugVersions.partition!(v => bs.debugVersionFilters.canFind(v));
  406. logDebug("Filtering out unused debug versions for %s: %s", name, filtered);
  407. bs.debugVersions = bs.debugVersions[0 .. $ - filtered.length];
  408. }
  409. }
  410.  
  411. // 5. override string import files in dependencies
  412. static void overrideStringImports(ref TargetInfo target,
  413. ref TargetInfo parent, TargetInfo[string] targets, string[] overrides)
  414. {
  415. // Since string import paths are inherited from dependencies in the
  416. // inheritance step above (step 3), it is guaranteed that all
  417. // following dependencies will not have string import paths either,
  418. // so we can skip the recursion here
  419. if (!target.buildSettings.stringImportPaths.length)
  420. return;
  421.  
  422. // do not use visited here as string imports can be overridden by *any* parent
  423. //
  424. // special support for overriding string imports in parent packages
  425. // this is a candidate for deprecation, once an alternative approach
  426. // has been found
  427. bool any_override = false;
  428.  
  429. // override string import files (used for up to date checking)
  430. foreach (ref f; target.buildSettings.stringImportFiles)
  431. {
  432. foreach (o; overrides)
  433. {
  434. NativePath op;
  435. if (f != o && NativePath(f).head == (op = NativePath(o)).head) {
  436. logDebug("string import %s overridden by %s", f, o);
  437. f = o;
  438. any_override = true;
  439. }
  440. }
  441. }
  442.  
  443. // override string import paths by prepending to the list, in
  444. // case there is any overlapping file
  445. if (any_override)
  446. target.buildSettings.prependStringImportPaths(parent.buildSettings.stringImportPaths);
  447.  
  448. // add all files to overrides for recursion
  449. overrides ~= target.buildSettings.stringImportFiles;
  450.  
  451. // recursively override all dependencies with the accumulated files/paths
  452. foreach (depname; target.dependencies)
  453. overrideStringImports(targets[depname], target, targets, overrides);
  454. }
  455.  
  456. // push string import paths/files down to all direct and indirect
  457. // dependencies, overriding their own
  458. foreach (depname; roottarget.dependencies)
  459. overrideStringImports(targets[depname], *roottarget, targets,
  460. roottarget.buildSettings.stringImportFiles);
  461.  
  462. // remove targets without output
  463. foreach (name; targets.keys)
  464. {
  465. if (!hasOutput[name])
  466. targets.remove(name);
  467. }
  468. }
  469.  
  470. // infer applicable version identifiers
  471. private static void inferVersionFilters(ref TargetInfo ti)
  472. {
  473. import std.algorithm.searching : any;
  474. import std.file : timeLastModified;
  475. import std.path : extension;
  476. import std.range : chain;
  477. import std.regex : ctRegex, matchAll;
  478. import std.stdio : File;
  479. import std.datetime : Clock, SysTime, UTC;
  480. import dub.compilers.utils : isLinkerFile;
  481. import dub.internal.vibecompat.data.json : Json, JSONException;
  482.  
  483. auto bs = &ti.buildSettings;
  484.  
  485. // only infer if neither version filters are specified explicitly
  486. if (bs.versionFilters.length || bs.debugVersionFilters.length)
  487. {
  488. logDebug("Using specified versionFilters for %s: %s %s", ti.pack.name,
  489. bs.versionFilters, bs.debugVersionFilters);
  490. return;
  491. }
  492.  
  493. // check all existing source files for version identifiers
  494. static immutable dexts = [".d", ".di"];
  495. auto srcs = chain(bs.sourceFiles, bs.importFiles, bs.stringImportFiles)
  496. .filter!(f => dexts.canFind(f.extension)).filter!exists;
  497. // try to load cached filters first
  498. auto cache = ti.pack.metadataCache;
  499. try
  500. {
  501. auto cachedFilters = cache["versionFilters"];
  502. if (cachedFilters.type != Json.Type.undefined)
  503. cachedFilters = cachedFilters[ti.config];
  504. if (cachedFilters.type != Json.Type.undefined)
  505. {
  506. immutable mtime = SysTime.fromISOExtString(cachedFilters["mtime"].get!string);
  507. if (!srcs.any!(src => src.timeLastModified > mtime))
  508. {
  509. auto versionFilters = cachedFilters["versions"][].map!(j => j.get!string).array;
  510. auto debugVersionFilters = cachedFilters["debugVersions"][].map!(j => j.get!string).array;
  511. logDebug("Using cached versionFilters for %s: %s %s", ti.pack.name,
  512. versionFilters, debugVersionFilters);
  513. bs.addVersionFilters(versionFilters);
  514. bs.addDebugVersionFilters(debugVersionFilters);
  515. return;
  516. }
  517. }
  518. }
  519. catch (JSONException e)
  520. {
  521. logWarn("Exception during loading invalid package cache %s.\n%s",
  522. ti.pack.path ~ ".dub/metadata_cache.json", e);
  523. }
  524.  
  525. // use ctRegex for performance reasons, only small compile time increase
  526. enum verRE = ctRegex!`(?:^|\s)version\s*\(\s*([^\s]*?)\s*\)`;
  527. enum debVerRE = ctRegex!`(?:^|\s)debug\s*\(\s*([^\s]*?)\s*\)`;
  528.  
  529. auto versionFilters = appender!(string[]);
  530. auto debugVersionFilters = appender!(string[]);
  531.  
  532. foreach (file; srcs)
  533. {
  534. foreach (line; File(file).byLine)
  535. {
  536. foreach (m; line.matchAll(verRE))
  537. if (!versionFilters.data.canFind(m[1]))
  538. versionFilters.put(m[1].idup);
  539. foreach (m; line.matchAll(debVerRE))
  540. if (!debugVersionFilters.data.canFind(m[1]))
  541. debugVersionFilters.put(m[1].idup);
  542. }
  543. }
  544. logDebug("Using inferred versionFilters for %s: %s %s", ti.pack.name,
  545. versionFilters.data, debugVersionFilters.data);
  546. bs.addVersionFilters(versionFilters.data);
  547. bs.addDebugVersionFilters(debugVersionFilters.data);
  548.  
  549. auto cachedFilters = cache["versionFilters"];
  550. if (cachedFilters.type == Json.Type.undefined)
  551. cachedFilters = cache["versionFilters"] = [ti.config: Json.emptyObject];
  552. cachedFilters[ti.config] = [
  553. "mtime": Json(Clock.currTime(UTC()).toISOExtString),
  554. "versions": Json(versionFilters.data.map!Json.array),
  555. "debugVersions": Json(debugVersionFilters.data.map!Json.array),
  556. ];
  557. ti.pack.metadataCache = cache;
  558. }
  559.  
  560. private static void mergeFromDependent(const scope ref BuildSettings parent, ref BuildSettings child)
  561. {
  562. child.addVersions(parent.versions);
  563. child.addDebugVersions(parent.debugVersions);
  564. child.addOptions(BuildOptions(parent.options & inheritedBuildOptions));
  565. }
  566.  
  567. private static void mergeFromDependency(const scope ref BuildSettings child, ref BuildSettings parent, const scope ref BuildPlatform platform)
  568. {
  569. import dub.compilers.utils : isLinkerFile;
  570.  
  571. parent.addDFlags(child.dflags);
  572. parent.addVersions(child.versions);
  573. parent.addDebugVersions(child.debugVersions);
  574. parent.addVersionFilters(child.versionFilters);
  575. parent.addDebugVersionFilters(child.debugVersionFilters);
  576. parent.addImportPaths(child.importPaths);
  577. parent.addStringImportPaths(child.stringImportPaths);
  578. // linking of static libraries is done by parent
  579. if (child.targetType == TargetType.staticLibrary) {
  580. parent.addSourceFiles(child.sourceFiles.filter!(f => isLinkerFile(platform, f)).array);
  581. parent.addLibs(child.libs);
  582. parent.addLFlags(child.lflags);
  583. }
  584. }
  585.  
  586. // configure targets for build types such as release, or unittest-cov
  587. private void addBuildTypeSettings(TargetInfo[string] targets, in GeneratorSettings settings)
  588. {
  589. foreach (ref ti; targets.byValue) {
  590. ti.buildSettings.add(settings.buildSettings);
  591.  
  592. // add build type settings and convert plain DFLAGS to build options
  593. m_project.addBuildTypeSettings(ti.buildSettings, settings, ti.pack is m_project.rootPackage);
  594. settings.compiler.extractBuildOptions(ti.buildSettings);
  595.  
  596. auto tt = ti.buildSettings.targetType;
  597. enforce (tt != TargetType.sourceLibrary || ti.pack !is m_project.rootPackage || (ti.buildSettings.options & BuildOption.syntaxOnly),
  598. format("Main package must not have target type \"%s\". Cannot build.", tt));
  599. }
  600. }
  601. }
  602.  
  603.  
  604. struct GeneratorSettings {
  605. BuildPlatform platform;
  606. Compiler compiler;
  607. string config;
  608. string buildType;
  609. BuildSettings buildSettings;
  610. BuildMode buildMode = BuildMode.separate;
  611. int targetExitStatus;
  612.  
  613. bool combined; // compile all in one go instead of each dependency separately
  614. bool filterVersions;
  615.  
  616. // only used for generator "build"
  617. bool run, force, direct, rdmd, tempBuild, parallelBuild;
  618.  
  619. /// single file dub package
  620. bool single;
  621.  
  622. string[] runArgs;
  623. void delegate(int status, string output) compileCallback;
  624. void delegate(int status, string output) linkCallback;
  625. void delegate(int status, string output) runCallback;
  626. }
  627.  
  628.  
  629. /**
  630. Determines the mode in which the compiler and linker are invoked.
  631. */
  632. enum BuildMode {
  633. separate, /// Compile and link separately
  634. allAtOnce, /// Perform compile and link with a single compiler invocation
  635. singleFile, /// Compile each file separately
  636. //multipleObjects, /// Generate an object file per module
  637. //multipleObjectsPerModule, /// Use the -multiobj switch to generate multiple object files per module
  638. //compileOnly /// Do not invoke the linker (can be done using a post build command)
  639. }
  640.  
  641.  
  642. /**
  643. Creates a project generator of the given type for the specified project.
  644. */
  645. ProjectGenerator createProjectGenerator(string generator_type, Project project)
  646. {
  647. assert(project !is null, "Project instance needed to create a generator.");
  648.  
  649. generator_type = generator_type.toLower();
  650. switch(generator_type) {
  651. default:
  652. throw new Exception("Unknown project generator: "~generator_type);
  653. case "build":
  654. logDebug("Creating build generator.");
  655. return new BuildGenerator(project);
  656. case "mono-d":
  657. throw new Exception("The Mono-D generator has been removed. Use Mono-D's built in DUB support instead.");
  658. case "visuald":
  659. logDebug("Creating VisualD generator.");
  660. return new VisualDGenerator(project);
  661. case "sublimetext":
  662. logDebug("Creating SublimeText generator.");
  663. return new SublimeTextGenerator(project);
  664. case "cmake":
  665. logDebug("Creating CMake generator.");
  666. return new CMakeGenerator(project);
  667. }
  668. }
  669.  
  670.  
  671. /**
  672. Runs pre-build commands and performs other required setup before project files are generated.
  673. */
  674. private void prepareGeneration(in Package pack, in Project proj, in GeneratorSettings settings,
  675. in BuildSettings buildsettings)
  676. {
  677. if (buildsettings.preGenerateCommands.length && !isRecursiveInvocation(pack.name)) {
  678. logInfo("Running pre-generate commands for %s...", pack.name);
  679. runBuildCommands(buildsettings.preGenerateCommands, pack, proj, settings, buildsettings);
  680. }
  681. }
  682.  
  683. /**
  684. Runs post-build commands and copies required files to the binary directory.
  685. */
  686. private void finalizeGeneration(in Package pack, in Project proj, in GeneratorSettings settings,
  687. in BuildSettings buildsettings, NativePath target_path, bool generate_binary)
  688. {
  689. import std.path : globMatch;
  690.  
  691. if (buildsettings.postGenerateCommands.length && !isRecursiveInvocation(pack.name)) {
  692. logInfo("Running post-generate commands for %s...", pack.name);
  693. runBuildCommands(buildsettings.postGenerateCommands, pack, proj, settings, buildsettings);
  694. }
  695.  
  696. if (generate_binary) {
  697. if (!exists(buildsettings.targetPath))
  698. mkdirRecurse(buildsettings.targetPath);
  699.  
  700. if (buildsettings.copyFiles.length) {
  701. void copyFolderRec(NativePath folder, NativePath dstfolder)
  702. {
  703. mkdirRecurse(dstfolder.toNativeString());
  704. foreach (de; iterateDirectory(folder.toNativeString())) {
  705. if (de.isDirectory) {
  706. copyFolderRec(folder ~ de.name, dstfolder ~ de.name);
  707. } else {
  708. try hardLinkFile(folder ~ de.name, dstfolder ~ de.name, true);
  709. catch (Exception e) {
  710. logWarn("Failed to copy file %s: %s", (folder ~ de.name).toNativeString(), e.msg);
  711. }
  712. }
  713. }
  714. }
  715.  
  716. void tryCopyDir(string file)
  717. {
  718. auto src = NativePath(file);
  719. if (!src.absolute) src = pack.path ~ src;
  720. auto dst = target_path ~ NativePath(file).head;
  721. if (src == dst) {
  722. logDiagnostic("Skipping copy of %s (same source and destination)", file);
  723. return;
  724. }
  725. logDiagnostic(" %s to %s", src.toNativeString(), dst.toNativeString());
  726. try {
  727. copyFolderRec(src, dst);
  728. } catch(Exception e) logWarn("Failed to copy %s to %s: %s", src.toNativeString(), dst.toNativeString(), e.msg);
  729. }
  730.  
  731. void tryCopyFile(string file)
  732. {
  733. auto src = NativePath(file);
  734. if (!src.absolute) src = pack.path ~ src;
  735. auto dst = target_path ~ NativePath(file).head;
  736. if (src == dst) {
  737. logDiagnostic("Skipping copy of %s (same source and destination)", file);
  738. return;
  739. }
  740. logDiagnostic(" %s to %s", src.toNativeString(), dst.toNativeString());
  741. try {
  742. hardLinkFile(src, dst, true);
  743. } catch(Exception e) logWarn("Failed to copy %s to %s: %s", src.toNativeString(), dst.toNativeString(), e.msg);
  744. }
  745. logInfo("Copying files for %s...", pack.name);
  746. string[] globs;
  747. foreach (f; buildsettings.copyFiles)
  748. {
  749. if (f.canFind("*", "?") ||
  750. (f.canFind("{") && f.balancedParens('{', '}')) ||
  751. (f.canFind("[") && f.balancedParens('[', ']')))
  752. {
  753. globs ~= f;
  754. }
  755. else
  756. {
  757. if (f.isDir)
  758. tryCopyDir(f);
  759. else
  760. tryCopyFile(f);
  761. }
  762. }
  763. if (globs.length) // Search all files for glob matches
  764. {
  765. foreach (f; dirEntries(pack.path.toNativeString(), SpanMode.breadth))
  766. {
  767. foreach (glob; globs)
  768. {
  769. if (f.name().globMatch(glob))
  770. {
  771. if (f.isDir)
  772. tryCopyDir(f);
  773. else
  774. tryCopyFile(f);
  775. break;
  776. }
  777. }
  778. }
  779. }
  780. }
  781.  
  782. }
  783. }
  784.  
  785.  
  786. /** Runs a list of build commands for a particular package.
  787.  
  788. This function sets all DUB speficic environment variables and makes sure
  789. that recursive dub invocations are detected and don't result in infinite
  790. command execution loops. The latter could otherwise happen when a command
  791. runs "dub describe" or similar functionality.
  792. */
  793. void runBuildCommands(in string[] commands, in Package pack, in Project proj,
  794. in GeneratorSettings settings, in BuildSettings build_settings)
  795. {
  796. import dub.internal.utils : getDUBExePath, runCommands;
  797. import std.conv : to, text;
  798. import std.process : environment, escapeShellFileName;
  799.  
  800. string[string] env = environment.toAA();
  801. // TODO: do more elaborate things here
  802. // TODO: escape/quote individual items appropriately
  803. env["VERSIONS"] = join(cast(string[])build_settings.versions," ");
  804. env["LIBS"] = join(cast(string[])build_settings.libs," ");
  805. env["SOURCE_FILES"] = join(cast(string[])build_settings.sourceFiles," ");
  806. env["IMPORT_PATHS"] = join(cast(string[])build_settings.importPaths," ");
  807. env["STRING_IMPORT_PATHS"] = join(cast(string[])build_settings.stringImportPaths," ");
  808.  
  809. env["DC"] = settings.platform.compilerBinary;
  810. env["DC_BASE"] = settings.platform.compiler;
  811. env["D_FRONTEND_VER"] = to!string(settings.platform.frontendVersion);
  812.  
  813. env["DUB_EXE"] = getDUBExePath(settings.platform.compilerBinary);
  814. env["DUB_PLATFORM"] = join(cast(string[])settings.platform.platform," ");
  815. env["DUB_ARCH"] = join(cast(string[])settings.platform.architecture," ");
  816.  
  817. env["DUB_TARGET_TYPE"] = to!string(build_settings.targetType);
  818. env["DUB_TARGET_PATH"] = build_settings.targetPath;
  819. env["DUB_TARGET_NAME"] = build_settings.targetName;
  820. env["DUB_TARGET_EXIT_STATUS"] = settings.targetExitStatus.text;
  821. env["DUB_WORKING_DIRECTORY"] = build_settings.workingDirectory;
  822. env["DUB_MAIN_SOURCE_FILE"] = build_settings.mainSourceFile;
  823.  
  824. env["DUB_CONFIG"] = settings.config;
  825. env["DUB_BUILD_TYPE"] = settings.buildType;
  826. env["DUB_BUILD_MODE"] = to!string(settings.buildMode);
  827. env["DUB_PACKAGE"] = pack.name;
  828. env["DUB_PACKAGE_DIR"] = pack.path.toNativeString();
  829. env["DUB_ROOT_PACKAGE"] = proj.rootPackage.name;
  830. env["DUB_ROOT_PACKAGE_DIR"] = proj.rootPackage.path.toNativeString();
  831. env["DUB_PACKAGE_VERSION"] = pack.version_.toString();
  832.  
  833. env["DUB_COMBINED"] = settings.combined? "TRUE" : "";
  834. env["DUB_RUN"] = settings.run? "TRUE" : "";
  835. env["DUB_FORCE"] = settings.force? "TRUE" : "";
  836. env["DUB_DIRECT"] = settings.direct? "TRUE" : "";
  837. env["DUB_RDMD"] = settings.rdmd? "TRUE" : "";
  838. env["DUB_TEMP_BUILD"] = settings.tempBuild? "TRUE" : "";
  839. env["DUB_PARALLEL_BUILD"] = settings.parallelBuild? "TRUE" : "";
  840.  
  841. env["DUB_RUN_ARGS"] = (cast(string[])settings.runArgs).map!(escapeShellFileName).join(" ");
  842.  
  843. auto cfgs = proj.getPackageConfigs(settings.platform, settings.config, true);
  844. auto rootPackageBuildSettings = proj.rootPackage.getBuildSettings(settings.platform, cfgs[proj.rootPackage.name]);
  845. env["DUB_ROOT_PACKAGE_TARGET_TYPE"] = to!string(rootPackageBuildSettings.targetType);
  846. env["DUB_ROOT_PACKAGE_TARGET_PATH"] = rootPackageBuildSettings.targetPath;
  847. env["DUB_ROOT_PACKAGE_TARGET_NAME"] = rootPackageBuildSettings.targetName;
  848.  
  849. auto depNames = proj.dependencies.map!((a) => a.name).array();
  850. storeRecursiveInvokations(env, proj.rootPackage.name ~ depNames);
  851. runCommands(commands, env, pack.path().toString());
  852. }
  853.  
  854. private bool isRecursiveInvocation(string pack)
  855. {
  856. import std.algorithm : canFind, splitter;
  857. import std.process : environment;
  858.  
  859. return environment
  860. .get("DUB_PACKAGES_USED", "")
  861. .splitter(",")
  862. .canFind(pack);
  863. }
  864.  
  865. private void storeRecursiveInvokations(string[string] env, string[] packs)
  866. {
  867. import std.algorithm : canFind, splitter;
  868. import std.range : chain;
  869. import std.process : environment;
  870.  
  871. env["DUB_PACKAGES_USED"] = environment
  872. .get("DUB_PACKAGES_USED", "")
  873. .splitter(",")
  874. .chain(packs)
  875. .join(",");
  876. }