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(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(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(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 auto filename = settings.compiler.getTargetFileName(buildsettings, settings.platform); 372 auto src = build_path ~ filename; 373 logDiagnostic("Copying target from %s to %s", src.toNativeString(), buildsettings.targetPath); 374 if (!existsFile(NativePath(buildsettings.targetPath))) 375 mkdirRecurse(buildsettings.targetPath); 376 hardLinkFile(src, NativePath(buildsettings.targetPath) ~ filename, true); 377 } 378 379 private bool isUpToDate(NativePath target_path, BuildSettings buildsettings, GeneratorSettings settings, in Package main_pack, in Package[] packages, in NativePath[] additional_dep_files) 380 { 381 import std.datetime; 382 383 auto targetfile = target_path ~ settings.compiler.getTargetFileName(buildsettings, settings.platform); 384 if (!existsFile(targetfile)) { 385 logDiagnostic("Target '%s' doesn't exist, need rebuild.", targetfile.toNativeString()); 386 return false; 387 } 388 auto targettime = getFileInfo(targetfile).timeModified; 389 390 auto allfiles = appender!(string[]); 391 allfiles ~= buildsettings.sourceFiles; 392 allfiles ~= buildsettings.importFiles; 393 allfiles ~= buildsettings.stringImportFiles; 394 allfiles ~= buildsettings.extraDependencyFiles; 395 // TODO: add library files 396 foreach (p; packages) 397 allfiles ~= (p.recipePath != NativePath.init ? p : p.basePackage).recipePath.toNativeString(); 398 foreach (f; additional_dep_files) allfiles ~= f.toNativeString(); 399 bool checkSelectedVersions = !settings.single; 400 if (checkSelectedVersions && main_pack is m_project.rootPackage && m_project.rootPackage.getAllDependencies().length > 0) 401 allfiles ~= (main_pack.path ~ SelectedVersions.defaultFile).toNativeString(); 402 403 foreach (file; allfiles.data) { 404 if (!existsFile(file)) { 405 logDiagnostic("File %s doesn't exist, triggering rebuild.", file); 406 return false; 407 } 408 auto ftime = getFileInfo(file).timeModified; 409 if (ftime > Clock.currTime) 410 logWarn("File '%s' was modified in the future. Please re-save.", file); 411 if (ftime > targettime) { 412 logDiagnostic("File '%s' modified, need rebuild.", file); 413 return false; 414 } 415 } 416 return true; 417 } 418 419 /// Output an unique name to represent the source file. 420 /// Calls with path that resolve to the same file on the filesystem will return the same, 421 /// unless they include different symbolic links (which are not resolved). 422 423 static string pathToObjName(const scope ref BuildPlatform platform, string path) 424 { 425 import std.digest.crc : crc32Of; 426 import std.path : buildNormalizedPath, dirSeparator, relativePath, stripDrive; 427 if (path.endsWith(".d")) path = path[0 .. $-2]; 428 auto ret = buildNormalizedPath(getcwd(), path).replace(dirSeparator, "."); 429 auto idx = ret.lastIndexOf('.'); 430 const objSuffix = getObjSuffix(platform); 431 return idx < 0 ? ret ~ objSuffix : format("%s_%(%02x%)%s", ret[idx+1 .. $], crc32Of(ret[0 .. idx]), objSuffix); 432 } 433 434 /// Compile a single source file (srcFile), and write the object to objName. 435 static string compileUnit(string srcFile, string objName, BuildSettings bs, GeneratorSettings gs) { 436 NativePath tempobj = NativePath(bs.targetPath)~objName; 437 string objPath = tempobj.toNativeString(); 438 bs.libs = null; 439 bs.lflags = null; 440 bs.sourceFiles = [ srcFile ]; 441 bs.targetType = TargetType.object; 442 gs.compiler.prepareBuildSettings(bs, gs.platform, BuildSetting.commandLine); 443 gs.compiler.setTarget(bs, gs.platform, objPath); 444 gs.compiler.invoke(bs, gs.platform, gs.compileCallback); 445 return objPath; 446 } 447 448 private void buildWithCompiler(GeneratorSettings settings, BuildSettings buildsettings) 449 { 450 auto generate_binary = !(buildsettings.options & BuildOption.syntaxOnly); 451 auto is_static_library = buildsettings.targetType == TargetType.staticLibrary || buildsettings.targetType == TargetType.library; 452 453 scope (failure) { 454 logDiagnostic("FAIL %s %s %s" , buildsettings.targetPath, buildsettings.targetName, buildsettings.targetType); 455 auto tpath = getTargetPath(buildsettings, settings); 456 if (generate_binary && existsFile(tpath)) 457 removeFile(tpath); 458 } 459 if (settings.buildMode == BuildMode.singleFile && generate_binary) { 460 import std.parallelism, std.range : walkLength; 461 462 auto lbuildsettings = buildsettings; 463 auto srcs = buildsettings.sourceFiles.filter!(f => !isLinkerFile(settings.platform, f)); 464 auto objs = new string[](srcs.walkLength); 465 466 void compileSource(size_t i, string src) { 467 logInfo("Compiling %s...", src); 468 const objPath = pathToObjName(settings.platform, src); 469 objs[i] = compileUnit(src, objPath, buildsettings, settings); 470 } 471 472 if (settings.parallelBuild) { 473 foreach (i, src; srcs.parallel(1)) compileSource(i, src); 474 } else { 475 foreach (i, src; srcs.array) compileSource(i, src); 476 } 477 478 logInfo("Linking..."); 479 lbuildsettings.sourceFiles = is_static_library ? [] : lbuildsettings.sourceFiles.filter!(f => isLinkerFile(settings.platform, f)).array; 480 settings.compiler.setTarget(lbuildsettings, settings.platform); 481 settings.compiler.prepareBuildSettings(lbuildsettings, settings.platform, BuildSetting.commandLineSeparate|BuildSetting.sourceFiles); 482 settings.compiler.invokeLinker(lbuildsettings, settings.platform, objs, settings.linkCallback); 483 484 // NOTE: separate compile/link is not yet enabled for GDC. 485 } else if (generate_binary && (settings.buildMode == BuildMode.allAtOnce || settings.compiler.name == "gdc" || is_static_library)) { 486 // don't include symbols of dependencies (will be included by the top level target) 487 if (is_static_library) buildsettings.sourceFiles = buildsettings.sourceFiles.filter!(f => !isLinkerFile(settings.platform, f)).array; 488 489 // setup for command line 490 settings.compiler.setTarget(buildsettings, settings.platform); 491 settings.compiler.prepareBuildSettings(buildsettings, settings.platform, BuildSetting.commandLine); 492 493 // invoke the compiler 494 settings.compiler.invoke(buildsettings, settings.platform, settings.compileCallback); 495 } else { 496 // determine path for the temporary object file 497 string tempobjname = buildsettings.targetName ~ getObjSuffix(settings.platform); 498 NativePath tempobj = NativePath(buildsettings.targetPath) ~ tempobjname; 499 500 // setup linker command line 501 auto lbuildsettings = buildsettings; 502 lbuildsettings.sourceFiles = lbuildsettings.sourceFiles.filter!(f => isLinkerFile(settings.platform, f)).array; 503 if (generate_binary) settings.compiler.setTarget(lbuildsettings, settings.platform); 504 settings.compiler.prepareBuildSettings(lbuildsettings, settings.platform, BuildSetting.commandLineSeparate|BuildSetting.sourceFiles); 505 506 // setup compiler command line 507 buildsettings.libs = null; 508 buildsettings.lflags = null; 509 if (generate_binary) buildsettings.addDFlags("-c", "-of"~tempobj.toNativeString()); 510 buildsettings.sourceFiles = buildsettings.sourceFiles.filter!(f => !isLinkerFile(settings.platform, f)).array; 511 512 settings.compiler.prepareBuildSettings(buildsettings, settings.platform, BuildSetting.commandLine); 513 514 settings.compiler.invoke(buildsettings, settings.platform, settings.compileCallback); 515 516 if (generate_binary) { 517 logInfo("Linking..."); 518 settings.compiler.invokeLinker(lbuildsettings, settings.platform, [tempobj.toNativeString()], settings.linkCallback); 519 } 520 } 521 } 522 523 private void runTarget(NativePath exe_file_path, in BuildSettings buildsettings, string[] run_args, GeneratorSettings settings) 524 { 525 if (buildsettings.targetType == TargetType.executable) { 526 auto cwd = NativePath(getcwd()); 527 auto runcwd = cwd; 528 if (buildsettings.workingDirectory.length) { 529 runcwd = NativePath(buildsettings.workingDirectory); 530 if (!runcwd.absolute) runcwd = cwd ~ runcwd; 531 } 532 if (!exe_file_path.absolute) exe_file_path = cwd ~ exe_file_path; 533 runPreRunCommands(m_project.rootPackage, m_project, settings, buildsettings); 534 logInfo("Running %s %s", exe_file_path.relativeTo(runcwd), run_args.join(" ")); 535 if (settings.runCallback) { 536 auto res = execute([ exe_file_path.toNativeString() ] ~ run_args, 537 null, Config.none, size_t.max, runcwd.toNativeString()); 538 settings.runCallback(res.status, res.output); 539 settings.targetExitStatus = res.status; 540 runPostRunCommands(m_project.rootPackage, m_project, settings, buildsettings); 541 } else { 542 auto prg_pid = spawnProcess([ exe_file_path.toNativeString() ] ~ run_args, 543 null, Config.none, runcwd.toNativeString()); 544 auto result = prg_pid.wait(); 545 settings.targetExitStatus = result; 546 runPostRunCommands(m_project.rootPackage, m_project, settings, buildsettings); 547 enforce(result == 0, "Program exited with code "~to!string(result)); 548 } 549 } else 550 enforce(false, "Target is a library. Skipping execution."); 551 } 552 553 private void runPreRunCommands(in Package pack, in Project proj, in GeneratorSettings settings, 554 in BuildSettings buildsettings) 555 { 556 if (buildsettings.preRunCommands.length) { 557 logInfo("Running pre-run commands..."); 558 runBuildCommands(buildsettings.preRunCommands, pack, proj, settings, buildsettings); 559 } 560 } 561 562 private void runPostRunCommands(in Package pack, in Project proj, in GeneratorSettings settings, 563 in BuildSettings buildsettings) 564 { 565 if (buildsettings.postRunCommands.length) { 566 logInfo("Running post-run commands..."); 567 runBuildCommands(buildsettings.postRunCommands, pack, proj, settings, buildsettings); 568 } 569 } 570 571 private void cleanupTemporaries() 572 { 573 foreach_reverse (f; m_temporaryFiles) { 574 try { 575 if (f.endsWithSlash) rmdir(f.toNativeString()); 576 else remove(f.toNativeString()); 577 } catch (Exception e) { 578 logWarn("Failed to remove temporary file '%s': %s", f.toNativeString(), e.msg); 579 logDiagnostic("Full error: %s", e.toString().sanitize); 580 } 581 } 582 m_temporaryFiles = null; 583 } 584 } 585 586 private NativePath getMainSourceFile(in Package prj) 587 { 588 foreach (f; ["source/app.d", "src/app.d", "source/"~prj.name~".d", "src/"~prj.name~".d"]) 589 if (existsFile(prj.path ~ f)) 590 return prj.path ~ f; 591 return prj.path ~ "source/app.d"; 592 } 593 594 private NativePath getTargetPath(const scope ref BuildSettings bs, const scope ref GeneratorSettings settings) 595 { 596 return NativePath(bs.targetPath) ~ settings.compiler.getTargetFileName(bs, settings.platform); 597 } 598 599 private string shrinkPath(NativePath path, NativePath base) 600 { 601 auto orig = path.toNativeString(); 602 if (!path.absolute) return orig; 603 version (Windows) 604 { 605 // avoid relative paths starting with `..\`: https://github.com/dlang/dub/issues/2143 606 if (!path.startsWith(base)) return orig; 607 } 608 auto rel = path.relativeTo(base).toNativeString(); 609 return rel.length < orig.length ? rel : orig; 610 } 611 612 unittest { 613 assert(shrinkPath(NativePath("/foo/bar/baz"), NativePath("/foo")) == NativePath("bar/baz").toNativeString()); 614 version (Windows) 615 assert(shrinkPath(NativePath("/foo/bar/baz"), NativePath("/foo/baz")) == NativePath("/foo/bar/baz").toNativeString()); 616 else 617 assert(shrinkPath(NativePath("/foo/bar/baz"), NativePath("/foo/baz")) == NativePath("../bar/baz").toNativeString()); 618 assert(shrinkPath(NativePath("/foo/bar/baz"), NativePath("/bar/")) == NativePath("/foo/bar/baz").toNativeString()); 619 assert(shrinkPath(NativePath("/foo/bar/baz"), NativePath("/bar/baz")) == NativePath("/foo/bar/baz").toNativeString()); 620 } 621 622 unittest { // issue #1235 - pass no library files to compiler command line when building a static lib 623 import dub.internal.vibecompat.data.json : parseJsonString; 624 import dub.compilers.gdc : GDCCompiler; 625 import dub.platform : determinePlatform; 626 627 version (Windows) auto libfile = "bar.lib"; 628 else auto libfile = "bar.a"; 629 630 auto desc = parseJsonString(`{"name": "test", "targetType": "library", "sourceFiles": ["foo.d", "`~libfile~`"]}`); 631 auto pack = new Package(desc, NativePath("/tmp/fooproject")); 632 auto pman = new PackageManager(pack.path, NativePath("/tmp/foo/"), NativePath("/tmp/foo/"), false); 633 auto prj = new Project(pman, pack); 634 635 final static class TestCompiler : GDCCompiler { 636 override void invoke(in BuildSettings settings, in BuildPlatform platform, void delegate(int, string) output_callback) { 637 assert(!settings.dflags[].any!(f => f.canFind("bar"))); 638 } 639 override void invokeLinker(in BuildSettings settings, in BuildPlatform platform, string[] objects, void delegate(int, string) output_callback) { 640 assert(false); 641 } 642 } 643 644 GeneratorSettings settings; 645 settings.platform = BuildPlatform(determinePlatform(), ["x86"], "gdc", "test", 2075); 646 settings.compiler = new TestCompiler; 647 settings.config = "library"; 648 settings.buildType = "debug"; 649 settings.tempBuild = true; 650 651 auto gen = new BuildGenerator(prj); 652 gen.generate(settings); 653 }