1 /**
2 	Abstract representation of a package description file.
3 
4 	Copyright: © 2012-2014 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, Matthias Dondorff
7 */
8 module dub.recipe.packagerecipe;
9 
10 import dub.compilers.compiler;
11 import dub.compilers.utils : warnOnSpecialCompilerFlags;
12 import dub.dependency;
13 
14 import dub.internal.vibecompat.core.file;
15 import dub.internal.vibecompat.core.log;
16 import dub.internal.vibecompat.inet.url;
17 
18 import std.algorithm : findSplit, sort;
19 import std.array : join, split;
20 import std.exception : enforce;
21 import std.file;
22 import std.range;
23 import std.process : environment;
24 
25 
26 /**
27 	Returns the individual parts of a qualified package name.
28 
29 	Sub qualified package names are lists of package names separated by ":". For
30 	example, "packa:packb:packc" references a package named "packc" that is a
31 	sub package of "packb", which in turn is a sub package of "packa".
32 */
33 string[] getSubPackagePath(string package_name) @safe pure
34 {
35 	return package_name.split(":");
36 }
37 
38 /**
39 	Returns the name of the top level package for a given (sub) package name.
40 
41 	In case of a top level package, the qualified name is returned unmodified.
42 */
43 string getBasePackageName(string package_name) @safe pure
44 {
45 	return package_name.findSplit(":")[0];
46 }
47 
48 /**
49 	Returns the qualified sub package part of the given package name.
50 
51 	This is the part of the package name excluding the base package
52 	name. See also $(D getBasePackageName).
53 */
54 string getSubPackageName(string package_name) @safe pure
55 {
56 	return package_name.findSplit(":")[2];
57 }
58 
59 @safe unittest
60 {
61 	assert(getSubPackagePath("packa:packb:packc") == ["packa", "packb", "packc"]);
62 	assert(getSubPackagePath("pack") == ["pack"]);
63 	assert(getBasePackageName("packa:packb:packc") == "packa");
64 	assert(getBasePackageName("pack") == "pack");
65 	assert(getSubPackageName("packa:packb:packc") == "packb:packc");
66 	assert(getSubPackageName("pack") == "");
67 }
68 
69 /**
70 	Represents the contents of a package recipe file (dub.json/dub.sdl) in an abstract way.
71 
72 	This structure is used to reason about package descriptions in isolation.
73 	For higher level package handling, see the $(D Package) class.
74 */
75 struct PackageRecipe {
76 	string name;
77 	string version_;
78 	string description;
79 	string homepage;
80 	string[] authors;
81 	string copyright;
82 	string license;
83 	string[] ddoxFilterArgs;
84 	string ddoxTool;
85 	BuildSettingsTemplate buildSettings;
86 	ConfigurationInfo[] configurations;
87 	BuildSettingsTemplate[string] buildTypes;
88 
89 	ToolchainRequirements toolchainRequirements;
90 
91 	SubPackage[] subPackages;
92 
93 	inout(ConfigurationInfo) getConfiguration(string name)
94 	inout {
95 		foreach (c; configurations)
96 			if (c.name == name)
97 				return c;
98 		throw new Exception("Unknown configuration: "~name);
99 	}
100 
101 	/** Clones the package recipe recursively.
102 	*/
103 	PackageRecipe clone() const { return .clone(this); }
104 }
105 
106 struct SubPackage
107 {
108 	string path;
109 	PackageRecipe recipe;
110 }
111 
112 /// Describes minimal toolchain requirements
113 struct ToolchainRequirements
114 {
115 	import std.typecons : Tuple, tuple;
116 
117 	/// DUB version requirement
118 	Dependency dub = Dependency.any;
119 	/// D front-end version requirement
120 	Dependency frontend = Dependency.any;
121 	/// DMD version requirement
122 	Dependency dmd = Dependency.any;
123 	/// LDC version requirement
124 	Dependency ldc = Dependency.any;
125 	/// GDC version requirement
126 	Dependency gdc = Dependency.any;
127 
128 	/** Get the list of supported compilers.
129 
130 		Returns:
131 			An array of couples of compiler name and compiler requirement
132 	*/
133 	@property Tuple!(string, Dependency)[] supportedCompilers() const
134 	{
135 		Tuple!(string, Dependency)[] res;
136 		if (dmd != Dependency.invalid) res ~= Tuple!(string, Dependency)("dmd", dmd);
137 		if (ldc != Dependency.invalid) res ~= Tuple!(string, Dependency)("ldc", ldc);
138 		if (gdc != Dependency.invalid) res ~= Tuple!(string, Dependency)("gdc", gdc);
139 		return res;
140 	}
141 
142 	bool empty()
143 	const {
144 		import std.algorithm.searching : all;
145 		return only(dub, frontend, dmd, ldc, gdc)
146 			.all!(r => r == Dependency.any);
147 	}
148 }
149 
150 
151 /// Bundles information about a build configuration.
152 struct ConfigurationInfo {
153 	string name;
154 	string[] platforms;
155 	BuildSettingsTemplate buildSettings;
156 
157 	this(string name, BuildSettingsTemplate build_settings)
158 	{
159 		enforce(!name.empty, "Configuration name is empty.");
160 		this.name = name;
161 		this.buildSettings = build_settings;
162 	}
163 
164 	bool matchesPlatform(in BuildPlatform platform)
165 	const {
166 		if( platforms.empty ) return true;
167 		foreach(p; platforms)
168 			if( platform.matchesSpecification("-"~p) )
169 				return true;
170 		return false;
171 	}
172 }
173 
174 /// This keeps general information about how to build a package.
175 /// It contains functions to create a specific BuildSetting, targeted at
176 /// a certain BuildPlatform.
177 struct BuildSettingsTemplate {
178 	Dependency[string] dependencies;
179 	string systemDependencies;
180 	TargetType targetType = TargetType.autodetect;
181 	string targetPath;
182 	string targetName;
183 	string workingDirectory;
184 	string mainSourceFile;
185 	string[string] subConfigurations;
186 	string[][string] dflags;
187 	string[][string] lflags;
188 	string[][string] libs;
189 	string[][string] sourceFiles;
190 	string[][string] sourcePaths;
191 	string[][string] excludedSourceFiles;
192 	string[][string] copyFiles;
193 	string[][string] extraDependencyFiles;
194 	string[][string] versions;
195 	string[][string] debugVersions;
196 	string[][string] versionFilters;
197 	string[][string] debugVersionFilters;
198 	string[][string] importPaths;
199 	string[][string] stringImportPaths;
200 	string[][string] preGenerateCommands;
201 	string[][string] postGenerateCommands;
202 	string[][string] preBuildCommands;
203 	string[][string] postBuildCommands;
204 	string[][string] preRunCommands;
205 	string[][string] postRunCommands;
206 	BuildRequirements[string] buildRequirements;
207 	BuildOptions[string] buildOptions;
208 
209 
210 	/// Constructs a BuildSettings object from this template.
211 	void getPlatformSettings(ref BuildSettings dst, in BuildPlatform platform, NativePath base_path)
212 	const {
213 		dst.targetType = this.targetType;
214 		if (!this.targetPath.empty) dst.targetPath = this.targetPath;
215 		if (!this.targetName.empty) dst.targetName = this.targetName;
216 		if (!this.workingDirectory.empty) dst.workingDirectory = this.workingDirectory;
217 		if (!this.mainSourceFile.empty) {
218 			auto p = NativePath(this.mainSourceFile);
219 			p.normalize();
220 			dst.mainSourceFile = p.toNativeString();
221 			dst.addSourceFiles(dst.mainSourceFile);
222 		}
223 
224 		string[] collectFiles(in string[][string] paths_map, string pattern)
225 		{
226 			auto files = appender!(string[]);
227 
228 			import dub.project : buildSettingsVars;
229 			import std.typecons : Nullable;
230 
231 			static Nullable!(string[string]) envVarCache;
232 
233 			if (envVarCache.isNull) envVarCache = environment.toAA();
234 
235 			foreach (suffix, paths; paths_map) {
236 				if (!platform.matchesSpecification(suffix))
237 					continue;
238 
239 				foreach (spath; paths) {
240 					enforce(!spath.empty, "Paths must not be empty strings.");
241 					auto path = NativePath(spath);
242 					if (!path.absolute) path = base_path ~ path;
243 					if (!existsFile(path) || !isDir(path.toNativeString())) {
244 						import std.algorithm : any, find;
245 						const hasVar = chain(buildSettingsVars, envVarCache.get.byKey).any!((string var) {
246 							return spath.find("$"~var).length > 0 || spath.find("${"~var~"}").length > 0;
247 						});
248 						if (!hasVar)
249 							logWarn("Invalid source/import path: %s", path.toNativeString());
250 						continue;
251 					}
252 
253 					foreach (d; dirEntries(path.toNativeString(), pattern, SpanMode.depth)) {
254 						import std.path : baseName;
255 						if (baseName(d.name)[0] == '.' || d.isDir) continue;
256 						auto src = NativePath(d.name).relativeTo(base_path);
257 						files ~= src.toNativeString();
258 					}
259 				}
260 			}
261 
262 			return files.data;
263 		}
264 
265  		// collect source files
266 		dst.addSourceFiles(collectFiles(sourcePaths, "*.d"));
267 		auto sourceFiles = dst.sourceFiles.sort();
268 
269  		// collect import files and remove sources
270 		import std.algorithm : copy, setDifference;
271 
272 		auto importFiles = collectFiles(importPaths, "*.{d,di}").sort();
273 		immutable nremoved = importFiles.setDifference(sourceFiles).copy(importFiles.release).length;
274 		importFiles = importFiles[0 .. $ - nremoved];
275 		dst.addImportFiles(importFiles.release);
276 
277 		dst.addStringImportFiles(collectFiles(stringImportPaths, "*"));
278 
279 		getPlatformSetting!("dflags", "addDFlags")(dst, platform);
280 		getPlatformSetting!("lflags", "addLFlags")(dst, platform);
281 		getPlatformSetting!("libs", "addLibs")(dst, platform);
282 		getPlatformSetting!("sourceFiles", "addSourceFiles")(dst, platform);
283 		getPlatformSetting!("excludedSourceFiles", "removeSourceFiles")(dst, platform);
284 		getPlatformSetting!("copyFiles", "addCopyFiles")(dst, platform);
285 		getPlatformSetting!("extraDependencyFiles", "addExtraDependencyFiles")(dst, platform);
286 		getPlatformSetting!("versions", "addVersions")(dst, platform);
287 		getPlatformSetting!("debugVersions", "addDebugVersions")(dst, platform);
288 		getPlatformSetting!("versionFilters", "addVersionFilters")(dst, platform);
289 		getPlatformSetting!("debugVersionFilters", "addDebugVersionFilters")(dst, platform);
290 		getPlatformSetting!("importPaths", "addImportPaths")(dst, platform);
291 		getPlatformSetting!("stringImportPaths", "addStringImportPaths")(dst, platform);
292 		getPlatformSetting!("preGenerateCommands", "addPreGenerateCommands")(dst, platform);
293 		getPlatformSetting!("postGenerateCommands", "addPostGenerateCommands")(dst, platform);
294 		getPlatformSetting!("preBuildCommands", "addPreBuildCommands")(dst, platform);
295 		getPlatformSetting!("postBuildCommands", "addPostBuildCommands")(dst, platform);
296 		getPlatformSetting!("preRunCommands", "addPreRunCommands")(dst, platform);
297 		getPlatformSetting!("postRunCommands", "addPostRunCommands")(dst, platform);
298 		getPlatformSetting!("buildRequirements", "addRequirements")(dst, platform);
299 		getPlatformSetting!("buildOptions", "addOptions")(dst, platform);
300 	}
301 
302 	void getPlatformSetting(string name, string addname)(ref BuildSettings dst, in BuildPlatform platform)
303 	const {
304 		foreach(suffix, values; __traits(getMember, this, name)){
305 			if( platform.matchesSpecification(suffix) )
306 				__traits(getMember, dst, addname)(values);
307 		}
308 	}
309 
310 	void warnOnSpecialCompilerFlags(string package_name, string config_name)
311 	{
312 		auto nodef = false;
313 		auto noprop = false;
314 		foreach (req; this.buildRequirements) {
315 			if (req & BuildRequirement.noDefaultFlags) nodef = true;
316 			if (req & BuildRequirement.relaxProperties) noprop = true;
317 		}
318 
319 		if (noprop) {
320 			logWarn(`Warning: "buildRequirements": ["relaxProperties"] is deprecated and is now the default behavior. Note that the -property switch will probably be removed in future versions of DMD.`);
321 			logWarn("");
322 		}
323 
324 		if (nodef) {
325 			logWarn("Warning: This package uses the \"noDefaultFlags\" build requirement. Please use only for development purposes and not for released packages.");
326 			logWarn("");
327 		} else {
328 			string[] all_dflags;
329 			BuildOptions all_options;
330 			foreach (flags; this.dflags) all_dflags ~= flags;
331 			foreach (options; this.buildOptions) all_options |= options;
332 			.warnOnSpecialCompilerFlags(all_dflags, all_options, package_name, config_name);
333 		}
334 	}
335 }
336 
337 package(dub) void checkPlatform(in ref ToolchainRequirements tr, BuildPlatform platform, string package_name)
338 {
339 	import dub.compilers.utils : dmdLikeVersionToSemverLike;
340 	import std.algorithm.iteration : map;
341 	import std.format : format;
342 
343 	string compilerver;
344 	Dependency compilerspec;
345 
346 	switch (platform.compiler) {
347 		default:
348 			compilerspec = Dependency.any;
349 			compilerver = "0.0.0";
350 			break;
351 		case "dmd":
352 			compilerspec = tr.dmd;
353 			compilerver = platform.compilerVersion.length
354 				? dmdLikeVersionToSemverLike(platform.compilerVersion)
355 				: "0.0.0";
356 			break;
357 		case "ldc":
358 			compilerspec = tr.ldc;
359 			compilerver = platform.compilerVersion;
360 			if (!compilerver.length) compilerver = "0.0.0";
361 			break;
362 		case "gdc":
363 			compilerspec = tr.gdc;
364 			compilerver = platform.compilerVersion;
365 			if (!compilerver.length) compilerver = "0.0.0";
366 			break;
367 	}
368 
369 	enforce(compilerspec != Dependency.invalid,
370 		format(
371 			"Installed %s %s is not supported by %s. Supported compiler(s):\n%s",
372 			platform.compiler, platform.compilerVersion, package_name,
373 			tr.supportedCompilers.map!((cs) {
374 				auto str = "  - " ~ cs[0];
375 				if (cs[1] != Dependency.any) str ~= ": " ~ cs[1].toString();
376 				return str;
377 			}).join("\n")
378 		)
379 	);
380 
381 	enforce(compilerspec.matches(compilerver),
382 		format(
383 			"Installed %s-%s does not comply with %s compiler requirement: %s %s\n" ~
384 			"Please consider upgrading your installation.",
385 			platform.compiler, platform.compilerVersion,
386 			package_name, platform.compiler, compilerspec
387 		)
388 	);
389 
390 	enforce(tr.frontend.matches(dmdLikeVersionToSemverLike(platform.frontendVersionString)),
391 		format(
392 			"Installed %s-%s with frontend %s does not comply with %s frontend requirement: %s\n" ~
393 			"Please consider upgrading your installation.",
394 			platform.compiler, platform.compilerVersion,
395 			platform.frontendVersionString, package_name, tr.frontend
396 		)
397 	);
398 }
399 
400 package bool addRequirement(ref ToolchainRequirements req, string name, string value)
401 {
402 	switch (name) {
403 		default: return false;
404 		case "dub": req.dub = parseDependency(value); break;
405 		case "frontend": req.frontend = parseDMDDependency(value); break;
406 		case "ldc": req.ldc = parseDependency(value); break;
407 		case "gdc": req.gdc = parseDependency(value); break;
408 		case "dmd": req.dmd = parseDMDDependency(value); break;
409 	}
410 	return true;
411 }
412 
413 private static Dependency parseDependency(string dep)
414 {
415 	if (dep == "no") return Dependency.invalid;
416 	return Dependency(dep);
417 }
418 
419 private static Dependency parseDMDDependency(string dep)
420 {
421 	import dub.compilers.utils : dmdLikeVersionToSemverLike;
422 	import dub.dependency : Dependency;
423 	import std.algorithm : map, splitter;
424 	import std.array : join;
425 
426 	if (dep == "no") return Dependency.invalid;
427 	return dep
428 		.splitter(' ')
429 		.map!(r => dmdLikeVersionToSemverLike(r))
430 		.join(' ')
431 		.Dependency;
432 }
433 
434 private T clone(T)(ref const(T) val)
435 {
436 	import std.traits : isSomeString, isDynamicArray, isAssociativeArray, isBasicType, ValueType;
437 
438 	static if (is(T == immutable)) return val;
439 	else static if (isBasicType!T) return val;
440 	else static if (isDynamicArray!T) {
441 		alias V = typeof(T.init[0]);
442 		static if (is(V == immutable)) return val;
443 		else {
444 			T ret = new V[val.length];
445 			foreach (i, ref f; val)
446 				ret[i] = clone!V(f);
447 			return ret;
448 		}
449 	} else static if (isAssociativeArray!T) {
450 		alias V = ValueType!T;
451 		T ret;
452 		foreach (k, ref f; val)
453 			ret[k] = clone!V(f);
454 		return ret;
455 	} else static if (is(T == struct)) {
456 		T ret;
457 		foreach (i, M; typeof(T.tupleof))
458 			ret.tupleof[i] = clone!M(val.tupleof[i]);
459 		return ret;
460 	} else static assert(false, "Unsupported type: "~T.stringof);
461 }
462 
463 unittest { // issue #1407 - duplicate main source file
464 	{
465 		BuildSettingsTemplate t;
466 		t.mainSourceFile = "./foo.d";
467 		t.sourceFiles[""] = ["foo.d"];
468 		BuildSettings bs;
469 		t.getPlatformSettings(bs, BuildPlatform.init, NativePath("/"));
470 		assert(bs.sourceFiles == ["foo.d"]);
471 	}
472 
473 	version (Windows) {{
474 		BuildSettingsTemplate t;
475 		t.mainSourceFile = "src/foo.d";
476 		t.sourceFiles[""] = ["src\\foo.d"];
477 		BuildSettings bs;
478 		t.getPlatformSettings(bs, BuildPlatform.init, NativePath("/"));
479 		assert(bs.sourceFiles == ["src\\foo.d"]);
480 	}}
481 }