Newer
Older
dub_jkp / source / dub / generators / generator.d
@Remi Thebault Remi Thebault on 25 Nov 2018 24 KB implement $DUB build variable
  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;
  24. import std.array;
  25. import std.exception;
  26. import std.file;
  27. import std.string;
  28.  
  29.  
  30. /**
  31. Common interface for project generators/builders.
  32. */
  33. class ProjectGenerator
  34. {
  35. /** Information about a single binary target.
  36.  
  37. A binary target can either be an executable or a static/dynamic library.
  38. It consists of one or more packages.
  39. */
  40. struct TargetInfo {
  41. /// The root package of this target
  42. Package pack;
  43.  
  44. /// All packages compiled into this target
  45. Package[] packages;
  46.  
  47. /// The configuration used for building the root package
  48. string config;
  49.  
  50. /** Build settings used to build the target.
  51.  
  52. The build settings include all sources of all contained packages.
  53.  
  54. Depending on the specific generator implementation, it may be
  55. necessary to add any static or dynamic libraries generated for
  56. child targets ($(D linkDependencies)).
  57. */
  58. BuildSettings buildSettings;
  59.  
  60. /** List of all dependencies.
  61.  
  62. This list includes dependencies that are not the root of a binary
  63. target.
  64. */
  65. string[] dependencies;
  66.  
  67. /** List of all binary dependencies.
  68.  
  69. This list includes all dependencies that are the root of a binary
  70. target.
  71. */
  72. string[] linkDependencies;
  73. }
  74.  
  75. protected {
  76. Project m_project;
  77. NativePath m_tempTargetExecutablePath;
  78. }
  79.  
  80. this(Project project)
  81. {
  82. m_project = project;
  83. }
  84.  
  85. /** Performs the full generator process.
  86. */
  87. final void generate(GeneratorSettings settings)
  88. {
  89. import dub.compilers.utils : enforceBuildRequirements;
  90.  
  91. if (!settings.config.length) settings.config = m_project.getDefaultConfiguration(settings.platform);
  92.  
  93. string[string] configs = m_project.getPackageConfigs(settings.platform, settings.config);
  94. TargetInfo[string] targets;
  95.  
  96. foreach (pack; m_project.getTopologicalPackageList(true, null, configs)) {
  97. BuildSettings buildSettings;
  98. auto config = configs[pack.name];
  99. buildSettings.processVars(m_project, pack, pack.getBuildSettings(settings.platform, config), settings, true);
  100. targets[pack.name] = TargetInfo(pack, [pack], config, buildSettings);
  101.  
  102. prepareGeneration(pack, m_project, settings, buildSettings);
  103. }
  104.  
  105. string[] mainfiles = configurePackages(m_project.rootPackage, targets, settings);
  106.  
  107. addBuildTypeSettings(targets, settings);
  108. foreach (ref t; targets.byValue) enforceBuildRequirements(t.buildSettings);
  109. auto bs = &targets[m_project.rootPackage.name].buildSettings;
  110. if (bs.targetType == TargetType.executable) bs.addSourceFiles(mainfiles);
  111.  
  112. generateTargets(settings, targets);
  113. auto targetPath = (m_tempTargetExecutablePath.empty) ? NativePath(bs.targetPath) : m_tempTargetExecutablePath;
  114.  
  115. foreach (pack; m_project.getTopologicalPackageList(true, null, configs)) {
  116. BuildSettings buildsettings;
  117. buildsettings.processVars(m_project, pack, pack.getBuildSettings(settings.platform, configs[pack.name]), settings, true);
  118. bool generate_binary = !(buildsettings.options & BuildOption.syntaxOnly);
  119. finalizeGeneration(pack, m_project, settings, buildsettings, targetPath, generate_binary);
  120. }
  121.  
  122. performPostGenerateActions(settings, targets);
  123. }
  124.  
  125. /** Overridden in derived classes to implement the actual generator functionality.
  126.  
  127. The function should go through all targets recursively. The first target
  128. (which is guaranteed to be there) is
  129. $(D targets[m_project.rootPackage.name]). The recursive descent is then
  130. done using the $(D TargetInfo.linkDependencies) list.
  131.  
  132. This method is also potentially responsible for running the pre and post
  133. build commands, while pre and post generate commands are already taken
  134. care of by the $(D generate) method.
  135.  
  136. Params:
  137. settings = The generator settings used for this run
  138. targets = A map from package name to TargetInfo that contains all
  139. binary targets to be built.
  140. */
  141. protected abstract void generateTargets(GeneratorSettings settings, in TargetInfo[string] targets);
  142.  
  143. /** Overridable method to be invoked after the generator process has finished.
  144.  
  145. An examples of functionality placed here is to run the application that
  146. has just been built.
  147. */
  148. protected void performPostGenerateActions(GeneratorSettings settings, in TargetInfo[string] targets) {}
  149.  
  150. /** Configure `rootPackage` and all of it's dependencies.
  151.  
  152. 1. Merge versions, debugVersions, and inheritable build
  153. settings from dependents to their dependencies.
  154.  
  155. 2. Define version identifiers Have_dependency_xyz for all
  156. direct dependencies of all packages.
  157.  
  158. 3. Merge versions, debugVersions, and inheritable build settings from
  159. dependencies to their dependents, so that importer and importee are ABI
  160. compatible. This also transports all Have_dependency_xyz version
  161. identifiers to `rootPackage`.
  162.  
  163. Note: The upwards inheritance is done at last so that siblings do not
  164. influence each other, also see https://github.com/dlang/dub/pull/1128.
  165.  
  166. Note: Targets without output are integrated into their
  167. dependents and removed from `targets`.
  168. */
  169. private string[] configurePackages(Package rootPackage, TargetInfo[string] targets, GeneratorSettings genSettings)
  170. {
  171. import std.algorithm : remove, sort;
  172. import std.range : repeat;
  173.  
  174. // 0. do shallow configuration (not including dependencies) of all packages
  175. TargetType determineTargetType(const ref TargetInfo ti)
  176. {
  177. TargetType tt = ti.buildSettings.targetType;
  178. if (ti.pack is rootPackage) {
  179. if (tt == TargetType.autodetect || tt == TargetType.library) tt = TargetType.staticLibrary;
  180. } else {
  181. if (tt == TargetType.autodetect || tt == TargetType.library) tt = genSettings.combined ? TargetType.sourceLibrary : TargetType.staticLibrary;
  182. else if (tt == TargetType.dynamicLibrary) {
  183. logWarn("Dynamic libraries are not yet supported as dependencies - building as static library.");
  184. tt = TargetType.staticLibrary;
  185. }
  186. }
  187. if (tt != TargetType.none && tt != TargetType.sourceLibrary && ti.buildSettings.sourceFiles.empty) {
  188. logWarn(`Configuration '%s' of package %s contains no source files. Please add {"targetType": "none"} to its package description to avoid building it.`,
  189. ti.config, ti.pack.name);
  190. tt = TargetType.none;
  191. }
  192. return tt;
  193. }
  194.  
  195. string[] mainSourceFiles;
  196. bool[string] hasOutput;
  197.  
  198. foreach (ref ti; targets.byValue)
  199. {
  200. auto bs = &ti.buildSettings;
  201. // determine the actual target type
  202. bs.targetType = determineTargetType(ti);
  203.  
  204. switch (bs.targetType)
  205. {
  206. case TargetType.none:
  207. // ignore any build settings for targetType none (only dependencies will be processed)
  208. *bs = BuildSettings.init;
  209. bs.targetType = TargetType.none;
  210. break;
  211.  
  212. case TargetType.executable:
  213. break;
  214.  
  215. case TargetType.dynamicLibrary:
  216. // set -fPIC for dynamic library builds
  217. ti.buildSettings.addOptions(BuildOption.pic);
  218. goto default;
  219.  
  220. default:
  221. // remove any mainSourceFile from non-executable builds
  222. if (bs.mainSourceFile.length) {
  223. bs.sourceFiles = bs.sourceFiles.remove!(f => f == bs.mainSourceFile);
  224. mainSourceFiles ~= bs.mainSourceFile;
  225. }
  226. break;
  227. }
  228. bool generatesBinary = bs.targetType != TargetType.sourceLibrary && bs.targetType != TargetType.none;
  229. hasOutput[ti.pack.name] = generatesBinary || ti.pack is rootPackage;
  230. }
  231.  
  232. // mark packages as visited (only used during upwards propagation)
  233. void[0][Package] visited;
  234.  
  235. // collect all dependencies
  236. void collectDependencies(Package pack, ref TargetInfo ti, TargetInfo[string] targets, size_t level = 0)
  237. {
  238. // use `visited` here as pkgs cannot depend on themselves
  239. if (pack in visited)
  240. return;
  241. // transitive dependencies must be visited multiple times, see #1350
  242. immutable transitive = !hasOutput[pack.name];
  243. if (!transitive)
  244. visited[pack] = typeof(visited[pack]).init;
  245.  
  246. auto bs = &ti.buildSettings;
  247. if (hasOutput[pack.name])
  248. logDebug("%sConfiguring target %s (%s %s %s)", ' '.repeat(2 * level), pack.name, bs.targetType, bs.targetPath, bs.targetName);
  249. else
  250. logDebug("%sConfiguring target without output %s", ' '.repeat(2 * level), pack.name);
  251.  
  252. // get specified dependencies, e.g. vibe-d ~0.8.1
  253. auto deps = pack.getDependencies(targets[pack.name].config);
  254. logDebug("deps: %s -> %(%s, %)", pack.name, deps.byKey);
  255. foreach (depname; deps.keys.sort())
  256. {
  257. auto depspec = deps[depname];
  258. // get selected package for that dependency, e.g. vibe-d 0.8.2-beta.2
  259. auto deppack = m_project.getDependency(depname, depspec.optional);
  260. if (deppack is null) continue; // optional and not selected
  261.  
  262. // if dependency has no output
  263. if (!hasOutput[depname]) {
  264. // add itself
  265. ti.packages ~= deppack;
  266. // and it's transitive dependencies to current target
  267. collectDependencies(deppack, ti, targets, level + 1);
  268. continue;
  269. }
  270. auto depti = &targets[depname];
  271. const depbs = &depti.buildSettings;
  272. if (depbs.targetType == TargetType.executable && ti.buildSettings.targetType != TargetType.none)
  273. continue;
  274.  
  275. // add to (link) dependencies
  276. ti.dependencies ~= depname;
  277. ti.linkDependencies ~= depname;
  278.  
  279. // recurse
  280. collectDependencies(deppack, *depti, targets, level + 1);
  281.  
  282. // also recursively add all link dependencies of static libraries
  283. // preserve topological sorting of dependencies for correct link order
  284. if (depbs.targetType == TargetType.staticLibrary)
  285. ti.linkDependencies = ti.linkDependencies.filter!(d => !depti.linkDependencies.canFind(d)).array ~ depti.linkDependencies;
  286. }
  287.  
  288. enforce(!(ti.buildSettings.targetType == TargetType.none && ti.dependencies.empty),
  289. "Package with target type \"none\" must have dependencies to build.");
  290. }
  291.  
  292. collectDependencies(rootPackage, targets[rootPackage.name], targets);
  293. static if (__VERSION__ > 2070)
  294. visited.clear();
  295. else
  296. destroy(visited);
  297.  
  298. // 1. downwards inherits versions, debugVersions, and inheritable build settings
  299. static void configureDependencies(in ref TargetInfo ti, TargetInfo[string] targets, size_t level = 0)
  300. {
  301. // do not use `visited` here as dependencies must inherit
  302. // configurations from *all* of their parents
  303. logDebug("%sConfigure dependencies of %s, deps:%(%s, %)", ' '.repeat(2 * level), ti.pack.name, ti.dependencies);
  304. foreach (depname; ti.dependencies)
  305. {
  306. auto pti = &targets[depname];
  307. mergeFromDependent(ti.buildSettings, pti.buildSettings);
  308. configureDependencies(*pti, targets, level + 1);
  309. }
  310. }
  311.  
  312. configureDependencies(targets[rootPackage.name], targets);
  313.  
  314. // 2. add Have_dependency_xyz for all direct dependencies of a target
  315. // (includes incorporated non-target dependencies and their dependencies)
  316. foreach (ref ti; targets.byValue)
  317. {
  318. import std.range : chain;
  319. import dub.internal.utils : stripDlangSpecialChars;
  320.  
  321. auto bs = &ti.buildSettings;
  322. auto pkgnames = ti.packages.map!(p => p.name).chain(ti.dependencies);
  323. bs.addVersions(pkgnames.map!(pn => "Have_" ~ stripDlangSpecialChars(pn)).array);
  324. }
  325.  
  326. // 3. upwards inherit full build configurations (import paths, versions, debugVersions, ...)
  327. void configureDependents(ref TargetInfo ti, TargetInfo[string] targets, size_t level = 0)
  328. {
  329. // use `visited` here as pkgs cannot depend on themselves
  330. if (ti.pack in visited)
  331. return;
  332. visited[ti.pack] = typeof(visited[ti.pack]).init;
  333.  
  334. logDiagnostic("%sConfiguring dependent %s, deps:%(%s, %)", ' '.repeat(2 * level), ti.pack.name, ti.dependencies);
  335. // embedded non-binary dependencies
  336. foreach (deppack; ti.packages[1 .. $])
  337. ti.buildSettings.add(targets[deppack.name].buildSettings);
  338. // binary dependencies
  339. foreach (depname; ti.dependencies)
  340. {
  341. auto pdepti = &targets[depname];
  342. configureDependents(*pdepti, targets, level + 1);
  343. mergeFromDependency(pdepti.buildSettings, ti.buildSettings);
  344. }
  345. }
  346.  
  347. configureDependents(targets[rootPackage.name], targets);
  348. static if (__VERSION__ > 2070)
  349. visited.clear();
  350. else
  351. destroy(visited);
  352.  
  353. // 4. override string import files in dependencies
  354. static void overrideStringImports(ref TargetInfo ti, TargetInfo[string] targets, string[] overrides)
  355. {
  356. // do not use visited here as string imports can be overridden by *any* parent
  357. //
  358. // special support for overriding string imports in parent packages
  359. // this is a candidate for deprecation, once an alternative approach
  360. // has been found
  361. if (ti.buildSettings.stringImportPaths.length) {
  362. // override string import files (used for up to date checking)
  363. foreach (ref f; ti.buildSettings.stringImportFiles)
  364. {
  365. foreach (o; overrides)
  366. {
  367. NativePath op;
  368. if (f != o && NativePath(f).head == (op = NativePath(o)).head) {
  369. logDebug("string import %s overridden by %s", f, o);
  370. f = o;
  371. ti.buildSettings.prependStringImportPaths(op.parentPath.toNativeString);
  372. }
  373. }
  374. }
  375. }
  376. // add to overrides for recursion
  377. overrides ~= ti.buildSettings.stringImportFiles;
  378. // override dependencies
  379. foreach (depname; ti.dependencies)
  380. overrideStringImports(targets[depname], targets, overrides);
  381. }
  382.  
  383. overrideStringImports(targets[rootPackage.name], targets, null);
  384.  
  385. // remove targets without output
  386. foreach (name; targets.keys)
  387. {
  388. if (!hasOutput[name])
  389. targets.remove(name);
  390. }
  391.  
  392. return mainSourceFiles;
  393. }
  394.  
  395. private static void mergeFromDependent(in ref BuildSettings parent, ref BuildSettings child)
  396. {
  397. child.addVersions(parent.versions);
  398. child.addDebugVersions(parent.debugVersions);
  399. child.addOptions(BuildOptions(cast(BuildOptions)parent.options & inheritedBuildOptions));
  400. }
  401.  
  402. private static void mergeFromDependency(in ref BuildSettings child, ref BuildSettings parent)
  403. {
  404. import dub.compilers.utils : isLinkerFile;
  405.  
  406. parent.addDFlags(child.dflags);
  407. parent.addVersions(child.versions);
  408. parent.addDebugVersions(child.debugVersions);
  409. parent.addImportPaths(child.importPaths);
  410. parent.addStringImportPaths(child.stringImportPaths);
  411. // linking of static libraries is done by parent
  412. if (child.targetType == TargetType.staticLibrary) {
  413. parent.addSourceFiles(child.sourceFiles.filter!isLinkerFile.array);
  414. parent.addLibs(child.libs);
  415. parent.addLFlags(child.lflags);
  416. }
  417. }
  418.  
  419. // configure targets for build types such as release, or unittest-cov
  420. private void addBuildTypeSettings(TargetInfo[string] targets, in GeneratorSettings settings)
  421. {
  422. foreach (ref ti; targets.byValue) {
  423. ti.buildSettings.add(settings.buildSettings);
  424.  
  425. // add build type settings and convert plain DFLAGS to build options
  426. m_project.addBuildTypeSettings(ti.buildSettings, settings, ti.pack is m_project.rootPackage);
  427. settings.compiler.extractBuildOptions(ti.buildSettings);
  428.  
  429. auto tt = ti.buildSettings.targetType;
  430. enforce (tt != TargetType.sourceLibrary || ti.pack !is m_project.rootPackage || (ti.buildSettings.options & BuildOption.syntaxOnly),
  431. format("Main package must not have target type \"%s\". Cannot build.", tt));
  432. }
  433. }
  434. }
  435.  
  436.  
  437. struct GeneratorSettings {
  438. BuildPlatform platform;
  439. Compiler compiler;
  440. string config;
  441. string buildType;
  442. BuildSettings buildSettings;
  443. BuildMode buildMode = BuildMode.separate;
  444. int targetExitStatus;
  445.  
  446. bool combined; // compile all in one go instead of each dependency separately
  447.  
  448. // only used for generator "build"
  449. bool run, force, direct, rdmd, tempBuild, parallelBuild;
  450. string[] runArgs;
  451. void delegate(int status, string output) compileCallback;
  452. void delegate(int status, string output) linkCallback;
  453. void delegate(int status, string output) runCallback;
  454. }
  455.  
  456.  
  457. /**
  458. Determines the mode in which the compiler and linker are invoked.
  459. */
  460. enum BuildMode {
  461. separate, /// Compile and link separately
  462. allAtOnce, /// Perform compile and link with a single compiler invocation
  463. singleFile, /// Compile each file separately
  464. //multipleObjects, /// Generate an object file per module
  465. //multipleObjectsPerModule, /// Use the -multiobj switch to generate multiple object files per module
  466. //compileOnly /// Do not invoke the linker (can be done using a post build command)
  467. }
  468.  
  469.  
  470. /**
  471. Creates a project generator of the given type for the specified project.
  472. */
  473. ProjectGenerator createProjectGenerator(string generator_type, Project project)
  474. {
  475. assert(project !is null, "Project instance needed to create a generator.");
  476.  
  477. generator_type = generator_type.toLower();
  478. switch(generator_type) {
  479. default:
  480. throw new Exception("Unknown project generator: "~generator_type);
  481. case "build":
  482. logDebug("Creating build generator.");
  483. return new BuildGenerator(project);
  484. case "mono-d":
  485. throw new Exception("The Mono-D generator has been removed. Use Mono-D's built in DUB support instead.");
  486. case "visuald":
  487. logDebug("Creating VisualD generator.");
  488. return new VisualDGenerator(project);
  489. case "sublimetext":
  490. logDebug("Creating SublimeText generator.");
  491. return new SublimeTextGenerator(project);
  492. case "cmake":
  493. logDebug("Creating CMake generator.");
  494. return new CMakeGenerator(project);
  495. }
  496. }
  497.  
  498.  
  499. /**
  500. Runs pre-build commands and performs other required setup before project files are generated.
  501. */
  502. private void prepareGeneration(in Package pack, in Project proj, in GeneratorSettings settings,
  503. in BuildSettings buildsettings)
  504. {
  505. if (buildsettings.preGenerateCommands.length && !isRecursiveInvocation(pack.name)) {
  506. logInfo("Running pre-generate commands for %s...", pack.name);
  507. runBuildCommands(buildsettings.preGenerateCommands, pack, proj, settings, buildsettings);
  508. }
  509. }
  510.  
  511. /**
  512. Runs post-build commands and copies required files to the binary directory.
  513. */
  514. private void finalizeGeneration(in Package pack, in Project proj, in GeneratorSettings settings,
  515. in BuildSettings buildsettings, NativePath target_path, bool generate_binary)
  516. {
  517. import std.path : globMatch;
  518.  
  519. if (buildsettings.postGenerateCommands.length && !isRecursiveInvocation(pack.name)) {
  520. logInfo("Running post-generate commands for %s...", pack.name);
  521. runBuildCommands(buildsettings.postGenerateCommands, pack, proj, settings, buildsettings);
  522. }
  523.  
  524. if (generate_binary) {
  525. if (!exists(buildsettings.targetPath))
  526. mkdirRecurse(buildsettings.targetPath);
  527.  
  528. if (buildsettings.copyFiles.length) {
  529. void copyFolderRec(NativePath folder, NativePath dstfolder)
  530. {
  531. mkdirRecurse(dstfolder.toNativeString());
  532. foreach (de; iterateDirectory(folder.toNativeString())) {
  533. if (de.isDirectory) {
  534. copyFolderRec(folder ~ de.name, dstfolder ~ de.name);
  535. } else {
  536. try hardLinkFile(folder ~ de.name, dstfolder ~ de.name, true);
  537. catch (Exception e) {
  538. logWarn("Failed to copy file %s: %s", (folder ~ de.name).toNativeString(), e.msg);
  539. }
  540. }
  541. }
  542. }
  543.  
  544. void tryCopyDir(string file)
  545. {
  546. auto src = NativePath(file);
  547. if (!src.absolute) src = pack.path ~ src;
  548. auto dst = target_path ~ NativePath(file).head;
  549. if (src == dst) {
  550. logDiagnostic("Skipping copy of %s (same source and destination)", file);
  551. return;
  552. }
  553. logDiagnostic(" %s to %s", src.toNativeString(), dst.toNativeString());
  554. try {
  555. copyFolderRec(src, dst);
  556. } catch(Exception e) logWarn("Failed to copy %s to %s: %s", src.toNativeString(), dst.toNativeString(), e.msg);
  557. }
  558.  
  559. void tryCopyFile(string file)
  560. {
  561. auto src = NativePath(file);
  562. if (!src.absolute) src = pack.path ~ src;
  563. auto dst = target_path ~ NativePath(file).head;
  564. if (src == dst) {
  565. logDiagnostic("Skipping copy of %s (same source and destination)", file);
  566. return;
  567. }
  568. logDiagnostic(" %s to %s", src.toNativeString(), dst.toNativeString());
  569. try {
  570. hardLinkFile(src, dst, true);
  571. } catch(Exception e) logWarn("Failed to copy %s to %s: %s", src.toNativeString(), dst.toNativeString(), e.msg);
  572. }
  573. logInfo("Copying files for %s...", pack.name);
  574. string[] globs;
  575. foreach (f; buildsettings.copyFiles)
  576. {
  577. if (f.canFind("*", "?") ||
  578. (f.canFind("{") && f.balancedParens('{', '}')) ||
  579. (f.canFind("[") && f.balancedParens('[', ']')))
  580. {
  581. globs ~= f;
  582. }
  583. else
  584. {
  585. if (f.isDir)
  586. tryCopyDir(f);
  587. else
  588. tryCopyFile(f);
  589. }
  590. }
  591. if (globs.length) // Search all files for glob matches
  592. {
  593. foreach (f; dirEntries(pack.path.toNativeString(), SpanMode.breadth))
  594. {
  595. foreach (glob; globs)
  596. {
  597. if (f.name().globMatch(glob))
  598. {
  599. if (f.isDir)
  600. tryCopyDir(f);
  601. else
  602. tryCopyFile(f);
  603. break;
  604. }
  605. }
  606. }
  607. }
  608. }
  609.  
  610. }
  611. }
  612.  
  613.  
  614. /** Runs a list of build commands for a particular package.
  615.  
  616. This function sets all DUB speficic environment variables and makes sure
  617. that recursive dub invocations are detected and don't result in infinite
  618. command execution loops. The latter could otherwise happen when a command
  619. runs "dub describe" or similar functionality.
  620. */
  621. void runBuildCommands(in string[] commands, in Package pack, in Project proj,
  622. in GeneratorSettings settings, in BuildSettings build_settings)
  623. {
  624. import dub.internal.utils : getDUBExePath, runCommands;
  625. import std.conv : to, text;
  626. import std.process : environment, escapeShellFileName;
  627.  
  628. string[string] env = environment.toAA();
  629. // TODO: do more elaborate things here
  630. // TODO: escape/quote individual items appropriately
  631. env["DFLAGS"] = join(cast(string[])build_settings.dflags, " ");
  632. env["LFLAGS"] = join(cast(string[])build_settings.lflags," ");
  633. env["VERSIONS"] = join(cast(string[])build_settings.versions," ");
  634. env["LIBS"] = join(cast(string[])build_settings.libs," ");
  635. env["IMPORT_PATHS"] = join(cast(string[])build_settings.importPaths," ");
  636. env["STRING_IMPORT_PATHS"] = join(cast(string[])build_settings.stringImportPaths," ");
  637.  
  638. env["DC"] = settings.platform.compilerBinary;
  639. env["DC_BASE"] = settings.platform.compiler;
  640. env["D_FRONTEND_VER"] = to!string(settings.platform.frontendVersion);
  641.  
  642. env["DUB_EXE"] = getDUBExePath(settings.platform.compilerBinary);
  643. env["DUB_PLATFORM"] = join(cast(string[])settings.platform.platform," ");
  644. env["DUB_ARCH"] = join(cast(string[])settings.platform.architecture," ");
  645.  
  646. env["DUB_TARGET_TYPE"] = to!string(build_settings.targetType);
  647. env["DUB_TARGET_PATH"] = build_settings.targetPath;
  648. env["DUB_TARGET_NAME"] = build_settings.targetName;
  649. env["DUB_TARGET_EXIT_STATUS"] = settings.targetExitStatus.text;
  650. env["DUB_WORKING_DIRECTORY"] = build_settings.workingDirectory;
  651. env["DUB_MAIN_SOURCE_FILE"] = build_settings.mainSourceFile;
  652.  
  653. env["DUB_CONFIG"] = settings.config;
  654. env["DUB_BUILD_TYPE"] = settings.buildType;
  655. env["DUB_BUILD_MODE"] = to!string(settings.buildMode);
  656. env["DUB_PACKAGE"] = pack.name;
  657. env["DUB_PACKAGE_DIR"] = pack.path.toNativeString();
  658. env["DUB_ROOT_PACKAGE"] = proj.rootPackage.name;
  659. env["DUB_ROOT_PACKAGE_DIR"] = proj.rootPackage.path.toNativeString();
  660. env["DUB_PACKAGE_VERSION"] = pack.version_.toString();
  661.  
  662. env["DUB_COMBINED"] = settings.combined? "TRUE" : "";
  663. env["DUB_RUN"] = settings.run? "TRUE" : "";
  664. env["DUB_FORCE"] = settings.force? "TRUE" : "";
  665. env["DUB_DIRECT"] = settings.direct? "TRUE" : "";
  666. env["DUB_RDMD"] = settings.rdmd? "TRUE" : "";
  667. env["DUB_TEMP_BUILD"] = settings.tempBuild? "TRUE" : "";
  668. env["DUB_PARALLEL_BUILD"] = settings.parallelBuild? "TRUE" : "";
  669.  
  670. env["DUB_RUN_ARGS"] = (cast(string[])settings.runArgs).map!(escapeShellFileName).join(" ");
  671.  
  672. auto depNames = proj.dependencies.map!((a) => a.name).array();
  673. storeRecursiveInvokations(env, proj.rootPackage.name ~ depNames);
  674. runCommands(commands, env);
  675. }
  676.  
  677. private bool isRecursiveInvocation(string pack)
  678. {
  679. import std.algorithm : canFind, splitter;
  680. import std.process : environment;
  681.  
  682. return environment
  683. .get("DUB_PACKAGES_USED", "")
  684. .splitter(",")
  685. .canFind(pack);
  686. }
  687.  
  688. private void storeRecursiveInvokations(string[string] env, string[] packs)
  689. {
  690. import std.algorithm : canFind, splitter;
  691. import std.range : chain;
  692. import std.process : environment;
  693.  
  694. env["DUB_PACKAGES_USED"] = environment
  695. .get("DUB_PACKAGES_USED", "")
  696. .splitter(",")
  697. .chain(packs)
  698. .join(",");
  699. }