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 				[buildsettings.environments, buildsettings.buildEnvironments, buildsettings.postBuildEnvironments]);
180 		}
181 
182 		return cached;
183 	}
184 
185 	private bool performCachedBuild(GeneratorSettings settings, BuildSettings buildsettings, in Package pack, string config,
186 		string build_id, in Package[] packages, in NativePath[] additional_dep_files, out NativePath target_binary_path)
187 	{
188 		auto cwd = NativePath(getcwd());
189 
190 		NativePath target_path;
191 		if (settings.tempBuild) {
192 			string packageName = pack.basePackage is null ? pack.name : pack.basePackage.name;
193 			m_tempTargetExecutablePath = target_path = getTempDir() ~ format(".dub/build/%s-%s/%s/", packageName, pack.version_, build_id);
194 		}
195 		else target_path = pack.path ~ format(".dub/build/%s/", build_id);
196 
197 		if (!settings.force && isUpToDate(target_path, buildsettings, settings, pack, packages, additional_dep_files)) {
198 			logInfo("%s %s: target for configuration \"%s\" is up to date.", pack.name, pack.version_, config);
199 			logDiagnostic("Using existing build in %s.", target_path.toNativeString());
200 			target_binary_path = target_path ~ settings.compiler.getTargetFileName(buildsettings, settings.platform);
201 			if (!settings.tempBuild)
202 				copyTargetFile(target_path, buildsettings, settings);
203 			return true;
204 		}
205 
206 		if (!isWritableDir(target_path, true)) {
207 			if (!settings.tempBuild)
208 				logInfo("Build directory %s is not writable. Falling back to direct build in the system's temp folder.", target_path.relativeTo(cwd).toNativeString());
209 			performDirectBuild(settings, buildsettings, pack, config, target_path);
210 			return false;
211 		}
212 
213 		logInfo("%s %s: building configuration \"%s\"...", pack.name, pack.version_, config);
214 
215 		if( buildsettings.preBuildCommands.length ){
216 			logInfo("Running pre-build commands...");
217 			runBuildCommands(buildsettings.preBuildCommands, pack, m_project, settings, buildsettings,
218 				[buildsettings.environments, buildsettings.buildEnvironments, buildsettings.preBuildEnvironments]);
219 		}
220 
221 		// override target path
222 		auto cbuildsettings = buildsettings;
223 		cbuildsettings.targetPath = shrinkPath(target_path, cwd);
224 		buildWithCompiler(settings, cbuildsettings);
225 		target_binary_path = getTargetPath(cbuildsettings, settings);
226 
227 		if (!settings.tempBuild)
228 			copyTargetFile(target_path, buildsettings, settings);
229 
230 		return false;
231 	}
232 
233 	private void performRDMDBuild(GeneratorSettings settings, ref BuildSettings buildsettings, in Package pack, string config, out NativePath target_path)
234 	{
235 		auto cwd = NativePath(getcwd());
236 		//Added check for existence of [AppNameInPackagejson].d
237 		//If exists, use that as the starting file.
238 		NativePath mainsrc;
239 		if (buildsettings.mainSourceFile.length) {
240 			mainsrc = NativePath(buildsettings.mainSourceFile);
241 			if (!mainsrc.absolute) mainsrc = pack.path ~ mainsrc;
242 		} else {
243 			mainsrc = getMainSourceFile(pack);
244 			logWarn(`Package has no "mainSourceFile" defined. Using best guess: %s`, mainsrc.relativeTo(pack.path).toNativeString());
245 		}
246 
247 		// do not pass all source files to RDMD, only the main source file
248 		buildsettings.sourceFiles = buildsettings.sourceFiles.filter!(s => !s.endsWith(".d"))().array();
249 		settings.compiler.prepareBuildSettings(buildsettings, settings.platform, BuildSetting.commandLine);
250 
251 		auto generate_binary = !buildsettings.dflags.canFind("-o-");
252 
253 		// Create start script, which will be used by the calling bash/cmd script.
254 		// build "rdmd --force %DFLAGS% -I%~dp0..\source -Jviews -Isource @deps.txt %LIBS% source\app.d" ~ application arguments
255 		// or with "/" instead of "\"
256 		bool tmp_target = false;
257 		if (generate_binary) {
258 			if (settings.tempBuild || (settings.run && !isWritableDir(NativePath(buildsettings.targetPath), true))) {
259 				import std.random;
260 				auto rnd = to!string(uniform(uint.min, uint.max)) ~ "-";
261 				auto tmpdir = getTempDir()~".rdmd/source/";
262 				buildsettings.targetPath = tmpdir.toNativeString();
263 				buildsettings.targetName = rnd ~ buildsettings.targetName;
264 				m_temporaryFiles ~= tmpdir;
265 				tmp_target = true;
266 			}
267 			target_path = getTargetPath(buildsettings, settings);
268 			settings.compiler.setTarget(buildsettings, settings.platform);
269 		}
270 
271 		logDiagnostic("Application output name is '%s'", settings.compiler.getTargetFileName(buildsettings, settings.platform));
272 
273 		string[] flags = ["--build-only", "--compiler="~settings.platform.compilerBinary];
274 		if (settings.force) flags ~= "--force";
275 		flags ~= buildsettings.dflags;
276 		flags ~= mainsrc.relativeTo(cwd).toNativeString();
277 
278 		if (buildsettings.preBuildCommands.length){
279 			logInfo("Running pre-build commands...");
280 			runCommands(buildsettings.preBuildCommands);
281 		}
282 
283 		logInfo("%s %s: building configuration \"%s\"...", pack.name, pack.version_, config);
284 
285 		logInfo("Running rdmd...");
286 		logDiagnostic("rdmd %s", join(flags, " "));
287 		auto rdmd_pid = spawnProcess("rdmd" ~ flags);
288 		auto result = rdmd_pid.wait();
289 		enforce(result == 0, "Build command failed with exit code "~to!string(result));
290 
291 		if (tmp_target) {
292 			m_temporaryFiles ~= target_path;
293 			foreach (f; buildsettings.copyFiles)
294 				m_temporaryFiles ~= NativePath(buildsettings.targetPath).parentPath ~ NativePath(f).head;
295 		}
296 	}
297 
298 	private void performDirectBuild(GeneratorSettings settings, ref BuildSettings buildsettings, in Package pack, string config, out NativePath target_path)
299 	{
300 		auto cwd = NativePath(getcwd());
301 		auto generate_binary = !(buildsettings.options & BuildOption.syntaxOnly);
302 
303 		// make file paths relative to shrink the command line
304 		foreach (ref f; buildsettings.sourceFiles) {
305 			auto fp = NativePath(f);
306 			if( fp.absolute ) fp = fp.relativeTo(cwd);
307 			f = fp.toNativeString();
308 		}
309 
310 		logInfo("%s %s: building configuration \"%s\"...", pack.name, pack.version_, config);
311 
312 		// make all target/import paths relative
313 		string makeRelative(string path) {
314 			auto p = NativePath(path);
315 			// storing in a separate temprary to work around #601
316 			auto prel = p.absolute ? p.relativeTo(cwd) : p;
317 			return prel.toNativeString();
318 		}
319 		buildsettings.targetPath = makeRelative(buildsettings.targetPath);
320 		foreach (ref p; buildsettings.importPaths) p = makeRelative(p);
321 		foreach (ref p; buildsettings.stringImportPaths) p = makeRelative(p);
322 
323 		bool is_temp_target = false;
324 		if (generate_binary) {
325 			if (settings.tempBuild || (settings.run && !isWritableDir(NativePath(buildsettings.targetPath), true))) {
326 				import std.random;
327 				auto rnd = to!string(uniform(uint.min, uint.max));
328 				auto tmppath = getTempDir()~("dub/"~rnd~"/");
329 				buildsettings.targetPath = tmppath.toNativeString();
330 				m_temporaryFiles ~= tmppath;
331 				is_temp_target = true;
332 			}
333 			target_path = getTargetPath(buildsettings, settings);
334 		}
335 
336 		if( buildsettings.preBuildCommands.length ){
337 			logInfo("Running pre-build commands...");
338 			runBuildCommands(buildsettings.preBuildCommands, pack, m_project, settings, buildsettings,
339 				[buildsettings.environments, buildsettings.buildEnvironments, buildsettings.preBuildEnvironments]);
340 		}
341 
342 		buildWithCompiler(settings, buildsettings);
343 
344 		if (is_temp_target) {
345 			m_temporaryFiles ~= target_path;
346 			foreach (f; buildsettings.copyFiles)
347 				m_temporaryFiles ~= NativePath(buildsettings.targetPath).parentPath ~ NativePath(f).head;
348 		}
349 	}
350 
351 	private string computeBuildID(string config, in BuildSettings buildsettings, GeneratorSettings settings)
352 	{
353 		const(string[])[] hashing = [
354 			buildsettings.versions,
355 			buildsettings.debugVersions,
356 			buildsettings.dflags,
357 			buildsettings.lflags,
358 			buildsettings.stringImportPaths,
359 			buildsettings.importPaths,
360 			settings.platform.architecture,
361 			[
362 				(cast(uint)buildsettings.options).to!string,
363 				settings.platform.compilerBinary,
364 				settings.platform.compiler,
365 				settings.platform.compilerVersion,
366 			],
367 		];
368 
369 		return computeBuildName(config, settings, hashing);
370 	}
371 
372 	private void copyTargetFile(NativePath build_path, BuildSettings buildsettings, GeneratorSettings settings)
373 	{
374 		auto filename = settings.compiler.getTargetFileName(buildsettings, settings.platform);
375 		auto src = build_path ~ filename;
376 		logDiagnostic("Copying target from %s to %s", src.toNativeString(), buildsettings.targetPath);
377 		if (!existsFile(NativePath(buildsettings.targetPath)))
378 			mkdirRecurse(buildsettings.targetPath);
379 		hardLinkFile(src, NativePath(buildsettings.targetPath) ~ filename, true);
380 	}
381 
382 	private bool isUpToDate(NativePath target_path, BuildSettings buildsettings, GeneratorSettings settings, in Package main_pack, in Package[] packages, in NativePath[] additional_dep_files)
383 	{
384 		import std.datetime;
385 
386 		auto targetfile = target_path ~ settings.compiler.getTargetFileName(buildsettings, settings.platform);
387 		if (!existsFile(targetfile)) {
388 			logDiagnostic("Target '%s' doesn't exist, need rebuild.", targetfile.toNativeString());
389 			return false;
390 		}
391 		auto targettime = getFileInfo(targetfile).timeModified;
392 
393 		auto allfiles = appender!(string[]);
394 		allfiles ~= buildsettings.sourceFiles;
395 		allfiles ~= buildsettings.importFiles;
396 		allfiles ~= buildsettings.stringImportFiles;
397 		allfiles ~= buildsettings.extraDependencyFiles;
398 		// TODO: add library files
399 		foreach (p; packages)
400 			allfiles ~= (p.recipePath != NativePath.init ? p : p.basePackage).recipePath.toNativeString();
401 		foreach (f; additional_dep_files) allfiles ~= f.toNativeString();
402 		bool checkSelectedVersions = !settings.single;
403 		if (checkSelectedVersions && main_pack is m_project.rootPackage && m_project.rootPackage.getAllDependencies().length > 0)
404 			allfiles ~= (main_pack.path ~ SelectedVersions.defaultFile).toNativeString();
405 
406 		foreach (file; allfiles.data) {
407 			if (!existsFile(file)) {
408 				logDiagnostic("File %s doesn't exist, triggering rebuild.", file);
409 				return false;
410 			}
411 			auto ftime = getFileInfo(file).timeModified;
412 			if (ftime > Clock.currTime)
413 				logWarn("File '%s' was modified in the future. Please re-save.", file);
414 			if (ftime > targettime) {
415 				logDiagnostic("File '%s' modified, need rebuild.", file);
416 				return false;
417 			}
418 		}
419 		return true;
420 	}
421 
422 	/// Output an unique name to represent the source file.
423 	/// Calls with path that resolve to the same file on the filesystem will return the same,
424 	/// unless they include different symbolic links (which are not resolved).
425 
426 	static string pathToObjName(const scope ref BuildPlatform platform, string path)
427 	{
428 		import std.digest.crc : crc32Of;
429 		import std.path : buildNormalizedPath, dirSeparator, relativePath, stripDrive;
430 		if (path.endsWith(".d")) path = path[0 .. $-2];
431 		auto ret = buildNormalizedPath(getcwd(), path).replace(dirSeparator, ".");
432 		auto idx = ret.lastIndexOf('.');
433 		const objSuffix = getObjSuffix(platform);
434 		return idx < 0 ? ret ~ objSuffix : format("%s_%(%02x%)%s", ret[idx+1 .. $], crc32Of(ret[0 .. idx]), objSuffix);
435 	}
436 
437 	/// Compile a single source file (srcFile), and write the object to objName.
438 	static string compileUnit(string srcFile, string objName, BuildSettings bs, GeneratorSettings gs) {
439 		NativePath tempobj = NativePath(bs.targetPath)~objName;
440 		string objPath = tempobj.toNativeString();
441 		bs.libs = null;
442 		bs.lflags = null;
443 		bs.sourceFiles = [ srcFile ];
444 		bs.targetType = TargetType.object;
445 		gs.compiler.prepareBuildSettings(bs, gs.platform, BuildSetting.commandLine);
446 		gs.compiler.setTarget(bs, gs.platform, objPath);
447 		gs.compiler.invoke(bs, gs.platform, gs.compileCallback);
448 		return objPath;
449 	}
450 
451 	private void buildWithCompiler(GeneratorSettings settings, BuildSettings buildsettings)
452 	{
453 		auto generate_binary = !(buildsettings.options & BuildOption.syntaxOnly);
454 		auto is_static_library = buildsettings.targetType == TargetType.staticLibrary || buildsettings.targetType == TargetType.library;
455 
456 		scope (failure) {
457 			logDiagnostic("FAIL %s %s %s" , buildsettings.targetPath, buildsettings.targetName, buildsettings.targetType);
458 			auto tpath = getTargetPath(buildsettings, settings);
459 			if (generate_binary && existsFile(tpath))
460 				removeFile(tpath);
461 		}
462 		if (settings.buildMode == BuildMode.singleFile && generate_binary) {
463 			import std.parallelism, std.range : walkLength;
464 
465 			auto lbuildsettings = buildsettings;
466 			auto srcs = buildsettings.sourceFiles.filter!(f => !isLinkerFile(settings.platform, f));
467 			auto objs = new string[](srcs.walkLength);
468 
469 			void compileSource(size_t i, string src) {
470 				logInfo("Compiling %s...", src);
471 				const objPath = pathToObjName(settings.platform, src);
472 				objs[i] = compileUnit(src, objPath, buildsettings, settings);
473 			}
474 
475 			if (settings.parallelBuild) {
476 				foreach (i, src; srcs.parallel(1)) compileSource(i, src);
477 			} else {
478 				foreach (i, src; srcs.array) compileSource(i, src);
479 			}
480 
481 			logInfo("Linking...");
482 			lbuildsettings.sourceFiles = is_static_library ? [] : lbuildsettings.sourceFiles.filter!(f => isLinkerFile(settings.platform, f)).array;
483 			settings.compiler.setTarget(lbuildsettings, settings.platform);
484 			settings.compiler.prepareBuildSettings(lbuildsettings, settings.platform, BuildSetting.commandLineSeparate|BuildSetting.sourceFiles);
485 			settings.compiler.invokeLinker(lbuildsettings, settings.platform, objs, settings.linkCallback);
486 
487 		// NOTE: separate compile/link is not yet enabled for GDC.
488 		} else if (generate_binary && (settings.buildMode == BuildMode.allAtOnce || settings.compiler.name == "gdc" || is_static_library)) {
489 			// don't include symbols of dependencies (will be included by the top level target)
490 			if (is_static_library) buildsettings.sourceFiles = buildsettings.sourceFiles.filter!(f => !isLinkerFile(settings.platform, f)).array;
491 
492 			// setup for command line
493 			settings.compiler.setTarget(buildsettings, settings.platform);
494 			settings.compiler.prepareBuildSettings(buildsettings, settings.platform, BuildSetting.commandLine);
495 
496 			// invoke the compiler
497 			settings.compiler.invoke(buildsettings, settings.platform, settings.compileCallback);
498 		} else {
499 			// determine path for the temporary object file
500 			string tempobjname = buildsettings.targetName ~ getObjSuffix(settings.platform);
501 			NativePath tempobj = NativePath(buildsettings.targetPath) ~ tempobjname;
502 
503 			// setup linker command line
504 			auto lbuildsettings = buildsettings;
505 			lbuildsettings.sourceFiles = lbuildsettings.sourceFiles.filter!(f => isLinkerFile(settings.platform, f)).array;
506 			if (generate_binary) settings.compiler.setTarget(lbuildsettings, settings.platform);
507 			settings.compiler.prepareBuildSettings(lbuildsettings, settings.platform, BuildSetting.commandLineSeparate|BuildSetting.sourceFiles);
508 
509 			// setup compiler command line
510 			buildsettings.libs = null;
511 			buildsettings.lflags = null;
512 			if (generate_binary) buildsettings.addDFlags("-c", "-of"~tempobj.toNativeString());
513 			buildsettings.sourceFiles = buildsettings.sourceFiles.filter!(f => !isLinkerFile(settings.platform, f)).array;
514 
515 			settings.compiler.prepareBuildSettings(buildsettings, settings.platform, BuildSetting.commandLine);
516 
517 			settings.compiler.invoke(buildsettings, settings.platform, settings.compileCallback);
518 
519 			if (generate_binary) {
520 				logInfo("Linking...");
521 				settings.compiler.invokeLinker(lbuildsettings, settings.platform, [tempobj.toNativeString()], settings.linkCallback);
522 			}
523 		}
524 	}
525 
526 	private void runTarget(NativePath exe_file_path, in BuildSettings buildsettings, string[] run_args, GeneratorSettings settings)
527 	{
528 		if (buildsettings.targetType == TargetType.executable) {
529 			auto cwd = NativePath(getcwd());
530 			auto runcwd = cwd;
531 			if (buildsettings.workingDirectory.length) {
532 				runcwd = NativePath(buildsettings.workingDirectory);
533 				if (!runcwd.absolute) runcwd = cwd ~ runcwd;
534 			}
535 			if (!exe_file_path.absolute) exe_file_path = cwd ~ exe_file_path;
536 			runPreRunCommands(m_project.rootPackage, m_project, settings, buildsettings);
537 			logInfo("Running %s %s", exe_file_path.relativeTo(runcwd), run_args.join(" "));
538 			string[string] env;
539 			foreach (aa; [buildsettings.environments, buildsettings.runEnvironments])
540 				foreach (k, v; aa)
541 					env[k] = v;
542 			if (settings.runCallback) {
543 				auto res = execute([ exe_file_path.toNativeString() ] ~ run_args,
544 						   env, Config.none, size_t.max, runcwd.toNativeString());
545 				settings.runCallback(res.status, res.output);
546 				settings.targetExitStatus = res.status;
547 				runPostRunCommands(m_project.rootPackage, m_project, settings, buildsettings);
548 			} else {
549 				auto prg_pid = spawnProcess([ exe_file_path.toNativeString() ] ~ run_args,
550 								env, Config.none, runcwd.toNativeString());
551 				auto result = prg_pid.wait();
552 				settings.targetExitStatus = result;
553 				runPostRunCommands(m_project.rootPackage, m_project, settings, buildsettings);
554 				enforce(result == 0, "Program exited with code "~to!string(result));
555 			}
556 		} else
557 			enforce(false, "Target is a library. Skipping execution.");
558 	}
559 
560 	private void runPreRunCommands(in Package pack, in Project proj, in GeneratorSettings settings,
561 		in BuildSettings buildsettings)
562 	{
563 		if (buildsettings.preRunCommands.length) {
564 			logInfo("Running pre-run commands...");
565 			runBuildCommands(buildsettings.preRunCommands, pack, proj, settings, buildsettings,
566 				[buildsettings.environments, buildsettings.runEnvironments, buildsettings.preRunEnvironments]);
567 		}
568 	}
569 
570 	private void runPostRunCommands(in Package pack, in Project proj, in GeneratorSettings settings,
571 		in BuildSettings buildsettings)
572 	{
573 		if (buildsettings.postRunCommands.length) {
574 			logInfo("Running post-run commands...");
575 			runBuildCommands(buildsettings.postRunCommands, pack, proj, settings, buildsettings,
576 				[buildsettings.environments, buildsettings.runEnvironments, buildsettings.postRunEnvironments]);
577 		}
578 	}
579 
580 	private void cleanupTemporaries()
581 	{
582 		foreach_reverse (f; m_temporaryFiles) {
583 			try {
584 				if (f.endsWithSlash) rmdir(f.toNativeString());
585 				else remove(f.toNativeString());
586 			} catch (Exception e) {
587 				logWarn("Failed to remove temporary file '%s': %s", f.toNativeString(), e.msg);
588 				logDiagnostic("Full error: %s", e.toString().sanitize);
589 			}
590 		}
591 		m_temporaryFiles = null;
592 	}
593 }
594 
595 private NativePath getMainSourceFile(in Package prj)
596 {
597 	foreach (f; ["source/app.d", "src/app.d", "source/"~prj.name~".d", "src/"~prj.name~".d"])
598 		if (existsFile(prj.path ~ f))
599 			return prj.path ~ f;
600 	return prj.path ~ "source/app.d";
601 }
602 
603 private NativePath getTargetPath(const scope ref BuildSettings bs, const scope ref GeneratorSettings settings)
604 {
605 	return NativePath(bs.targetPath) ~ settings.compiler.getTargetFileName(bs, settings.platform);
606 }
607 
608 private string shrinkPath(NativePath path, NativePath base)
609 {
610 	auto orig = path.toNativeString();
611 	if (!path.absolute) return orig;
612 	version (Windows)
613 	{
614 		// avoid relative paths starting with `..\`: https://github.com/dlang/dub/issues/2143
615 		if (!path.startsWith(base)) return orig;
616 	}
617 	auto rel = path.relativeTo(base).toNativeString();
618 	return rel.length < orig.length ? rel : orig;
619 }
620 
621 unittest {
622 	assert(shrinkPath(NativePath("/foo/bar/baz"), NativePath("/foo")) == NativePath("bar/baz").toNativeString());
623 	version (Windows)
624 		assert(shrinkPath(NativePath("/foo/bar/baz"), NativePath("/foo/baz")) == NativePath("/foo/bar/baz").toNativeString());
625 	else
626 		assert(shrinkPath(NativePath("/foo/bar/baz"), NativePath("/foo/baz")) == NativePath("../bar/baz").toNativeString());
627 	assert(shrinkPath(NativePath("/foo/bar/baz"), NativePath("/bar/")) == NativePath("/foo/bar/baz").toNativeString());
628 	assert(shrinkPath(NativePath("/foo/bar/baz"), NativePath("/bar/baz")) == NativePath("/foo/bar/baz").toNativeString());
629 }
630 
631 unittest { // issue #1235 - pass no library files to compiler command line when building a static lib
632 	import dub.internal.vibecompat.data.json : parseJsonString;
633 	import dub.compilers.gdc : GDCCompiler;
634 	import dub.platform : determinePlatform;
635 
636 	version (Windows) auto libfile = "bar.lib";
637 	else auto libfile = "bar.a";
638 
639 	auto desc = parseJsonString(`{"name": "test", "targetType": "library", "sourceFiles": ["foo.d", "`~libfile~`"]}`);
640 	auto pack = new Package(desc, NativePath("/tmp/fooproject"));
641 	auto pman = new PackageManager(pack.path, NativePath("/tmp/foo/"), NativePath("/tmp/foo/"), false);
642 	auto prj = new Project(pman, pack);
643 
644 	final static class TestCompiler : GDCCompiler {
645 		override void invoke(in BuildSettings settings, in BuildPlatform platform, void delegate(int, string) output_callback) {
646 			assert(!settings.dflags[].any!(f => f.canFind("bar")));
647 		}
648 		override void invokeLinker(in BuildSettings settings, in BuildPlatform platform, string[] objects, void delegate(int, string) output_callback) {
649 			assert(false);
650 		}
651 	}
652 
653 	GeneratorSettings settings;
654 	settings.platform = BuildPlatform(determinePlatform(), ["x86"], "gdc", "test", 2075);
655 	settings.compiler = new TestCompiler;
656 	settings.config = "library";
657 	settings.buildType = "debug";
658 	settings.tempBuild = true;
659 
660 	auto gen = new BuildGenerator(prj);
661 	gen.generate(settings);
662 }