Skip to content

Commit 5b6d9c3

Browse files
committed
Replace illegal characters in the project name with _ when doing cmkr init
1 parent a90988b commit 5b6d9c3

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

src/cmake_generator.cpp

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,24 @@ static void create_file(const fs::path &path, const std::string &contents) {
8989
ofs << contents;
9090
}
9191

92+
// CMake target name rules: https://cmake.org/cmake/help/latest/policy/CMP0037.html [A-Za-z0-9_.+\-]
93+
// TOML bare keys: non-empty strings composed only of [A-Za-z0-9_-]
94+
// We replace all non-TOML bare key characters with _
95+
static std::string escape_project_name(const std::string &name) {
96+
std::string escaped;
97+
escaped.reserve(name.length());
98+
for (auto ch : name) {
99+
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '-') {
100+
escaped += ch;
101+
} else {
102+
escaped += '_';
103+
}
104+
}
105+
return escaped;
106+
}
107+
92108
void generate_project(const std::string &type) {
93-
const auto name = fs::current_path().stem().string();
109+
const auto name = escape_project_name(fs::current_path().stem().string());
94110
if (fs::exists(fs::current_path() / "cmake.toml")) {
95111
throw std::runtime_error("Cannot initialize a project when cmake.toml already exists!");
96112
}

0 commit comments

Comments
 (0)