1 /** 2 Generator for direct compiler builds. 3 4 Copyright: © 2013-2013 rejectedsoftware e.K. 5 License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. 6 Authors: Sönke Ludwig 7 */ 8 module dub.generators.build; 9 10 import dub.compilers.compiler; 11 import dub.compilers.utils; 12 import dub.generators.generator; 13 import dub.internal.utils; 14 import dub.internal.vibecompat.core.file; 15 import dub.internal.vibecompat.core.log; 16 import dub.internal.vibecompat.inet.path; 17 import dub.package_; 18 import dub.packagemanager; 19 import dub.project; 20 21 import std.algorithm; 22 import std.array; 23 import std.conv; 24 import std.exception; 25 import std.file; 26 import std.process; 27 import std.string; 28 import std.encoding : sanitize; 29 30 string getObjSuffix(const scope ref BuildPlatform platform) 31 { 32 return platform.platform.canFind("windows") ? ".obj" : ".o"; 33 } 34 35 string computeBuildName(string config, GeneratorSettings settings, const string[][] hashing...) 36 { 37 import std.digest; 38 import std.digest.md; 39 40 MD5 hash; 41 hash.start(); 42 void addHash(in string[] strings...) { foreach (s; strings) { hash.put(cast(ubyte[])s); hash.put(0); } hash.put(0); } 43 foreach(strings; hashing) 44 addHash(strings); 45 auto hashstr = hash.finish().toHexString().idup; 46 47 return format("%s-%s-%s-%s-%s_v%s-%s", config, settings.buildType, 48 settings.platform.platform.join("."), 49 settings.platform.architecture.join("."), 50 settings.platform.compiler, settings.platform.compilerVersion, hashstr); 51 } 52 53 class BuildGenerator : ProjectGenerator { 54 private { 55 PackageManager m_packageMan; 56 NativePath[] m_temporaryFiles; 57 } 58 59 this(Project project) 60 { 61 super(project); 62 m_packageMan = project.packageManager; 63 } 64 65 override void generateTargets(GeneratorSettings settings, in TargetInfo[string] targets) 66 { 67 scope (exit) cleanupTemporaries(); 68 69 void checkPkgRequirements(const(Package) pkg) 70 { 71 const tr = pkg.recipe.toolchainRequirements; 72 tr.checkPlatform(settings.platform, pkg.name); 73 } 74 75 checkPkgRequirements(m_project.rootPackage); 76 foreach (pkg; m_project.dependencies) 77 checkPkgRequirements(pkg); 78 79 auto root_ti = targets[m_project.rootPackage.name]; 80 81 enforce(!(settings.rdmd && root_ti.buildSettings.targetType == TargetType.none), 82 "Building package with target type \"none\" with rdmd is not supported yet."); 83 84 logInfo("Performing \"%s\" build using %s for %-(%s, %).", 85 settings.buildType, settings.platform.compilerBinary, settings.platform.architecture); 86 87 bool any_cached = false; 88 89 NativePath[string] target_paths; 90 91 bool[string] visited; 92 void buildTargetRec(string target) 93 { 94 if (target in visited) return; 95 visited[target] = true; 96 97 auto ti = targets[target]; 98 99 foreach (dep; ti.dependencies) 100 buildTargetRec(dep); 101 102 NativePath[] additional_dep_files; 103 auto bs = ti.buildSettings.dup; 104 foreach (ldep; ti.linkDependencies) { 105 if (bs.targetType != TargetType.staticLibrary && !(bs.options & BuildOption.syntaxOnly)) { 106 bs.addSourceFiles(target_paths[ldep].toNativeString()); 107 } else { 108 additional_dep_files ~= target_paths[ldep]; 109 } 110 } 111 NativePath tpath; 112 if (bs.targetType != TargetType.none) 113 if (buildTarget(settings, bs, ti.pack, ti.config, ti.packages, additional_dep_files, tpath)) 114 any_cached = true; 115 target_paths[target] = tpath; 116 } 117 118 // build all targets 119 if (settings.rdmd || root_ti.buildSettings.targetType == TargetType.staticLibrary) { 120 // RDMD always builds everything at once and static libraries don't need their 121 // dependencies to be built 122 NativePath tpath; 123 buildTarget(settings, root_ti.buildSettings.dup, m_project.rootPackage, root_ti.config, root_ti.packages, null, tpath); 124 } else { 125 buildTargetRec(m_project.rootPackage.name); 126 127 if (any_cached) { 128 logInfo("To force a rebuild of up-to-date targets, run again with --force."); 129 } 130 } 131 } 132 133 override void performPostGenerateActions(GeneratorSettings settings, in TargetInfo[string] targets) 134 { 135 // run the generated executable 136 auto buildsettings = targets[m_project.rootPackage.name].buildSettings.dup; 137 if (settings.run && !(buildsettings.options & BuildOption.syntaxOnly)) { 138 NativePath exe_file_path; 139 if (m_tempTargetExecutablePath.empty) 140 exe_file_path = getTargetPath(buildsettings, settings); 141 else 142 exe_file_path = m_tempTargetExecutablePath ~ settings.compiler.getTargetFileName(buildsettings, settings.platform); 143 runTarget(exe_file_path, buildsettings, settings.runArgs, settings); 144 } 145 } 146 147 private bool buildTarget(GeneratorSettings settings, BuildSettings buildsettings, in Package pack, string config, in Package[] packages, in NativePath[] additional_dep_files, out NativePath target_path) 148 { 149 auto cwd = NativePath(getcwd()); 150 bool generate_binary = !(buildsettings.options & BuildOption.syntaxOnly); 151 152 auto build_id = computeBuildID(config, buildsettings, settings); 153 154 // make all paths relative to shrink the command line 155 string makeRelative(string path) { return shrinkPath(NativePath(path), cwd); } 156 foreach (ref f; buildsettings.sourceFiles) f = makeRelative(f); 157 foreach (ref p; buildsettings.importPaths) p = makeRelative(p); 158 foreach (ref p; buildsettings.stringImportPaths) p = makeRelative(p); 159 160 // perform the actual build 161 bool cached = false; 162 if (settings.rdmd) performRDMDBuild(settings, buildsettings, pack, config, target_path); 163 else if (settings.direct || !generate_binary) performDirectBuild(settings, buildsettings, pack, config, target_path); 164 else cached = performCachedBuild(settings, buildsettings, pack, config, build_id, packages, additional_dep_files, target_path); 165 166 // HACK: cleanup dummy doc files, we shouldn't specialize on buildType 167 // here and the compiler shouldn't need dummy doc output. 168 if (settings.buildType == "ddox") { 169 if ("__dummy.html".exists) 170 removeFile("__dummy.html"); 171 if ("__dummy_docs".exists) 172 rmdirRecurse("__dummy_docs"); 173 } 174 175 // run post-build commands 176 if (!cached && buildsettings.postBuildCommands.length) { 177 logInfo("Running post-build commands..."); 178 runBuildCommands(CommandType.postBuild, buildsettings.postBuildCommands, pack, m_project, settings, buildsettings); 179 } 180 181 return cached; 182 } 183 184 private bool performCachedBuild(GeneratorSettings settings, BuildSettings buildsettings, in Package pack, string config, 185 string build_id, in Package[] packages, in NativePath[] additional_dep_files, out NativePath target_binary_path) 186 { 187 auto cwd = NativePath(getcwd()); 188 189 NativePath target_path; 190 if (settings.tempBuild) { 191 string packageName = pack.basePackage is null ? pack.name : pack.basePackage.name; 192 m_tempTargetExecutablePath = target_path = getTempDir() ~ format(".dub/build/%s-%s/%s/", packageName, pack.version_, build_id); 193 } 194 else target_path = pack.path ~ format(".dub/build/%s/", build_id); 195 196 if (!settings.force && isUpToDate(target_path, buildsettings, settings, pack, packages, additional_dep_files)) { 197 logInfo("%s %s: target for configuration \"%s\" is up to date.", pack.name, pack.version_, config); 198 logDiagnostic("Using existing build in %s.", target_path.toNativeString()); 199 target_binary_path = target_path ~ settings.compiler.getTargetFileName(buildsettings, settings.platform); 200 if (!settings.tempBuild) 201 copyTargetFile(target_path, buildsettings, settings); 202 return true; 203 } 204 205 if (!isWritableDir(target_path, true)) { 206 if (!settings.tempBuild) 207 logInfo("Build directory %s is not writable. Falling back to direct build in the system's temp folder.", target_path.relativeTo(cwd).toNativeString()); 208 performDirectBuild(settings, buildsettings, pack, config, target_path); 209 return false; 210 } 211 212 logInfo("%s %s: building configuration \"%s\"...", pack.name, pack.version_, config); 213 214 if( buildsettings.preBuildCommands.length ){ 215 logInfo("Running pre-build commands..."); 216 runBuildCommands(CommandType.preBuild, buildsettings.preBuildCommands, pack, m_project, settings, buildsettings); 217 } 218 219 // override target path 220 auto cbuildsettings = buildsettings; 221 cbuildsettings.targetPath = shrinkPath(target_path, cwd); 222 buildWithCompiler(settings, cbuildsettings); 223 target_binary_path = getTargetPath(cbuildsettings, settings); 224 225 if (!settings.tempBuild) 226 copyTargetFile(target_path, buildsettings, settings); 227 228 return false; 229 } 230 231 private void performRDMDBuild(GeneratorSettings settings, ref BuildSettings buildsettings, in Package pack, string config, out NativePath target_path) 232 { 233 auto cwd = NativePath(getcwd()); 234 //Added check for existence of [AppNameInPackagejson].d 235 //If exists, use that as the starting file. 236 NativePath mainsrc; 237 if (buildsettings.mainSourceFile.length) { 238 mainsrc = NativePath(buildsettings.mainSourceFile); 239 if (!mainsrc.absolute) mainsrc = pack.path ~ mainsrc; 240 } else { 241 mainsrc = getMainSourceFile(pack); 242 logWarn(`Package has no "mainSourceFile" defined. Using best guess: %s`, mainsrc.relativeTo(pack.path).toNativeString()); 243 } 244 245 // do not pass all source files to RDMD, only the main source file 246 buildsettings.sourceFiles = buildsettings.sourceFiles.filter!(s => !s.endsWith(".d"))().array(); 247 settings.compiler.prepareBuildSettings(buildsettings, settings.platform, BuildSetting.commandLine); 248 249 auto generate_binary = !buildsettings.dflags.canFind("-o-"); 250 251 // Create start script, which will be used by the calling bash/cmd script. 252 // build "rdmd --force %DFLAGS% -I%~dp0..\source -Jviews -Isource @deps.txt %LIBS% source\app.d" ~ application arguments 253 // or with "/" instead of "\" 254 bool tmp_target = false; 255 if (generate_binary) { 256 if (settings.tempBuild || (settings.run && !isWritableDir(NativePath(buildsettings.targetPath), true))) { 257 import std.random; 258 auto rnd = to!string(uniform(uint.min, uint.max)) ~ "-"; 259 auto tmpdir = getTempDir()~".rdmd/source/"; 260 buildsettings.targetPath = tmpdir.toNativeString(); 261 buildsettings.targetName = rnd ~ buildsettings.targetName; 262 m_temporaryFiles ~= tmpdir; 263 tmp_target = true; 264 } 265 target_path = getTargetPath(buildsettings, settings); 266 settings.compiler.setTarget(buildsettings, settings.platform); 267 } 268 269 logDiagnostic("Application output name is '%s'", settings.compiler.getTargetFileName(buildsettings, settings.platform)); 270 271 string[] flags = ["--build-only", "--compiler="~settings.platform.compilerBinary]; 272 if (settings.force) flags ~= "--force"; 273 flags ~= buildsettings.dflags; 274 flags ~= mainsrc.relativeTo(cwd).toNativeString(); 275 276 if (buildsettings.preBuildCommands.length){ 277 logInfo("Running pre-build commands..."); 278 runCommands(buildsettings.preBuildCommands); 279 } 280 281 logInfo("%s %s: building configuration \"%s\"...", pack.name, pack.version_, config); 282 283 logInfo("Running rdmd..."); 284 logDiagnostic("rdmd %s", join(flags, " ")); 285 auto rdmd_pid = spawnProcess("rdmd" ~ flags); 286 auto result = rdmd_pid.wait(); 287 enforce(result == 0, "Build command failed with exit code "~to!string(result)); 288 289 if (tmp_target) { 290 m_temporaryFiles ~= target_path; 291 foreach (f; buildsettings.copyFiles) 292 m_temporaryFiles ~= NativePath(buildsettings.targetPath).parentPath ~ NativePath(f).head; 293 } 294 } 295 296 private void performDirectBuild(GeneratorSettings settings, ref BuildSettings buildsettings, in Package pack, string config, out NativePath target_path) 297 { 298 auto cwd = NativePath(getcwd()); 299 auto generate_binary = !(buildsettings.options & BuildOption.syntaxOnly); 300 301 // make file paths relative to shrink the command line 302 foreach (ref f; buildsettings.sourceFiles) { 303 auto fp = NativePath(f); 304 if( fp.absolute ) fp = fp.relativeTo(cwd); 305 f = fp.toNativeString(); 306 } 307 308 logInfo("%s %s: building configuration \"%s\"...", pack.name, pack.version_, config); 309 310 // make all target/import paths relative 311 string makeRelative(string path) { 312 auto p = NativePath(path); 313 // storing in a separate temprary to work around #601 314 auto prel = p.absolute ? p.relativeTo(cwd) : p; 315 return prel.toNativeString(); 316 } 317 buildsettings.targetPath = makeRelative(buildsettings.targetPath); 318 foreach (ref p; buildsettings.importPaths) p = makeRelative(p); 319 foreach (ref p; buildsettings.stringImportPaths) p = makeRelative(p); 320 321 bool is_temp_target = false; 322 if (generate_binary) { 323 if (settings.tempBuild || (settings.run && !isWritableDir(NativePath(buildsettings.targetPath), true))) { 324 import std.random; 325 auto rnd = to!string(uniform(uint.min, uint.max)); 326 auto tmppath = getTempDir()~("dub/"~rnd~"/"); 327 buildsettings.targetPath = tmppath.toNativeString(); 328 m_temporaryFiles ~= tmppath; 329 is_temp_target = true; 330 } 331 target_path = getTargetPath(buildsettings, settings); 332 } 333 334 if( buildsettings.preBuildCommands.length ){ 335 logInfo("Running pre-build commands..."); 336 runBuildCommands(CommandType.preBuild, buildsettings.preBuildCommands, pack, m_project, settings, buildsettings); 337 } 338 339 buildWithCompiler(settings, buildsettings); 340 341 if (is_temp_target) { 342 m_temporaryFiles ~= target_path; 343 foreach (f; buildsettings.copyFiles) 344 m_temporaryFiles ~= NativePath(buildsettings.targetPath).parentPath ~ NativePath(f).head; 345 } 346 } 347 348 private string computeBuildID(string config, in BuildSettings buildsettings, GeneratorSettings settings) 349 { 350 const(string[])[] hashing = [ 351 buildsettings.versions, 352 buildsettings.debugVersions, 353 buildsettings.dflags, 354 buildsettings.lflags, 355 buildsettings.stringImportPaths, 356 buildsettings.importPaths, 357 settings.platform.architecture, 358 [ 359 (cast(uint)buildsettings.options).to!string, 360 settings.platform.compilerBinary, 361 settings.platform.compiler, 362 settings.platform.compilerVersion, 363 ], 364 ]; 365 366 return computeBuildName(config, settings, hashing); 367 } 368 369 private void copyTargetFile(NativePath build_path, BuildSettings buildsettings, GeneratorSettings settings) 370 { 371 if (!existsFile(NativePath(buildsettings.targetPath))) 372 mkdirRecurse(buildsettings.targetPath); 373 374 string[] filenames = [ 375 settings.compiler.getTargetFileName(buildsettings, settings.platform) 376 ]; 377 378 // Windows: add .pdb if found 379 const tt = buildsettings.targetType; 380 if ((tt == TargetType.executable || tt == TargetType.dynamicLibrary) && 381 settings.platform.platform.canFind("windows")) 382 { 383 import std.path : setExtension; 384 const pdbFilename = filenames[0].setExtension(".pdb"); 385 if (existsFile(build_path ~ pdbFilename)) 386 filenames ~= pdbFilename; 387 } 388 389 foreach (filename; filenames) 390 { 391 auto src = build_path ~ filename; 392 logDiagnostic("Copying target from %s to %s", src.toNativeString(), buildsettings.targetPath); 393 hardLinkFile(src, NativePath(buildsettings.targetPath) ~ filename, true); 394 } 395 } 396 397 private bool isUpToDate(NativePath target_path, BuildSettings buildsettings, GeneratorSettings settings, in Package main_pack, in Package[] packages, in NativePath[] additional_dep_files) 398 { 399 import std.datetime; 400 401 auto targetfile = target_path ~ settings.compiler.getTargetFileName(buildsettings, settings.platform); 402 if (!existsFile(targetfile)) { 403 logDiagnostic("Target '%s' doesn't exist, need rebuild.", targetfile.toNativeString()); 404 return false; 405 } 406 auto targettime = getFileInfo(targetfile).timeModified; 407 408 auto allfiles = appender!(string[]); 409 allfiles ~= buildsettings.sourceFiles; 410 allfiles ~= buildsettings.importFiles; 411 allfiles ~= buildsettings.stringImportFiles; 412 allfiles ~= buildsettings.extraDependencyFiles; 413 // TODO: add library files 414 foreach (p; packages) 415 allfiles ~= (p.recipePath != NativePath.init ? p : p.basePackage).recipePath.toNativeString(); 416 foreach (f; additional_dep_files) allfiles ~= f.toNativeString(); 417 bool checkSelectedVersions = !settings.single; 418 if (checkSelectedVersions && main_pack is m_project.rootPackage && m_project.rootPackage.getAllDependencies().length > 0) 419 allfiles ~= (main_pack.path ~ SelectedVersions.defaultFile).toNativeString(); 420 421 foreach (file; allfiles.data) { 422 if (!existsFile(file)) { 423 logDiagnostic("File %s doesn't exist, triggering rebuild.", file); 424 return false; 425 } 426 auto ftime = getFileInfo(file).timeModified; 427 if (ftime > Clock.currTime) 428 logWarn("File '%s' was modified in the future. Please re-save.", file); 429 if (ftime > targettime) { 430 logDiagnostic("File '%s' modified, need rebuild.", file); 431 return false; 432 } 433 } 434 return true; 435 } 436 437 /// Output an unique name to represent the source file. 438 /// Calls with path that resolve to the same file on the filesystem will return the same, 439 /// unless they include different symbolic links (which are not resolved). 440 441 static string pathToObjName(const scope ref BuildPlatform platform, string path) 442 { 443 import std.digest.crc : crc32Of; 444 import std.path : buildNormalizedPath, dirSeparator, relativePath, stripDrive; 445 if (path.endsWith(".d")) path = path[0 .. $-2]; 446 auto ret = buildNormalizedPath(getcwd(), path).replace(dirSeparator, "."); 447 auto idx = ret.lastIndexOf('.'); 448 const objSuffix = getObjSuffix(platform); 449 return idx < 0 ? ret ~ objSuffix : format("%s_%(%02x%)%s", ret[idx+1 .. $], crc32Of(ret[0 .. idx]), objSuffix); 450 } 451 452 /// Compile a single source file (srcFile), and write the object to objName. 453 static string compileUnit(string srcFile, string objName, BuildSettings bs, GeneratorSettings gs) { 454 NativePath tempobj = NativePath(bs.targetPath)~objName; 455 string objPath = tempobj.toNativeString(); 456 bs.libs = null; 457 bs.lflags = null; 458 bs.sourceFiles = [ srcFile ]; 459 bs.targetType = TargetType.object; 460 gs.compiler.prepareBuildSettings(bs, gs.platform, BuildSetting.commandLine); 461 gs.compiler.setTarget(bs, gs.platform, objPath); 462 gs.compiler.invoke(bs, gs.platform, gs.compileCallback); 463 return objPath; 464 } 465 466 private void buildWithCompiler(GeneratorSettings settings, BuildSettings buildsettings) 467 { 468 auto generate_binary = !(buildsettings.options & BuildOption.syntaxOnly); 469 auto is_static_library = buildsettings.targetType == TargetType.staticLibrary || buildsettings.targetType == TargetType.library; 470 471 scope (failure) { 472 logDiagnostic("FAIL %s %s %s" , buildsettings.targetPath, buildsettings.targetName, buildsettings.targetType); 473 auto tpath = getTargetPath(buildsettings, settings); 474 if (generate_binary && existsFile(tpath)) 475 removeFile(tpath); 476 } 477 if (settings.buildMode == BuildMode.singleFile && generate_binary) { 478 import std.parallelism, std.range : walkLength; 479 480 auto lbuildsettings = buildsettings; 481 auto srcs = buildsettings.sourceFiles.filter!(f => !isLinkerFile(settings.platform, f)); 482 auto objs = new string[](srcs.walkLength); 483 484 void compileSource(size_t i, string src) { 485 logInfo("Compiling %s...", src); 486 const objPath = pathToObjName(settings.platform, src); 487 objs[i] = compileUnit(src, objPath, buildsettings, settings); 488 } 489 490 if (settings.parallelBuild) { 491 foreach (i, src; srcs.parallel(1)) compileSource(i, src); 492 } else { 493 foreach (i, src; srcs.array) compileSource(i, src); 494 } 495 496 logInfo("Linking..."); 497 lbuildsettings.sourceFiles = is_static_library ? [] : lbuildsettings.sourceFiles.filter!(f => isLinkerFile(settings.platform, f)).array; 498 settings.compiler.setTarget(lbuildsettings, settings.platform); 499 settings.compiler.prepareBuildSettings(lbuildsettings, settings.platform, BuildSetting.commandLineSeparate|BuildSetting.sourceFiles); 500 settings.compiler.invokeLinker(lbuildsettings, settings.platform, objs, settings.linkCallback); 501 502 // NOTE: separate compile/link is not yet enabled for GDC. 503 } else if (generate_binary && (settings.buildMode == BuildMode.allAtOnce || settings.compiler.name == "gdc" || is_static_library)) { 504 // don't include symbols of dependencies (will be included by the top level target) 505 if (is_static_library) buildsettings.sourceFiles = buildsettings.sourceFiles.filter!(f => !isLinkerFile(settings.platform, f)).array; 506 507 // setup for command line 508 settings.compiler.setTarget(buildsettings, settings.platform); 509 settings.compiler.prepareBuildSettings(buildsettings, settings.platform, BuildSetting.commandLine); 510 511 // invoke the compiler 512 settings.compiler.invoke(buildsettings, settings.platform, settings.compileCallback); 513 } else { 514 // determine path for the temporary object file 515 string tempobjname = buildsettings.targetName ~ getObjSuffix(settings.platform); 516 NativePath tempobj = NativePath(buildsettings.targetPath) ~ tempobjname; 517 518 // setup linker command line 519 auto lbuildsettings = buildsettings; 520 lbuildsettings.sourceFiles = lbuildsettings.sourceFiles.filter!(f => isLinkerFile(settings.platform, f)).array; 521 if (generate_binary) settings.compiler.setTarget(lbuildsettings, settings.platform); 522 settings.compiler.prepareBuildSettings(lbuildsettings, settings.platform, BuildSetting.commandLineSeparate|BuildSetting.sourceFiles); 523 524 // setup compiler command line 525 buildsettings.libs = null; 526 buildsettings.lflags = null; 527 if (generate_binary) buildsettings.addDFlags("-c", "-of"~tempobj.toNativeString()); 528 buildsettings.sourceFiles = buildsettings.sourceFiles.filter!(f => !isLinkerFile(settings.platform, f)).array; 529 530 settings.compiler.prepareBuildSettings(buildsettings, settings.platform, BuildSetting.commandLine); 531 532 settings.compiler.invoke(buildsettings, settings.platform, settings.compileCallback); 533 534 if (generate_binary) { 535 logInfo("Linking..."); 536 settings.compiler.invokeLinker(lbuildsettings, settings.platform, [tempobj.toNativeString()], settings.linkCallback); 537 } 538 } 539 } 540 541 private void runTarget(NativePath exe_file_path, in BuildSettings buildsettings, string[] run_args, GeneratorSettings settings) 542 { 543 if (buildsettings.targetType == TargetType.executable) { 544 auto cwd = NativePath(getcwd()); 545 auto runcwd = cwd; 546 if (buildsettings.workingDirectory.length) { 547 runcwd = NativePath(buildsettings.workingDirectory); 548 if (!runcwd.absolute) runcwd = cwd ~ runcwd; 549 } 550 if (!exe_file_path.absolute) exe_file_path = cwd ~ exe_file_path; 551 runPreRunCommands(m_project.rootPackage, m_project, settings, buildsettings); 552 logInfo("Running %s %s", exe_file_path.relativeTo(runcwd), run_args.join(" ")); 553 string[string] env; 554 foreach (aa; [buildsettings.environments, buildsettings.runEnvironments]) 555 foreach (k, v; aa) 556 env[k] = v; 557 if (settings.runCallback) { 558 auto res = execute([ exe_file_path.toNativeString() ] ~ run_args, 559 env, Config.none, size_t.max, runcwd.toNativeString()); 560 settings.runCallback(res.status, res.output); 561 settings.targetExitStatus = res.status; 562 runPostRunCommands(m_project.rootPackage, m_project, settings, buildsettings); 563 } else { 564 auto prg_pid = spawnProcess([ exe_file_path.toNativeString() ] ~ run_args, 565 env, Config.none, runcwd.toNativeString()); 566 auto result = prg_pid.wait(); 567 settings.targetExitStatus = result; 568 runPostRunCommands(m_project.rootPackage, m_project, settings, buildsettings); 569 enforce(result == 0, "Program exited with code "~to!string(result)); 570 } 571 } else 572 enforce(false, "Target is a library. Skipping execution."); 573 } 574 575 private void runPreRunCommands(in Package pack, in Project proj, in GeneratorSettings settings, 576 in BuildSettings buildsettings) 577 { 578 if (buildsettings.preRunCommands.length) { 579 logInfo("Running pre-run commands..."); 580 runBuildCommands(CommandType.preRun, buildsettings.preRunCommands, pack, proj, settings, buildsettings); 581 } 582 } 583 584 private void runPostRunCommands(in Package pack, in Project proj, in GeneratorSettings settings, 585 in BuildSettings buildsettings) 586 { 587 if (buildsettings.postRunCommands.length) { 588 logInfo("Running post-run commands..."); 589 runBuildCommands(CommandType.postRun, buildsettings.postRunCommands, pack, proj, settings, buildsettings); 590 } 591 } 592 593 private void cleanupTemporaries() 594 { 595 foreach_reverse (f; m_temporaryFiles) { 596 try { 597 if (f.endsWithSlash) rmdir(f.toNativeString()); 598 else remove(f.toNativeString()); 599 } catch (Exception e) { 600 logWarn("Failed to remove temporary file '%s': %s", f.toNativeString(), e.msg); 601 logDiagnostic("Full error: %s", e.toString().sanitize); 602 } 603 } 604 m_temporaryFiles = null; 605 } 606 } 607 608 private NativePath getMainSourceFile(in Package prj) 609 { 610 foreach (f; ["source/app.d", "src/app.d", "source/"~prj.name~".d", "src/"~prj.name~".d"]) 611 if (existsFile(prj.path ~ f)) 612 return prj.path ~ f; 613 return prj.path ~ "source/app.d"; 614 } 615 616 private NativePath getTargetPath(const scope ref BuildSettings bs, const scope ref GeneratorSettings settings) 617 { 618 return NativePath(bs.targetPath) ~ settings.compiler.getTargetFileName(bs, settings.platform); 619 } 620 621 private string shrinkPath(NativePath path, NativePath base) 622 { 623 auto orig = path.toNativeString(); 624 if (!path.absolute) return orig; 625 version (Windows) 626 { 627 // avoid relative paths starting with `..\`: https://github.com/dlang/dub/issues/2143 628 if (!path.startsWith(base)) return orig; 629 } 630 auto rel = path.relativeTo(base).toNativeString(); 631 return rel.length < orig.length ? rel : orig; 632 } 633 634 unittest { 635 assert(shrinkPath(NativePath("/foo/bar/baz"), NativePath("/foo")) == NativePath("bar/baz").toNativeString()); 636 version (Windows) 637 assert(shrinkPath(NativePath("/foo/bar/baz"), NativePath("/foo/baz")) == NativePath("/foo/bar/baz").toNativeString()); 638 else 639 assert(shrinkPath(NativePath("/foo/bar/baz"), NativePath("/foo/baz")) == NativePath("../bar/baz").toNativeString()); 640 assert(shrinkPath(NativePath("/foo/bar/baz"), NativePath("/bar/")) == NativePath("/foo/bar/baz").toNativeString()); 641 assert(shrinkPath(NativePath("/foo/bar/baz"), NativePath("/bar/baz")) == NativePath("/foo/bar/baz").toNativeString()); 642 } 643 644 unittest { // issue #1235 - pass no library files to compiler command line when building a static lib 645 import dub.internal.vibecompat.data.json : parseJsonString; 646 import dub.compilers.gdc : GDCCompiler; 647 import dub.platform : determinePlatform; 648 649 version (Windows) auto libfile = "bar.lib"; 650 else auto libfile = "bar.a"; 651 652 auto desc = parseJsonString(`{"name": "test", "targetType": "library", "sourceFiles": ["foo.d", "`~libfile~`"]}`); 653 auto pack = new Package(desc, NativePath("/tmp/fooproject")); 654 auto pman = new PackageManager(pack.path, NativePath("/tmp/foo/"), NativePath("/tmp/foo/"), false); 655 auto prj = new Project(pman, pack); 656 657 final static class TestCompiler : GDCCompiler { 658 override void invoke(in BuildSettings settings, in BuildPlatform platform, void delegate(int, string) output_callback) { 659 assert(!settings.dflags[].any!(f => f.canFind("bar"))); 660 } 661 override void invokeLinker(in BuildSettings settings, in BuildPlatform platform, string[] objects, void delegate(int, string) output_callback) { 662 assert(false); 663 } 664 } 665 666 GeneratorSettings settings; 667 settings.platform = BuildPlatform(determinePlatform(), ["x86"], "gdc", "test", 2075); 668 settings.compiler = new TestCompiler; 669 settings.config = "library"; 670 settings.buildType = "debug"; 671 settings.tempBuild = true; 672 673 auto gen = new BuildGenerator(prj); 674 gen.generate(settings); 675 }