summaryrefslogtreecommitdiff
path: root/src/app/qbs-create-project/createproject.cpp
blob: 20338be986ae2467353eb73aef57e0c5bd71c1b4 (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
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "createproject.h"

#include <logging/translator.h>
#include <tools/error.h>
#include <tools/jsliterals.h>
#include <tools/qttools.h>

#include <QtCore/qdebug.h>
#include <QtCore/qdiriterator.h>
#include <QtCore/qfile.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qtextstream.h>

#include <algorithm>

using qbs::ErrorInfo;
using qbs::Internal::Tr;

static const char *indent = "    ";

void ProjectCreator::run(const QString &topLevelDir, ProjectStructure projectStructure,
                         const QStringList &whiteList, const QStringList &blackList)
{
    m_projectStructure = projectStructure;
    for (const QString &s : whiteList)
        m_whiteList.push_back(QRegularExpression(QRegularExpression::wildcardToRegularExpression(s)));
    for (const QString &s : blackList)
        m_blackList.push_back(QRegularExpression(QRegularExpression::wildcardToRegularExpression(s)));
    m_topLevelProject.dirPath = topLevelDir;
    setupProject(&m_topLevelProject);
    serializeProject(m_topLevelProject);
}

void ProjectCreator::setupProject(Project *project)
{
    QDirIterator dit(project->dirPath, QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
    while (dit.hasNext()) {
        dit.next();
        if (dit.fileInfo().isFile()) {
            if (dit.fileName().endsWith(QLatin1String(".qbs")))
                throw ErrorInfo(Tr::tr("Project already contains qbs files, aborting."));
            if (isSourceFile(dit.fileName()))
                project->fileNames << dit.fileName();
        } else if (dit.fileInfo().isDir()) {
            ProjectPtr subProject(new Project);
            subProject->dirName = dit.fileName();
            subProject->dirPath = dit.filePath();
            setupProject(subProject.get());
            if (!subProject->fileNames.empty() || !subProject->subProjects.empty())
                project->subProjects.push_back(std::move(subProject));
        }
    }
    project->fileNames.sort();
    std::sort(project->subProjects.begin(), project->subProjects.end(),
            [](const ProjectPtr &p1, const ProjectPtr &p2) { return p1->dirName < p2->dirName; });
}

void ProjectCreator::serializeProject(const ProjectCreator::Project &project)
{
    const QString fileName = QFileInfo(project.dirPath).baseName() + QLatin1String(".qbs");
    QFile projectFile(project.dirPath + QLatin1Char('/') + fileName);
    if (!projectFile.open(QIODevice::WriteOnly)) {
        throw ErrorInfo(Tr::tr("Failed to open '%1' for writing: %2")
                        .arg(projectFile.fileName(), projectFile.errorString()));
    }
    QTextStream fileContents(&projectFile);
    fileContents.setCodec("UTF-8");
    fileContents << "import qbs\n\n";
    if (!project.fileNames.empty() || m_projectStructure == ProjectStructure::Flat) {
        fileContents << "Product {\n";
        const ProductFlags productFlags = getFlags(project);
        if (productFlags.testFlag(IsApp)) {
            fileContents << indent << "type: [\"application\"]\n";
        } else {
            fileContents << indent << "type: [\"unknown\"] // E.g. \"application\", "
                            "\"dynamiclibrary\", \"staticlibrary\"\n";
        }
        if (productFlags.testFlag(NeedsQt)) {
            fileContents << indent << "Depends {\n";
            fileContents << indent << indent << "name: \"Qt\"\n";
            fileContents << indent << indent << "submodules: [\"core\"] "
                                                "// Add more here if needed\n";
            fileContents << indent << "}\n";
        } else if (productFlags.testFlag(NeedsCpp)) {
            fileContents << indent << "Depends { name: \"cpp\" }\n";
        }
        fileContents << indent << "files: [\n";
        for (const QString &fileName : qAsConst(project.fileNames))
            fileContents << indent << indent << qbs::toJSLiteral(fileName) << ",\n";
        fileContents << indent << "]\n";
        for (const ProjectPtr &p : project.subProjects)
            addGroups(fileContents, QDir(project.dirPath), *p);
    } else {
        fileContents << "Project {\n";
        fileContents << indent << "references: [\n";
        for (const ProjectPtr &p : project.subProjects) {
            serializeProject(*p);
            fileContents << indent << indent
                         << qbs::toJSLiteral(QFileInfo(p->dirPath).fileName()) << ",\n";
        }
        fileContents << indent << "]\n";
    }
    fileContents << "}\n";
}

void ProjectCreator::addGroups(QTextStream &stream, const QDir &baseDir,
                                 const ProjectCreator::Project &subProject)
{
    stream << indent << "Group {\n";
    stream << indent << indent << "name: "
           << qbs::toJSLiteral(QFileInfo(subProject.dirPath).fileName()) << "\n";
    stream << indent << indent << "prefix: "
           << qbs::toJSLiteral(baseDir.relativeFilePath(subProject.dirPath) + QLatin1Char('/'))
           << '\n';
    stream << indent << indent << "files: [\n";
    for (const QString &fileName : qAsConst(subProject.fileNames))
        stream << indent << indent << indent << qbs::toJSLiteral(fileName) << ",\n";
    stream << indent << indent << "]\n";
    stream << indent << "}\n";
    for (const ProjectPtr &p : subProject.subProjects)
        addGroups(stream, baseDir, *p);
}

bool ProjectCreator::isSourceFile(const QString &fileName)
{
    const auto isMatch = [fileName](const QRegularExpression &rex) {
        return rex.match(fileName).hasMatch();
    };
    return !std::any_of(m_blackList.cbegin(), m_blackList.cend(), isMatch)
            && (m_whiteList.empty()
                || std::any_of(m_whiteList.cbegin(), m_whiteList.cend(), isMatch));
}

ProjectCreator::ProductFlags ProjectCreator::getFlags(const ProjectCreator::Project &project)
{
    ProductFlags flags;
    getFlagsFromFileNames(project, flags);
    if (flags.testFlag(IsApp) && flags.testFlag(NeedsQt))
        return flags;
    if (!flags.testFlag(NeedsCpp))
        return flags;
    getFlagsFromFileContents(project, flags);
    return flags;
}

void ProjectCreator::getFlagsFromFileNames(const ProjectCreator::Project &project,
                                           ProductFlags &flags)
{
    for (const QString &fileName : qAsConst(project.fileNames)) {
        if (flags.testFlag(IsApp) && flags.testFlag(NeedsQt))
            return;
        const QFileInfo fi(project.dirPath + QLatin1Char('/') + fileName);
        const QString &suffix = fi.suffix();
        if (suffix == QLatin1String("qrc")) {
            flags |= NeedsQt;
            continue;
        }
        if (suffix == QLatin1String("cpp") || suffix == QLatin1String("c")
                || suffix == QLatin1String("m") || suffix == QLatin1String("mm")) {
            flags |= NeedsCpp;
        }
        if (flags.testFlag(NeedsCpp) && fi.completeBaseName() == QLatin1String("main"))
            flags |= IsApp;
    }
    for (const ProjectPtr &p : project.subProjects) {
        getFlagsFromFileNames(*p, flags);
        if (flags.testFlag(IsApp) && flags.testFlag(NeedsQt))
            return;
    }
}

void ProjectCreator::getFlagsFromFileContents(const ProjectCreator::Project &project,
                                              ProductFlags &flags)
{
    for (const QString &fileName : qAsConst(project.fileNames)) {
        QFile f (project.dirPath + QLatin1Char('/') + fileName);
        if (!f.open(QIODevice::ReadOnly)) {
            qDebug() << "Ignoring failure to read" << f.fileName();
            continue;
        }
        while (!f.atEnd()) {
            const QByteArray &line = f.readLine();
            if (line.contains("#include <Q"))
                flags |= NeedsQt;
            if (line.contains("int main"))
                flags |= IsApp;
            if (flags.testFlag(IsApp) && flags.testFlag(NeedsQt))
                return;
        }
    }
    for (const ProjectPtr &p : project.subProjects) {
        getFlagsFromFileContents(*p, flags);
        if (flags.testFlag(IsApp) && flags.testFlag(NeedsQt))
            return;
    }
}