1 /+
2 dub.sdl:
3     name "config"
4     targetPath "generated/dub"
5 +/
6 /**
7 Generates the compiler version, the version printed with `dmd --version`.
8 
9 Outputs a file with the generated version which is imported as a string literal
10 in the compiler source code.
11 */
12 module config;
13 
14 void main(const string[] args)
15 {
16     import std.file : mkdirRecurse, readText;
17     import std.path : buildPath;
18 
19     const outputDirectory = args[1];
20     const versionFile = args[2];
21 
22     version (Posix)
23         const sysConfigDirectory = args[3];
24 
25     mkdirRecurse(outputDirectory);
26     const version_ = generateVersion(versionFile);
27 
28     updateIfChanged(buildPath(outputDirectory, "VERSION"), version_);
29 
30     version (Posix)
31     {
32         const path = buildPath(outputDirectory, "SYSCONFDIR.imp");
33         updateIfChanged(path, sysConfigDirectory);
34     }
35 }
36 
37 /**
38 Generates the version for the compiler.
39 
40 If anything goes wrong in the process the contents of the file
41 `versionFile` will be returned.
42 
43 Params:
44     versionFile = a file containing a version, used for backup if generating the
45         version fails
46 
47 Returns: the generated version, or the content of `versionFile`
48 */
49 string generateVersion(const string versionFile)
50 {
51     import std.process : execute;
52     import std.file : readText;
53     import std.path : dirName;
54     import std..string : strip;
55 
56     enum workDir = __FILE_FULL_PATH__.dirName;
57     const result = execute(["git", "-C", workDir, "describe", "--dirty"]);
58 
59     return result.status == 0 ? result.output.strip : versionFile.readText;
60 }
61 
62 /**
63 Writes given the content to the given file.
64 
65 The content will only be written to the file specified in `path` if that file
66 doesn't exist, or the content of the existing file is different from the given
67 content.
68 
69 This makes sure the timestamp of the file is only updated when the
70 content has changed. This will avoid rebuilding when the content hasn't changed.
71 
72 Params:
73     path = the path to the file to write the content to
74     content = the content to write to the file
75 */
76 void updateIfChanged(const string path, const string content)
77 {
78     import std.file : exists, readText, write;
79 
80     const existingContent = path.exists ? path.readText : "";
81 
82     if (content != existingContent)
83         write(path, content);
84 }