aboutsummaryrefslogtreecommitdiff
path: root/backend/ninja/Ninja.cpp
blob: 73a6dc3009623e873fca2ac21ba763283e7c012e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#include <cstring>
#include "Ninja.hpp"
#include "../../include/FileUtil.hpp"

using namespace std;
using namespace sibs;

namespace backend
{
    string join(const vector<string> &list, const char *joinStr)
    {
        if(list.empty()) return "";
        string result;
        long stringSize = 0;
        long joinStrLen = strlen(joinStr);
        int i = 0;
        for(const string &str : list)
        {
            stringSize += str.size();
            if(!str.empty() && i > 0)
                stringSize += joinStrLen;
            ++i;
        }

        result.reserve(stringSize);

        i = 0;
        for(const string &str : list)
        {
            if(i > 0);
                result += joinStr;
            result += str;
            ++i;
        }

        return move(result);
    }

    struct ExecResult
    {
        string stdout;
        int exitCode;
    };

    Result<ExecResult> exec(const char *cmd, bool print = false)
    {
        char buffer[128];
        string result;
        FILE *pipe = popen(cmd, "r");
        if(!pipe)
            return Result<ExecResult>::Err("popen() failed");

        while(!feof(pipe))
        {
            if(fgets(buffer, 128, pipe))
            {
                result += buffer;
                if(print)
                    printf("%s", buffer);
            }
        }

        ExecResult execResult;
        execResult.stdout = result;
        execResult.exitCode = WEXITSTATUS(pclose(pipe));
        return Result<ExecResult>::Ok(execResult);
    }

    void Ninja::addSourceFile(const char *filepath)
    {
        if(filepath && !containsSourceFile(filepath))
            sourceFiles.emplace_back(filepath);
    }

    bool Ninja::containsSourceFile(const char *filepath) const
    {
        for(const string &sourceFile : sourceFiles)
        {
            if(sourceFile == filepath)
                return true;
        }
        return false;
    }

    Result<bool> Ninja::validatePkgConfigPackageExists(const string &name) const
    {
        string command = "pkg-config --exists '";
        command += name;
        command += "'";
        Result<ExecResult> execResult = exec(command.c_str());
        if(execResult.isErr())
        {
            return Result<bool>::Err(execResult.getErrMsg());
        }

        if(execResult.unwrap().exitCode == 1)
        {
            string errMsg = "Dependency not found: ";
            errMsg += name;
            return Result<bool>::Err(errMsg);
        }
        else if(execResult.unwrap().exitCode == 127)
        {
            return Result<bool>::Err("pkg-config is not installed");
        }
        else if(execResult.unwrap().exitCode != 0)
        {
            string errMsg = "Failed to check if dependency exists, Unknown error, exit code: ";
            errMsg += to_string(execResult.unwrap().exitCode);
            return Result<bool>::Err(errMsg);
        }

        return Result<bool>::Ok(true);
    }

    Result<bool> Ninja::validatePkgConfigPackageVersionAtLeast(const string &name, const string &version) const
    {
        // Use --modversion instead and check if the version returned is newer or equal to dependency version.
        // This way we can output installed version vs expected dependency version
        string command = "pkg-config '--atleast-version=";
        command += version;
        command += "' '";
        command += name;
        command += "'";
        Result<ExecResult> execResult = exec(command.c_str());
        if(execResult.isErr())
        {
            return Result<bool>::Err(execResult.getErrMsg());
        }

        if(execResult.unwrap().exitCode == 1)
        {
            string errMsg = "Dependency ";
            errMsg += name;
            errMsg += " is installed but the version older than ";
            errMsg += version;
            return Result<bool>::Err(errMsg);
        }
        else if(execResult.unwrap().exitCode == 127)
        {
            return Result<bool>::Err("pkg-config is not installed");
        }
        else if(execResult.unwrap().exitCode != 0)
        {
            string errMsg = "Failed to check dependency version, Unknown error, exit code: ";
            errMsg += to_string(execResult.unwrap().exitCode);
            return Result<bool>::Err(errMsg);
        }

        return Result<bool>::Ok(true);
    }

    // TODO: First check if pkg-config is installed. If it's not, only check dependencies that exists in the dependencies sub directory.
    // If pkg-config is installed and dependency is not installed, check in dependencies sub directory.
    Result<string> Ninja::getLinkerFlags(const vector<Dependency> &dependencies) const
    {
        if(dependencies.empty()) return Result<string>::Ok("");

        for(const sibs::Dependency &dependency : dependencies)
        {
            Result<bool> dependencyValidationResult = validatePkgConfigPackageExists(dependency.name);
            if(dependencyValidationResult.isErr())
                return Result<string>::Err(dependencyValidationResult.getErrMsg());

            Result<bool> dependencyVersionValidationResult = validatePkgConfigPackageVersionAtLeast(dependency.name, dependency.version);
            if(dependencyVersionValidationResult.isErr())
                return Result<string>::Err(dependencyVersionValidationResult.getErrMsg());
        }

        string args;
        for(const sibs::Dependency &dependency : dependencies)
        {
            args += " '";
            args += dependency.name;
            args += "'";
        }

        string command = "pkg-config --libs";
        command += args;
        Result<ExecResult> execResult = exec(command.c_str());
        if(execResult.isErr())
            return Result<string>::Err(execResult.getErrMsg());

        if(execResult.unwrap().exitCode == 0)
        {
            return Result<string>::Ok(execResult.unwrap().stdout);
        }
        else if(execResult.unwrap().exitCode == 1)
        {
            // TODO: This shouldn't happen because we check if each dependency is installed before this,
            // but maybe the package is uninstalled somewhere between here...
            // Would be better to recheck if each package is installed here again
            // to know which package was uninstalled
            return Result<string>::Err("Dependencies not found");
        }
        else if(execResult.unwrap().exitCode == 127)
        {
            return Result<string>::Err("pkg-config is not installed");
        }
        else
        {
            string errMsg = "Failed to get dependencies linking flags, Unknown error, exit code: ";
            errMsg += to_string(execResult.unwrap().exitCode);
            return Result<string>::Err(errMsg);
        }
    }

    Result<bool> Ninja::createBuildFile(const std::string &packageName, const vector<Dependency> &dependencies, const char *savePath)
    {
        if(sourceFiles.empty())
            return Result<bool>::Err("No source files provided");

        printf("Package name: %s\n", packageName.c_str());

        string result;
        result.reserve(16384);

        result += "cflags = -Wall -Werror\n\n";

        result += "rule cpp_COMPILER\n";
        result += "  command = ccache c++ $ARGS -c $in -o $out\n\n";

        result += "rule cpp_LINKER\n";
        result += "  command = ccache c++ $ARGS -o $out $in $LINK_ARGS $aliasing\n\n";

        vector<string> objectNames;
        for(const string &sourceFile : sourceFiles)
        {
            //string sourceFileEncoded = sourceFile;
            //replace(sourceFileEncoded, '/', '@');
            string objectName = packageName + "@exe/" + sourceFile + ".o";
            result += "build ";
            result += objectName;
            result += ": cpp_COMPILER ../../";
            result += sourceFile;
            result += "\n";
            result += "  ARGS = '-I" + packageName + "@exe' '-I.' '-I..' '-fdiagnostics-color=always' '-pipe' '-D_FILE_OFFSET_BITS=64' '-Wall' '-Winvalid-pch' '-Wnon-virtual-dtor' '-O0' '-g'\n\n";
            objectNames.emplace_back(objectName);
        }

        Result<string> linkerFlags = getLinkerFlags(dependencies);
        if(linkerFlags.isErr())
            return Result<bool>::Err(linkerFlags.getErrMsg());

        result += "build ";
        result += packageName;
        result += ": cpp_LINKER ";
        result += join(objectNames, " ");
        result += "\n";
        result += "  LINK_ARGS = '-Wl,--no-undefined' '-Wl,--as-needed' ";
        result += linkerFlags.unwrap();
        result += "\n\n";

        bool fileOverwritten = sibs::fileOverwrite(savePath, sibs::StringView(result.data(), result.size()));
        if(!fileOverwritten)
        {
            string errMsg = "Failed to overwrite ninja build file: ";
            errMsg += savePath;
            return Result<bool>::Err(errMsg);
        }

        printf("Created ninja build file: %s\n", savePath);
        return Result<bool>::Ok(true);
    }

    Result<bool> Ninja::build(const char *buildFilePath)
    {
        string command = "ninja -C '";
        command += buildFilePath;
        command += "'";
        Result<ExecResult> execResult = exec(command.c_str(), true);
        if(execResult.isOk())
            return Result<bool>::Ok(true);
        else
            return Result<bool>::Err(execResult.getErrMsg());
    }
}