aboutsummaryrefslogtreecommitdiff
path: root/src/CmakeModule.cpp
blob: 8606a42c303e0a1fcd60a374e0e372f33d80ae80 (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
#include "../include/CmakeModule.hpp"
#include "../include/Exec.hpp"
#include "../include/GlobalLib.hpp"
#include "../include/PkgConfig.hpp"

#if OS_FAMILY == OS_FAMILY_POSIX
#define nprintf printf
#else
#define nprintf wprintf
#endif

using namespace std;

namespace sibs
{
    Result<bool> CmakeModule::compile(const SibsConfig &config, const FileString &buildPath, LinkerFlagCallbackFunc staticLinkerFlagCallbackFunc, LinkerFlagCallbackFunc dynamicLinkerFlagCallbackFunc, GlobalIncludeDirCallbackFunc globalIncludeDirCallback)
    {
        Result<FileString> globalLibDirResult = getHomeDir();
        if (!globalLibDirResult)
            return Result<bool>::Err(globalLibDirResult);
        FileString globalLibDir = globalLibDirResult.unwrap();
        globalLibDir += TINYDIR_STRING("/.sibs/lib");
        Result<bool> createGlobalLibDirResult = createDirectoryRecursive(globalLibDir.c_str());
        if(createGlobalLibDirResult.isErr())
            return createGlobalLibDirResult;
        
// TODO: This code was copied from Ninja.cpp, convert it to work for CMake
#if OS_TYPE == OS_TYPE_LINUX
        // TODO: Allow configuring default linking flags. Maybe have `package.useThreads = false` to disable this flag
        string allLinkerFlags = "-pthread";
#else
        string allLinkerFlags = "";
#endif

#if 0
        // TODO: Somehow check loading order, because it has to be correct to work.. Or does it for dynamic libraries?
        // Anyways it's required for static libraries (especially on Windows)
        for (const string &binaryDependency : binaryDependencies)
        {
            allLinkerFlags += " ";
            allLinkerFlags += binaryDependency;
        }
#endif
        if (!staticLinkerFlagCallbackFunc || (config.getPackageType() == PackageType::DYNAMIC || config.getPackageType() == PackageType::LIBRARY))
        {
            staticLinkerFlagCallbackFunc = [&allLinkerFlags](const string &linkerFlag)
            {
                allLinkerFlags += " ";
                allLinkerFlags += linkerFlag;
            };
        }

        // TODO: If project contains no source files, then we shouldn't override this function
        dynamicLinkerFlagCallbackFunc = [&allLinkerFlags](const string &linkerFlag)
        {
            allLinkerFlags += " ";
            allLinkerFlags += linkerFlag;
        };
        
        // TODO: Create a cmake module that contains library/include path for the dependencies (https://cmake.org/Wiki/CMake:How_To_Find_Libraries).
        // Modify the project CMakeLists.txt and add: list(APPEND CMAKE_MODULE_PATH "PathToDependenciesCmakeModulesGoesHere").
        // CMakeLists.txt may contain: set(CMAKE_MODULE_PATH "PathToModules"). This needs to be replaced with list append,
        // otherwise our added module path is replaced.
        // It may work to do like vcpkg instead - to use -DCMAKE_TOOLCHAIN_FILE program argument to specify path to script (https://github.com/Microsoft/vcpkg/blob/master/docs/examples/using-sqlite.md)
        vector<Dependency> globalLibDependencies;
#if OS_FAMILY == OS_FAMILY_POSIX
        vector<Dependency> pkgConfigDependencies;
        for(const Dependency &dependency : config.getDependencies())
        {
            Result<bool> pkgConfigDependencyValidation = PkgConfig::validatePkgConfigPackageVersionExists(dependency);
            if(pkgConfigDependencyValidation.isOk())
            {
                pkgConfigDependencies.push_back(dependency);
            }
            else
            {
                globalLibDependencies.push_back(dependency);
            }
        }

        // TODO: Use getDynamicLibsFlags instead which includes cflags?
        Result<string> pkgConfigLinkerFlagsResult = PkgConfig::getDynamicLibsLinkerFlags(pkgConfigDependencies);
        if (pkgConfigLinkerFlagsResult.isErr())
        {
            printf("%s, using global lib...\n", pkgConfigLinkerFlagsResult.getErrMsg().c_str());
            globalLibDependencies.reserve(globalLibDependencies.size() + pkgConfigDependencies.size());
            for (const Dependency &pkgConfigDependency : pkgConfigDependencies)
            {
                globalLibDependencies.push_back(pkgConfigDependency);
            }
            pkgConfigDependencies.clear();
        }
        else
        {
            if (!pkgConfigLinkerFlagsResult.unwrap().empty())
                dynamicLinkerFlagCallbackFunc(pkgConfigLinkerFlagsResult.unwrap());
        }
#else
        for (const Dependency &dependency : dependencies)
        {
            globalLibDependencies.push_back(dependency);
        }
#endif

        Result<bool> globalLibResult = GlobalLib::getLibs(globalLibDependencies, config, globalLibDir, staticLinkerFlagCallbackFunc, dynamicLinkerFlagCallbackFunc, globalIncludeDirCallback);
        if(!globalLibResult)
            return globalLibResult;
            
        Result<bool> createBuildDirResult = createDirectoryRecursive(buildPath.c_str());
        if (createBuildDirResult.isErr())
            return createBuildDirResult;
        
        FileString cmd = TINYDIR_STRING("cmake ");
        switch(config.getPackageType())
        {
            case PackageType::EXECUTABLE:
            {
                cmd += config.getCmakeArgs();
                break;
            }
            case PackageType::STATIC:
            {
                cmd += config.getCmakeArgsStatic();
                break;
            }
            case PackageType::DYNAMIC:
            case PackageType::LIBRARY:
            {
                cmd += config.getCmakeArgsDynamic();
                break;
            }
        }
        cmd += TINYDIR_STRING(" \"-B");
        cmd += buildPath;
        cmd += TINYDIR_STRING("\" \"-H");
        switch(config.getPackageType())
        {
            case PackageType::EXECUTABLE:
            {
                cmd += config.getCmakeDir();
                break;
            }
            case PackageType::STATIC:
            {
                cmd += config.getCmakeDirStatic();
                break;
            }
            case PackageType::DYNAMIC:
            case PackageType::LIBRARY:
            {
                cmd += config.getCmakeDirDynamic();
                break;
            }
        }
        cmd += TINYDIR_STRING("\"");
        nprintf("Compiling with cmake with arguments: %s\n", cmd.c_str());
        
        Result<ExecResult> execResult = exec(cmd.c_str(), true);
        if(execResult.isOk())
        {
            if(execResult.unwrap().exitCode != 0)
                return Result<bool>::Err(execResult.unwrap().execStdout);
        }
        else
            return Result<bool>::Err(execResult);
        
        FileString ninjaCommand = TINYDIR_STRING("ninja -C \"");
        ninjaCommand += buildPath;
        ninjaCommand += TINYDIR_STRING("\"");
        nprintf("Compiling cmake generated ninja file: %s\n", ninjaCommand.c_str());
        execResult = exec(ninjaCommand.c_str(), true);
        if(execResult.isOk())
        {
            if(execResult.unwrap().exitCode != 0)
                return Result<bool>::Err(execResult.unwrap().execStdout);
        }
        else
            return Result<bool>::Err(execResult);
        
        if(config.getPackageType() != PackageType::EXECUTABLE)
        {
            string buildPathUtf8 = toUtf8(buildPath);
            nprintf("Searching for libraries generate by cmake in build path: %s\n", buildPathUtf8.c_str());
            walkDirFiles(buildPath.c_str(), 
                [&config, &staticLinkerFlagCallbackFunc, &dynamicLinkerFlagCallbackFunc](tinydir_file *file) 
            {
                if(_tinydir_strcmp(file->extension, CONFIG_DYNAMIC_LIB_FILE_EXTENSION) == 0)
                {
                    string libFileUtf8 = toUtf8(file->path);
                    nprintf("Library generated by cmake: %s\n", libFileUtf8.c_str());
                    
                    switch(config.getPackageType())
                    {
                        case PackageType::STATIC:
                        {
                            string libFileCmd = "\"";
                            libFileCmd += libFileUtf8;
                            libFileCmd += "\"";
                            staticLinkerFlagCallbackFunc(libFileCmd);
                            break;
                        }
                        case PackageType::DYNAMIC:
                        case PackageType::LIBRARY:
                        {
                            string libFileCmd = "\"";
                            libFileCmd += libFileUtf8;
                            libFileCmd += "\"";
                            dynamicLinkerFlagCallbackFunc(libFileCmd);
                            break;
                        }
                    }
                }
            });
            
            // TODO: Clean this up. The below code is indentical to code in Ninja.cpp.......
            string projectPathUtf8 = toUtf8(config.getProjectPath());
            for (const string &globalIncludeDir : config.getGlobalIncludeDirs())
            {
                string globalIncludeDirFull = projectPathUtf8;
                globalIncludeDirFull += "/";
                globalIncludeDirFull += globalIncludeDir;
                if(globalIncludeDirCallback)
                    globalIncludeDirCallback(globalIncludeDirFull);
            }
        }
        
        return Result<bool>::Ok(true);
    }
}