-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
394 lines (342 loc) · 9.08 KB
/
main.js
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
#!/usr/bin/env node
import { execSync } from "child_process";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { program } from "commander";
import figlet from "figlet";
import chalk from "chalk";
import inquirer from "inquirer";
import boxen from "boxen";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const checkQtVersion = (version) => {
try {
const command =
process.platform === "win32"
? `where qmake && qmake -query QT_VERSION`
: `command -v qmake && qmake -query QT_VERSION`;
const stdout = execSync(command).toString().trim();
const qtVersion = stdout.split("\n").pop();
return qtVersion.startsWith(version);
} catch {
return false;
}
};
const createBuildScript = (projectDir, projectName, makeTool) => {
const isWindows = process.platform === "win32";
const scriptExt = isWindows ? "bat" : "sh";
const scriptName = `run.${scriptExt}`;
const scriptContent = isWindows
? `@echo off
mkdir build
cd build
${makeTool === "cmake" ? "cmake .." : "qmake .."}
${makeTool === "cmake" ? "cmake --build . --config Release" : "mingw32-make"}
cd ..
.\\build\\Release\\${projectName}.exe
`
: `#!/bin/bash
mkdir -p build
cd build
${makeTool === "cmake" ? "cmake .." : "qmake .."}
${makeTool === "cmake" ? "cmake --build . --config Release" : "make"}
cd ..
./build/${projectName}
`;
const scriptPath = path.join(projectDir, scriptName);
fs.writeFileSync(scriptPath, scriptContent);
if (!isWindows) {
fs.chmodSync(scriptPath, "755");
}
};
const createProjectStructure = (
projectName,
qtVersion,
makeTool,
useWidgetUI
) => {
const projectDir = path.join(process.cwd(), projectName);
if (fs.existsSync(projectDir)) {
throw new Error(
`Folder '${projectName}' already exists. Please choose another name.`
);
}
fs.mkdirSync(projectDir);
["headers", "src", useWidgetUI ? "ui" : null]
.filter(Boolean)
.forEach((dir) => fs.mkdirSync(path.join(projectDir, dir)));
const files = [
{
path: "headers/widget.h",
content: `
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QLabel>
class Widget : public QWidget {
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
private:
QLabel *titleLabel;
};
#endif // WIDGET_H
`,
},
{
path: "src/widget.cpp",
content: `
#include "../headers/widget.h"
#include <QVBoxLayout>
Widget::Widget(QWidget *parent) : QWidget(parent) {
titleLabel = new QLabel("${projectName}", this);
titleLabel->setAlignment(Qt::AlignCenter);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(titleLabel);
setLayout(layout);
}
`,
},
{
path: "src/main.cpp",
content: `
#include <QApplication>
#include "../headers/widget.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
Widget widget;
widget.setWindowTitle("Hello, Qt${qtVersion}!");
widget.resize(400, 300);
widget.show();
return app.exec();
}
`,
},
{
path: "README.md",
content: `# ${projectName}
This is a Qt${qtVersion} application.
## Building and Running
### Automatic (using script)
Run the following command:
\`\`\`
${process.platform === "win32" ? ".\\run.bat" : "./run.sh"}
\`\`\`
### Manual
To build this project manually, use the following commands:
\`\`\`
mkdir build
cd build
${makeTool === "cmake" ? "cmake .." : "qmake .."}
${makeTool === "cmake" ? "cmake --build . --config Release" : "make"}
\`\`\`
To run the application:
\`\`\`
${
process.platform === "win32" ? ".\\build\\Release\\" : "./build/"
}${projectName}${process.platform === "win32" ? ".exe" : ""}
\`\`\`
`,
},
{
path: "LICENSE",
content: "MIT License\n\nCopyright (c) 2024 Your Name\n",
},
makeTool === "cmake"
? {
path: "CMakeLists.txt",
content: `
cmake_minimum_required(VERSION 3.16)
project(${projectName} VERSION 1.0 LANGUAGES CXX)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Qt${qtVersion} REQUIRED COMPONENTS Core Gui Widgets)
set(SOURCES
src/main.cpp
src/widget.cpp
)
set(HEADERS
headers/widget.h
)
add_executable(\${PROJECT_NAME} \${SOURCES} \${HEADERS})
target_include_directories(\${PROJECT_NAME} PRIVATE headers)
target_link_libraries(\${PROJECT_NAME} PRIVATE Qt${qtVersion}::Core Qt${qtVersion}::Gui Qt${qtVersion}::Widgets)
`,
}
: {
path: `${projectName}.pro`,
content: `
QT += core gui widgets
CONFIG += c++17
TARGET = ${projectName}
TEMPLATE = app
SOURCES += src/main.cpp src/widget.cpp
HEADERS += headers/widget.h
INCLUDEPATH += headers
`,
},
];
files.forEach((file) =>
fs.writeFileSync(path.join(projectDir, file.path), file.content.trim())
);
if (useWidgetUI) {
const uiFilePath = path.join(projectDir, "ui/widget.ui");
const uiFileContent = `
<?xml version="1.0"?>
<ui version="4.0">
<class>Widget</class>
<widget class="QWidget" name="Widget">
<property name="windowTitle">
<string>${projectName}</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="titleLabel">
<property name="text">
<string>${projectName}</string>
</property>
</widget>
</item>
</layout>
</widget>
<connections/>
</ui>
`;
fs.writeFileSync(uiFilePath, uiFileContent.trim());
}
createBuildScript(projectDir, projectName, makeTool);
};
const printHeader = () => {
console.log(
boxen("QT PROJECT CREATOR", {
padding: 1,
borderColor: "cyan",
borderStyle: "round",
})
);
};
const promptUser = async () => {
const questions = [
{
type: "list",
name: "qtVersion",
message: "Qt version:",
choices: ["5", "6"],
default: "6",
loop: false,
},
{
type: "list",
name: "makeTool",
message: "Build system:",
choices: ["cmake", "qmake"],
default: "cmake",
loop: false,
},
{
type: "confirm",
name: "useWidgetUI",
message: "Create a widget.ui file?",
default: false,
},
{
type: "input",
name: "projectName",
message: "Project name:",
default: "hello-world-qt",
validate: (input) =>
!fs.existsSync(path.join(process.cwd(), input)) ||
"Folder already exists. Please choose another name.",
},
];
const answers = {};
for (const question of questions) {
console.clear();
printHeader();
console.log(chalk.yellow("Press 'CTRL + C' to abort the process."));
const answer = await inquirer.prompt({
...question,
validate: async (input) => {
if (input === "q") {
console.log(chalk.red("Aborted by user."));
process.exit(0);
}
return question.validate ? question.validate(input) : true;
},
});
if (question.name === "qtVersion") {
const isAvailable = await checkQtVersion(answer.qtVersion);
if (!isAvailable) {
console.error(
chalk.red(`Qt${answer.qtVersion} is not installed or not in PATH.`)
);
process.exit(1);
}
}
answers[question.name] = answer[question.name];
}
return answers;
};
const displayBuildAndRunInstructions = (projectName, makeTool) => {
console.clear();
console.log(
boxen(
`
-----------------------------------------------------
Project Created successfully
-----------------------------------------------------
To build and run the app:
${chalk.italic.cyan(`cd ${projectName}`)}
${chalk.italic.cyan("mkdir build && cd build && qmake && make")}
${chalk.italic.cyan(
`cd .. && ./build/${projectName}${process.platform === "win32" ? ".exe" : ""}`
)}
${chalk.bold.yellowBright("OR")}
Build and Run using script:
${chalk.italic.cyan(`cd ${projectName}`)}
${chalk.italic.cyan(`./run${process.platform === "win32" ? ".bat" : ".sh"}`)}
`,
{
padding: 1,
borderColor: "cyan",
borderStyle: "round",
textAlignment: "center",
}
)
);
};
const main = async () => {
program
.version("1.0.0")
.description("CLI tool to set up a Qt project structure")
.option("--init", "Initialize a default hello-world-qt project with cmake");
program.parse(process.argv);
const options = program.opts();
console.clear();
printHeader();
if (options.init) {
console.log(chalk.cyan("Initializing project..."));
const qtVersion = "6";
if (!checkQtVersion(qtVersion)) {
console.error(
chalk.red(`Qt${qtVersion} is not installed or not in PATH.`)
);
process.exit(1);
}
const projectName = "hello-world-qt";
createProjectStructure(projectName, qtVersion, "cmake", false);
displayBuildAndRunInstructions(projectName, "cmake");
} else {
const { projectName, qtVersion, makeTool, useWidgetUI } =
await promptUser();
createProjectStructure(projectName, qtVersion, makeTool, useWidgetUI);
displayBuildAndRunInstructions(projectName, makeTool);
}
};
main().catch((err) => {
console.error(chalk.red("An error occurred:"), err);
process.exit(1);
});