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 : exists, readText;
53     import std.path : dirName;
54     import std.string : strip;
55 
56     if (versionFile.exists)
57         return versionFile.readText.strip;
58 
59     enum workDir = __FILE_FULL_PATH__.dirName;
60     return execute(["git", "-C", workDir, "describe", "--dirty"]).output.strip;
61 }
62 
63 /**
64 Writes given the content to the given file.
65 
66 The content will only be written to the file specified in `path` if that file
67 doesn't exist, or the content of the existing file is different from the given
68 content.
69 
70 This makes sure the timestamp of the file is only updated when the
71 content has changed. This will avoid rebuilding when the content hasn't changed.
72 
73 Params:
74     path = the path to the file to write the content to
75     content = the content to write to the file
76 */
77 void updateIfChanged(const string path, const string content)
78 {
79     import std.file : exists, readText, write;
80 
81     const existingContent = path.exists ? path.readText : "";
82 
83     if (content != existingContent)
84         write(path, content);
85 }