-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcppinit
More file actions
executable file
·444 lines (376 loc) · 13.2 KB
/
cppinit
File metadata and controls
executable file
·444 lines (376 loc) · 13.2 KB
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
#!/usr/bin/env python3
import os
import subprocess
from typing import List
from typing import Dict
import sys
import shutil
class ProjectContent:
def __init__(self, new_project_name: str):
self.project_name = new_project_name
#________________________________-main_cpp-________________________________#
self.main_cpp_content: str = f"""
#include <iostream>
#include <{self.project_name}.h>
int main()
{{
my::{self.project_name} a{{}};
std::cout << "YES " << a.p << std::endl;
return 0;
}}
"""
#________________________________-header_file-________________________________#
self.header_file_content: str = f"""
#ifndef __{self.project_name.upper()}_INCLUDE_{self.project_name.upper()}_H__
#define __{self.project_name.upper()}_INCLUDE_{self.project_name.upper()}_H__
namespace my {{
class {self.project_name} {{
public:
{self.project_name}();
int p;
}};
}} // namespace my
#endif // __{self.project_name.upper()}_INCLUDE_{self.project_name.upper()}_H__
"""
#________________________________-src_file-________________________________#
self.src_file_content: str = f"""
#include "../include/{self.project_name}.h"
namespace my {{
{self.project_name}::{self.project_name}() : p(42) {{}}
}} // namespace my
"""
#________________________________-.git_ignore_content-________________________________#
self.git_ignore_content: str = """
build/
compile_commands.json
.vscode
.cache
# Prerequisites
*.d
# C++ objects and libs
*.slo
*.lo
*.o
*.a
*.la
*.lai
*.so
*.so.*
*.dll
*.dylib
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
*.smod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
"""
#________________________________-.CMakeLists.txt__root-________________________________#
self.cmake_list_root: str = f"""
cmake_minimum_required(VERSION 3.10)
project("{self.project_name}")
set(TARGET_NAME app_${{PROJECT_NAME}})
set(CMAKE_EXPORT_COMPILE_COMMANDS on)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
file(GLOB_RECURSE SOURCE_FILES
src/*.cpp
)
file(GLOB_RECURSE HEADER_FILES
include/*.h
)
add_executable(${{TARGET_NAME}}
main.cpp
${{SOURCE_FILES}}
${{HEADER_FILES}}
)
target_include_directories(${{TARGET_NAME}}
PRIVATE
${{CMAKE_CURRENT_SOURCE_DIR}}/include
)
include(CTest)
add_subdirectory(tests)
set(COMMON_COMPILE_OPTIONS
-Wall
-Wextra
-Wshadow
-Wswitch
-pedantic
-Wformat=2
-Wnull-dereference
-Wunused-parameter
-Wunreachable-code
-Wimplicit-fallthrough
)
set(COMMON_ERROR_OPTIONS
-Werror
-Werror=return-type
-Werror=uninitialized
-Werror=unused-result
-Werror=strict-overflow
)
set(SANITIZER_FLAGS
-fsanitize=undefined
-fsanitize=address
# -fsanitize=thread
-fsanitize=address
-fno-omit-frame-pointer
)
target_compile_options(${{TARGET_NAME}} PRIVATE
${{COMMON_COMPILE_OPTIONS}}
${{COMMON_ERROR_OPTIONS}}
)
target_link_libraries(${{TARGET_NAME}} PRIVATE
${{SANITIZER_FLAGS}}
)
#-----------------------------------------------------------------------#
# if need to remove flags set lib as SYSTEM
# to suppress warnings in external headers
#-----------------------------------------------------------------------#
#target_compile_options(${{TARGET_NAME}} PRIVATE
# "-isystem${{CMAKE_CURRENT_SOURCE_DIR}}/<lib_path>"
#)
# If not Visual Studio generator, copy compile_commands.json
if(NOT CMAKE_GENERATOR MATCHES "Visual Studio")
add_custom_command(
OUTPUT ${{CMAKE_CURRENT_SOURCE_DIR}}/compile_commands.json
COMMAND ${{CMAKE_COMMAND}} -E copy ${{CMAKE_BINARY_DIR}}/compile_commands.json ${{CMAKE_CURRENT_SOURCE_DIR}}/compile_commands.json
DEPENDS ${{CMAKE_BINARY_DIR}}/compile_commands.json
COMMENT "Copying compile_commands.json..."
)
add_custom_target(copy_compile_commands ALL
DEPENDS ${{CMAKE_CURRENT_SOURCE_DIR}}/compile_commands.json
)
endif()
"""
#________________________________-.CMakeLists.txt__test-________________________________#
self.cmake_list_test_content: str = f"""
cmake_minimum_required(VERSION 3.10)
project({self.project_name}_test)
find_package(GTest QUIET)
if(NOT GTest_FOUND)
message(STATUS "[...] GTest not found. Attempting to install using package manager...")
if(UNIX AND NOT APPLE)
execute_process(
COMMAND sh -c "sudo apt-get install -y libgtest-dev || sudo dnf install -y gtest-devel ||
sudo pacman -S --noconfirm gtest || yay -S --noconfirm gtest"
RESULT_VARIABLE PACKAGE_INSTALL_RESULT
OUTPUT_VARIABLE PACKAGE_INSTALL_OUTPUT
ERROR_VARIABLE PACKAGE_INSTALL_ERROR
)
elseif(APPLE)
execute_process(
COMMAND brew install googletest
RESULT_VARIABLE PACKAGE_INSTALL_RESULT
OUTPUT_VARIABLE PACKAGE_INSTALL_OUTPUT
ERROR_VARIABLE PACKAGE_INSTALL_ERROR
)
elseif(WIN32)
execute_process(
COMMAND powershell -Command "scoop install gtest"
RESULT_VARIABLE PACKAGE_INSTALL_RESULT
OUTPUT_VARIABLE PACKAGE_INSTALL_OUTPUT
ERROR_VARIABLE PACKAGE_INSTALL_ERROR
)
else()
set(PACKAGE_INSTALL_RESULT -1)
endif()
if(PACKAGE_INSTALL_RESULT EQUAL 0)
find_package(GTest QUIET)
if(GTest_FOUND)
message(STATUS "[ V ] Successfully installed GTest using the package manager.")
else()
message(WARNING "[ X ] Installation via package manager was successful, but GTest could not be found.")
endif()
else()
message(WARNING "[ X ] Failed to install GTest using the package manager.")
message(STATUS "[ X ] Package manager output: ${{PACKAGE_INSTALL_OUTPUT}}")
message(STATUS "[ X ] Package manager error: ${{PACKAGE_INSTALL_ERROR}}")
endif()
endif()
include_directories(${{GTEST_INCLUDE_DIRS}})
include_directories(${{CMAKE_SOURCE_DIR}}/include)
file(GLOB_RECURSE SRC_FILES "${{CMAKE_SOURCE_DIR}}/src/*.cpp")
file(GLOB_RECURSE HDR_FILES "${{CMAKE_SOURCE_DIR}}/include/*.h")
add_executable({self.project_name}_test {self.project_name}_test.cpp)
target_include_directories({self.project_name}_test PRIVATE ${{CMAKE_SOURCE_DIR}}/include)
target_link_libraries({self.project_name}_test ${{GTEST_LIBRARIES}} ${{GTEST_MAIN_LIBRARIES}} pthread)
enable_testing()
add_test(NAME {self.project_name}_test COMMAND {self.project_name}_test)
target_compile_options({self.project_name}_test PRIVATE -Wall)
"""
self.test_file_content: str = f"""
#include <{self.project_name}.h>
#include <gtest/gtest.h>
TEST({self.project_name}Test, {self.project_name}Test__1)
{{}}
int main(int argc, char** argv)
{{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}}
"""
#________________________________-.clang-format-________________________________#
self.clang_format_conten: str = """
Language: Cpp
BasedOnStyle: Microsoft
AlignTrailingComments: true
BreakBeforeBraces: Custom
BraceWrapping:
AfterEnum: true
AfterStruct: true
AfterClass: true
AfterFunction: true
AfterUnion: true
AfterExternBlock: false
BeforeCatch: true
BeforeElse: true
BeforeLambdaBody: true
BeforeWhile: false
AfterNamespace: false
SplitEmptyFunction: true
IndentWidth: 4
KeepEmptyLinesAtTheStartOfBlocks: false
PointerBindsToType: true
SpacesBeforeTrailingComments: 1
TabWidth: 4
UseTab: Never
IndentCaseLabels: true
NamespaceIndentation: All
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: Consecutive
AlignConsecutiveMacros:
Enabled: true
AcrossEmptyLines: true
AcrossComments: false
AllowShortCaseLabelsOnASingleLine: true
AlignEscapedNewlines: Right
AllowShortBlocksOnASingleLine: Always
AllowShortEnumsOnASingleLine: false
AlignConsecutiveDeclarations: true
AlwaysBreakTemplateDeclarations: true
Cpp11BracedListStyle: false
PackConstructorInitializers: Never
AllowShortFunctionsOnASingleLine: Empty
ReflowComments: true
PenaltyBreakComment: 0
PenaltyBreakOpenParenthesis: 1
"""
def is_tool_installed(tool_name: str) -> bool:
"""Check if a tool is installed on the system."""
try:
subprocess.run([tool_name, "--version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
return True
except (FileNotFoundError, subprocess.CalledProcessError):
return False
def install_tool(tool_name: str):
"""Attempt to install a tool using the appropriate package manager."""
try:
if sys.platform.startswith("linux"):
if os.path.exists("/usr/bin/pacman"):
print(f"Installing {tool_name} using pacman...")
subprocess.run(["sudo", "pacman", "-S", "--noconfirm", tool_name], check=True)
elif os.path.exists("/usr/bin/yay"):
print(f"Installing {tool_name} using yay...")
subprocess.run(["yay", "-S", "--noconfirm", tool_name], check=True)
elif os.path.exists("/usr/bin/apt-get"):
print(f"Installing {tool_name} using apt-get...")
subprocess.run(["sudo", "apt-get", "install", "-y", tool_name], check=True)
elif os.path.exists("/usr/bin/dnf"):
print(f"Installing {tool_name} using dnf...")
subprocess.run(["sudo", "dnf", "install", "-y", tool_name], check=True)
else:
print(f"Unknown package manager. Please install {tool_name} manually.")
elif sys.platform == "darwin":
print(f"Installing {tool_name} via Homebrew...")
subprocess.run(["brew", "install", tool_name], check=True)
elif sys.platform == "win32":
print(f"Please install {tool_name} manually on Windows.")
else:
print(f"Unsupported platform. Please install {tool_name} manually.")
except subprocess.CalledProcessError as e:
print(f"Failed to install {tool_name}: {e}")
def check_dependencies():
"""Ensure all necessary tools are installed."""
tools = ["clang-format", "cmake", "make"]
for tool in tools:
if not is_tool_installed(tool):
print(f"{tool} is not installed.")
install_tool(tool)
def write_file(file_path: str, content: str = "") -> None:
with open(file_path, "w", encoding="utf-8") as file:
file.write(content)
def main(argv: list[str]) -> None:
check_dependencies()
argc: int = len(argv)
project_name: str = ""
if argc != 2:
print("Please enter project name:")
project_name = input()
else:
project_name = argv[1]
# Check if the directory already exists
if os.path.exists(project_name):
print(f"Error: Directory '{project_name}' already exists.")
print("Do you want to override? (y/Y/yes)")
response = input().strip().lower()
if response in {'y', 'yes'}:
print("Overriding the existing directory...")
shutil.rmtree(project_name)
else:
print("Operation aborted.")
return
project_content = ProjectContent(project_name)
os.makedirs(project_name)
# Dictionary of file paths and contents to be written
root_files: Dict[str, str] = {
os.path.join(project_name, "main.cpp"): project_content.main_cpp_content, # root main
os.path.join(project_name, ".clang-format"): project_content.clang_format_conten, # root clang-format
os.path.join(project_name, ".gitignore"): project_content.git_ignore_content, # root .gitignore
os.path.join(project_name, "CMakeLists.txt"): project_content.cmake_list_root # root CMakeLists
}
for file_path, content in root_files.items():
write_file(file_path, content)
print(f" [V] Created {file_path}")
# List of directories to create
directories: List[str] = [
os.path.join(project_name, "build"),
os.path.join(project_name, "src"),
os.path.join(project_name, "include"),
os.path.join(project_name, "tests")
]
for directory in directories:
os.makedirs(directory, exist_ok=True)
print(f" [V] Created directory {directory}")
# Dictionary of additional files to be created
additional_files: Dict[str, str] = {
os.path.join(project_name, "src", f'{project_name}.cpp'): project_content.src_file_content, # src/ dir c++ file
os.path.join(project_name, "include", f'{project_name}.h'): project_content.header_file_content, # include/ dir header file
os.path.join(project_name, "tests", f'{project_name}_test.cpp'): project_content.test_file_content, # test/ dir test.cpp file
os.path.join(project_name, "tests", "CMakeLists.txt"): project_content.cmake_list_test_content # test/ dir CMakeLists
}
for file_path, content in additional_files.items():
write_file(file_path, content)
print(f" [V] Created {file_path}")
print("\n[V] Project initialized successfully!")
print(f" Next steps:\n"
f" cd {project_name}\n"
f" cd build\n"
f" cmake .. && cmake --build . -j\n"
f" ./app_{project_name}")
if __name__ == '__main__':
main(sys.argv)