cmProjectCommand.cxx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmProjectCommand.h"
  4. #include <array>
  5. #include <cstdio>
  6. #include <limits>
  7. #include <set>
  8. #include <utility>
  9. #include <cm/optional>
  10. #include <cm/string_view>
  11. #include <cmext/string_view>
  12. #include "cmsys/RegularExpression.hxx"
  13. #include "cmArgumentParser.h"
  14. #include "cmArgumentParserTypes.h"
  15. #include "cmExecutionStatus.h"
  16. #include "cmExperimental.h"
  17. #include "cmList.h"
  18. #include "cmMakefile.h"
  19. #include "cmMessageType.h"
  20. #include "cmPolicies.h"
  21. #include "cmStateTypes.h"
  22. #include "cmStringAlgorithms.h"
  23. #include "cmSystemTools.h"
  24. #include "cmValue.h"
  25. namespace {
  26. bool IncludeByVariable(cmExecutionStatus& status, std::string const& variable);
  27. void TopLevelCMakeVarCondSet(cmMakefile& mf, std::string const& name,
  28. std::string const& value);
  29. struct ProjectArguments : ArgumentParser::ParseResult
  30. {
  31. cm::optional<std::string> ProjectName;
  32. cm::optional<std::string> Version;
  33. cm::optional<std::string> CompatVersion;
  34. cm::optional<std::string> License;
  35. cm::optional<std::string> Description;
  36. cm::optional<std::string> HomepageURL;
  37. cm::optional<ArgumentParser::MaybeEmpty<std::vector<std::string>>> Languages;
  38. };
  39. struct ProjectArgumentParser : public cmArgumentParser<void>
  40. {
  41. ProjectArgumentParser& BindKeywordMissingValue(
  42. std::vector<cm::string_view>& ref)
  43. {
  44. this->cmArgumentParser<void>::BindKeywordMissingValue(
  45. [&ref](Instance&, cm::string_view arg) { ref.emplace_back(arg); });
  46. return *this;
  47. }
  48. };
  49. } // namespace
  50. bool cmProjectCommand(std::vector<std::string> const& args,
  51. cmExecutionStatus& status)
  52. {
  53. std::vector<std::string> unparsedArgs;
  54. std::vector<cm::string_view> missingValueKeywords;
  55. std::vector<cm::string_view> parsedKeywords;
  56. ProjectArguments prArgs;
  57. ProjectArgumentParser parser;
  58. parser.BindKeywordMissingValue(missingValueKeywords)
  59. .BindParsedKeywords(parsedKeywords)
  60. .Bind(0, prArgs.ProjectName)
  61. .Bind("VERSION"_s, prArgs.Version)
  62. .Bind("DESCRIPTION"_s, prArgs.Description)
  63. .Bind("HOMEPAGE_URL"_s, prArgs.HomepageURL)
  64. .Bind("LANGUAGES"_s, prArgs.Languages);
  65. cmMakefile& mf = status.GetMakefile();
  66. bool enablePackageInfo = cmExperimental::HasSupportEnabled(
  67. mf, cmExperimental::Feature::ExportPackageInfo);
  68. if (enablePackageInfo) {
  69. parser.Bind("COMPAT_VERSION"_s, prArgs.CompatVersion);
  70. parser.Bind("SPDX_LICENSE"_s, prArgs.License);
  71. }
  72. parser.Parse(args, &unparsedArgs, 0);
  73. if (!prArgs.ProjectName) {
  74. status.SetError("PROJECT called with incorrect number of arguments");
  75. return false;
  76. }
  77. if (mf.IsRootMakefile() &&
  78. !mf.GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION")) {
  79. mf.IssueMessage(
  80. MessageType::AUTHOR_WARNING,
  81. "cmake_minimum_required() should be called prior to this top-level "
  82. "project() call. Please see the cmake-commands(7) manual for usage "
  83. "documentation of both commands.");
  84. }
  85. if (!IncludeByVariable(status, "CMAKE_PROJECT_INCLUDE_BEFORE")) {
  86. return false;
  87. }
  88. if (!IncludeByVariable(
  89. status, "CMAKE_PROJECT_" + *prArgs.ProjectName + "_INCLUDE_BEFORE")) {
  90. return false;
  91. }
  92. mf.SetProjectName(*prArgs.ProjectName);
  93. cmPolicies::PolicyStatus cmp0180 = mf.GetPolicyStatus(cmPolicies::CMP0180);
  94. std::string varName = cmStrCat(*prArgs.ProjectName, "_BINARY_DIR"_s);
  95. bool nonCacheVarAlreadySet = mf.IsNormalDefinitionSet(varName);
  96. mf.AddCacheDefinition(varName, mf.GetCurrentBinaryDirectory(),
  97. "Value Computed by CMake", cmStateEnums::STATIC);
  98. if (cmp0180 == cmPolicies::NEW || nonCacheVarAlreadySet) {
  99. mf.AddDefinition(varName, mf.GetCurrentBinaryDirectory());
  100. }
  101. varName = cmStrCat(*prArgs.ProjectName, "_SOURCE_DIR"_s);
  102. nonCacheVarAlreadySet = mf.IsNormalDefinitionSet(varName);
  103. mf.AddCacheDefinition(varName, mf.GetCurrentSourceDirectory(),
  104. "Value Computed by CMake", cmStateEnums::STATIC);
  105. if (cmp0180 == cmPolicies::NEW || nonCacheVarAlreadySet) {
  106. mf.AddDefinition(varName, mf.GetCurrentSourceDirectory());
  107. }
  108. mf.AddDefinition("PROJECT_BINARY_DIR", mf.GetCurrentBinaryDirectory());
  109. mf.AddDefinition("PROJECT_SOURCE_DIR", mf.GetCurrentSourceDirectory());
  110. mf.AddDefinition("PROJECT_NAME", *prArgs.ProjectName);
  111. mf.AddDefinitionBool("PROJECT_IS_TOP_LEVEL", mf.IsRootMakefile());
  112. varName = cmStrCat(*prArgs.ProjectName, "_IS_TOP_LEVEL"_s);
  113. nonCacheVarAlreadySet = mf.IsNormalDefinitionSet(varName);
  114. mf.AddCacheDefinition(varName, mf.IsRootMakefile() ? "ON" : "OFF",
  115. "Value Computed by CMake", cmStateEnums::STATIC);
  116. if (cmp0180 == cmPolicies::NEW || nonCacheVarAlreadySet) {
  117. mf.AddDefinition(varName, mf.IsRootMakefile() ? "ON" : "OFF");
  118. }
  119. TopLevelCMakeVarCondSet(mf, "CMAKE_PROJECT_NAME", *prArgs.ProjectName);
  120. std::set<cm::string_view> seenKeywords;
  121. for (cm::string_view keyword : parsedKeywords) {
  122. if (seenKeywords.find(keyword) != seenKeywords.end()) {
  123. mf.IssueMessage(MessageType::FATAL_ERROR,
  124. cmStrCat(keyword, " may be specified at most once."));
  125. cmSystemTools::SetFatalErrorOccurred();
  126. return true;
  127. }
  128. seenKeywords.insert(keyword);
  129. }
  130. for (cm::string_view keyword : missingValueKeywords) {
  131. mf.IssueMessage(MessageType::WARNING,
  132. cmStrCat(keyword,
  133. " keyword not followed by a value or was "
  134. "followed by a value that expanded to nothing."));
  135. }
  136. if (!unparsedArgs.empty()) {
  137. if (prArgs.Languages) {
  138. mf.IssueMessage(
  139. MessageType::WARNING,
  140. cmStrCat("the following parameters must be specified after LANGUAGES "
  141. "keyword: ",
  142. cmJoin(unparsedArgs, ", "), '.'));
  143. } else if (prArgs.Version || prArgs.Description || prArgs.HomepageURL) {
  144. mf.IssueMessage(MessageType::FATAL_ERROR,
  145. "project with VERSION, DESCRIPTION or HOMEPAGE_URL must "
  146. "use LANGUAGES before language names.");
  147. cmSystemTools::SetFatalErrorOccurred();
  148. return true;
  149. }
  150. } else if (prArgs.Languages && prArgs.Languages->empty()) {
  151. prArgs.Languages->emplace_back("NONE");
  152. }
  153. if (prArgs.CompatVersion && !prArgs.Version) {
  154. mf.IssueMessage(MessageType::FATAL_ERROR,
  155. "project with COMPAT_VERSION must also provide VERSION.");
  156. cmSystemTools::SetFatalErrorOccurred();
  157. return true;
  158. }
  159. cmsys::RegularExpression vx(
  160. R"(^([0-9]+(\.[0-9]+(\.[0-9]+(\.[0-9]+)?)?)?)?$)");
  161. constexpr std::size_t MAX_VERSION_COMPONENTS = 4u;
  162. std::string version_string;
  163. std::array<std::string, MAX_VERSION_COMPONENTS> version_components;
  164. if (prArgs.Version) {
  165. if (!vx.find(*prArgs.Version)) {
  166. std::string e =
  167. R"(VERSION ")" + *prArgs.Version + R"(" format invalid.)";
  168. mf.IssueMessage(MessageType::FATAL_ERROR, e);
  169. cmSystemTools::SetFatalErrorOccurred();
  170. return true;
  171. }
  172. cmPolicies::PolicyStatus const cmp0096 =
  173. mf.GetPolicyStatus(cmPolicies::CMP0096);
  174. if (cmp0096 == cmPolicies::OLD || cmp0096 == cmPolicies::WARN) {
  175. constexpr size_t maxIntLength =
  176. std::numeric_limits<unsigned>::digits10 + 2;
  177. char vb[MAX_VERSION_COMPONENTS][maxIntLength];
  178. unsigned v[MAX_VERSION_COMPONENTS] = { 0, 0, 0, 0 };
  179. int const vc = std::sscanf(prArgs.Version->c_str(), "%u.%u.%u.%u", &v[0],
  180. &v[1], &v[2], &v[3]);
  181. for (auto i = 0u; i < MAX_VERSION_COMPONENTS; ++i) {
  182. if (static_cast<int>(i) < vc) {
  183. std::snprintf(vb[i], maxIntLength, "%u", v[i]);
  184. version_string += &"."[static_cast<std::size_t>(i == 0)];
  185. version_string += vb[i];
  186. version_components[i] = vb[i];
  187. } else {
  188. vb[i][0] = '\x00';
  189. }
  190. }
  191. } else {
  192. // The regex above verified that we have a .-separated string of
  193. // non-negative integer components. Keep the original string.
  194. version_string = std::move(*prArgs.Version);
  195. // Split the integer components.
  196. auto components = cmSystemTools::SplitString(version_string, '.');
  197. for (auto i = 0u; i < components.size(); ++i) {
  198. version_components[i] = std::move(components[i]);
  199. }
  200. }
  201. }
  202. if (prArgs.CompatVersion) {
  203. if (!vx.find(*prArgs.CompatVersion)) {
  204. std::string e =
  205. R"(COMPAT_VERSION ")" + *prArgs.CompatVersion + R"(" format invalid.)";
  206. mf.IssueMessage(MessageType::FATAL_ERROR, e);
  207. cmSystemTools::SetFatalErrorOccurred();
  208. return true;
  209. }
  210. if (cmSystemTools::VersionCompareGreater(*prArgs.CompatVersion,
  211. version_string)) {
  212. mf.IssueMessage(MessageType::FATAL_ERROR,
  213. "COMPAT_VERSION must be less than or equal to VERSION");
  214. cmSystemTools::SetFatalErrorOccurred();
  215. return true;
  216. }
  217. }
  218. auto createVariables = [&](cm::string_view var, std::string const& val) {
  219. mf.AddDefinition(cmStrCat("PROJECT_"_s, var), val);
  220. mf.AddDefinition(cmStrCat(*prArgs.ProjectName, "_"_s, var), val);
  221. TopLevelCMakeVarCondSet(mf, cmStrCat("CMAKE_PROJECT_"_s, var), val);
  222. };
  223. createVariables("VERSION"_s, version_string);
  224. createVariables("VERSION_MAJOR"_s, version_components[0]);
  225. createVariables("VERSION_MINOR"_s, version_components[1]);
  226. createVariables("VERSION_PATCH"_s, version_components[2]);
  227. createVariables("VERSION_TWEAK"_s, version_components[3]);
  228. createVariables("COMPAT_VERSION"_s, prArgs.CompatVersion.value_or(""));
  229. createVariables("SPDX_LICENSE"_s, prArgs.License.value_or(""));
  230. createVariables("DESCRIPTION"_s, prArgs.Description.value_or(""));
  231. createVariables("HOMEPAGE_URL"_s, prArgs.HomepageURL.value_or(""));
  232. if (unparsedArgs.empty() && !prArgs.Languages) {
  233. // if no language is specified do c and c++
  234. mf.EnableLanguage({ "C", "CXX" }, false);
  235. } else {
  236. if (!unparsedArgs.empty()) {
  237. mf.EnableLanguage(unparsedArgs, false);
  238. }
  239. if (prArgs.Languages) {
  240. mf.EnableLanguage(*prArgs.Languages, false);
  241. }
  242. }
  243. if (!IncludeByVariable(status, "CMAKE_PROJECT_INCLUDE")) {
  244. return false;
  245. }
  246. if (!IncludeByVariable(
  247. status, "CMAKE_PROJECT_" + *prArgs.ProjectName + "_INCLUDE")) {
  248. return false;
  249. }
  250. return true;
  251. }
  252. namespace {
  253. bool IncludeByVariable(cmExecutionStatus& status, std::string const& variable)
  254. {
  255. cmMakefile& mf = status.GetMakefile();
  256. cmValue include = mf.GetDefinition(variable);
  257. if (!include) {
  258. return true;
  259. }
  260. cmList includeFiles{ *include };
  261. bool failed = false;
  262. for (auto filePath : includeFiles) {
  263. // Any relative path without a .cmake extension is checked for valid cmake
  264. // modules. This logic should be consistent with CMake's include() command.
  265. // Otherwise default to checking relative path w.r.t. source directory
  266. if (!cmSystemTools::FileIsFullPath(filePath) &&
  267. !cmHasLiteralSuffix(filePath, ".cmake")) {
  268. std::string mfile = mf.GetModulesFile(cmStrCat(filePath, ".cmake"));
  269. if (mfile.empty()) {
  270. status.SetError(
  271. cmStrCat("could not find requested module:\n ", filePath));
  272. failed = true;
  273. continue;
  274. }
  275. filePath = mfile;
  276. }
  277. std::string includeFile = cmSystemTools::CollapseFullPath(
  278. filePath, mf.GetCurrentSourceDirectory());
  279. if (!cmSystemTools::FileExists(includeFile)) {
  280. status.SetError(
  281. cmStrCat("could not find requested file:\n ", filePath));
  282. failed = true;
  283. continue;
  284. }
  285. if (cmSystemTools::FileIsDirectory(includeFile)) {
  286. status.SetError(
  287. cmStrCat("requested file is a directory:\n ", filePath));
  288. failed = true;
  289. continue;
  290. }
  291. bool const readit = mf.ReadDependentFile(filePath);
  292. if (readit) {
  293. // If the included file ran successfully, continue to the next file
  294. continue;
  295. }
  296. if (cmSystemTools::GetFatalErrorOccurred()) {
  297. failed = true;
  298. continue;
  299. }
  300. status.SetError(cmStrCat("could not load requested file:\n ", filePath));
  301. failed = true;
  302. }
  303. // At this point all files were processed
  304. return !failed;
  305. }
  306. void TopLevelCMakeVarCondSet(cmMakefile& mf, std::string const& name,
  307. std::string const& value)
  308. {
  309. // Set the CMAKE_PROJECT_XXX variable to be the highest-level
  310. // project name in the tree. If there are two project commands
  311. // in the same CMakeLists.txt file, and it is the top level
  312. // CMakeLists.txt file, then go with the last one.
  313. if (!mf.GetDefinition(name) || mf.IsRootMakefile()) {
  314. mf.RemoveDefinition(name);
  315. mf.AddCacheDefinition(name, value, "Value Computed by CMake",
  316. cmStateEnums::STATIC);
  317. }
  318. }
  319. }