cmFindPackageCommand.cxx 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmFindPackageCommand.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cstdio>
  7. #include <cstring>
  8. #include <deque>
  9. #include <functional>
  10. #include <iterator>
  11. #include <sstream>
  12. #include <utility>
  13. #include <cm/memory>
  14. #include <cmext/string_view>
  15. #include "cmsys/Directory.hxx"
  16. #include "cmsys/FStream.hxx"
  17. #include "cmsys/Glob.hxx"
  18. #include "cmsys/RegularExpression.hxx"
  19. #include "cmsys/String.h"
  20. #include "cmAlgorithms.h"
  21. #include "cmMakefile.h"
  22. #include "cmMessageType.h"
  23. #include "cmPolicies.h"
  24. #include "cmRange.h"
  25. #include "cmSearchPath.h"
  26. #include "cmState.h"
  27. #include "cmStateTypes.h"
  28. #include "cmStringAlgorithms.h"
  29. #include "cmSystemTools.h"
  30. #include "cmValue.h"
  31. #include "cmVersion.h"
  32. #if defined(__HAIKU__)
  33. # include <FindDirectory.h>
  34. # include <StorageDefs.h>
  35. #endif
  36. class cmExecutionStatus;
  37. class cmFileList;
  38. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::UserRegistry(
  39. "PACKAGE_REGISTRY");
  40. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::Builds(
  41. "BUILDS");
  42. cmFindPackageCommand::PathLabel
  43. cmFindPackageCommand::PathLabel::SystemRegistry("SYSTEM_PACKAGE_REGISTRY");
  44. const cm::string_view cmFindPackageCommand::VERSION_ENDPOINT_INCLUDED(
  45. "INCLUDE");
  46. const cm::string_view cmFindPackageCommand::VERSION_ENDPOINT_EXCLUDED(
  47. "EXCLUDE");
  48. struct StrverscmpGreater
  49. {
  50. bool operator()(const std::string& lhs, const std::string& rhs) const
  51. {
  52. return cmSystemTools::strverscmp(lhs, rhs) > 0;
  53. }
  54. };
  55. struct StrverscmpLesser
  56. {
  57. bool operator()(const std::string& lhs, const std::string& rhs) const
  58. {
  59. return cmSystemTools::strverscmp(lhs, rhs) < 0;
  60. }
  61. };
  62. void cmFindPackageCommand::Sort(std::vector<std::string>::iterator begin,
  63. std::vector<std::string>::iterator end,
  64. SortOrderType order, SortDirectionType dir)
  65. {
  66. if (order == Name_order) {
  67. if (dir == Dec) {
  68. std::sort(begin, end, std::greater<std::string>());
  69. } else {
  70. std::sort(begin, end);
  71. }
  72. } else if (order == Natural)
  73. // natural order uses letters and numbers (contiguous numbers digit are
  74. // compared such that e.g. 000 00 < 01 < 010 < 09 < 0 < 1 < 9 < 10
  75. {
  76. if (dir == Dec) {
  77. std::sort(begin, end, StrverscmpGreater());
  78. } else {
  79. std::sort(begin, end, StrverscmpLesser());
  80. }
  81. }
  82. // else do not sort
  83. }
  84. cmFindPackageCommand::cmFindPackageCommand(cmExecutionStatus& status)
  85. : cmFindCommon(status)
  86. , VersionRangeMin(VERSION_ENDPOINT_INCLUDED)
  87. , VersionRangeMax(VERSION_ENDPOINT_INCLUDED)
  88. {
  89. this->CMakePathName = "PACKAGE";
  90. this->DebugMode = false;
  91. this->AppendSearchPathGroups();
  92. this->DeprecatedFindModules["Qt"] = cmPolicies::CMP0084;
  93. }
  94. void cmFindPackageCommand::AppendSearchPathGroups()
  95. {
  96. std::vector<cmFindCommon::PathLabel>* labels;
  97. // Update the All group with new paths
  98. labels = &this->PathGroupLabelMap[PathGroup::All];
  99. labels->insert(
  100. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  101. PathLabel::UserRegistry);
  102. labels->insert(
  103. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  104. PathLabel::Builds);
  105. labels->insert(std::find(labels->begin(), labels->end(), PathLabel::Guess),
  106. PathLabel::SystemRegistry);
  107. // Create the new path objects
  108. this->LabeledPaths.insert(
  109. std::make_pair(PathLabel::UserRegistry, cmSearchPath(this)));
  110. this->LabeledPaths.insert(
  111. std::make_pair(PathLabel::Builds, cmSearchPath(this)));
  112. this->LabeledPaths.insert(
  113. std::make_pair(PathLabel::SystemRegistry, cmSearchPath(this)));
  114. }
  115. bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args)
  116. {
  117. if (args.empty()) {
  118. this->SetError("called with incorrect number of arguments");
  119. return false;
  120. }
  121. // Lookup required version of CMake.
  122. if (cmValue rv =
  123. this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION")) {
  124. unsigned int v[3] = { 0, 0, 0 };
  125. sscanf(rv->c_str(), "%u.%u.%u", &v[0], &v[1], &v[2]);
  126. this->RequiredCMakeVersion = CMake_VERSION_ENCODE(v[0], v[1], v[2]);
  127. }
  128. // Lookup target architecture, if any.
  129. if (cmValue arch =
  130. this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE")) {
  131. this->LibraryArchitecture = *arch;
  132. }
  133. // Lookup whether lib32 paths should be used.
  134. if (this->Makefile->PlatformIs32Bit() &&
  135. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  136. "FIND_LIBRARY_USE_LIB32_PATHS")) {
  137. this->UseLib32Paths = true;
  138. }
  139. // Lookup whether lib64 paths should be used.
  140. if (this->Makefile->PlatformIs64Bit() &&
  141. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  142. "FIND_LIBRARY_USE_LIB64_PATHS")) {
  143. this->UseLib64Paths = true;
  144. }
  145. // Lookup whether libx32 paths should be used.
  146. if (this->Makefile->PlatformIsx32() &&
  147. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  148. "FIND_LIBRARY_USE_LIBX32_PATHS")) {
  149. this->UseLibx32Paths = true;
  150. }
  151. // Check if User Package Registry should be disabled
  152. // The `CMAKE_FIND_USE_PACKAGE_REGISTRY` has
  153. // priority over the deprecated CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY
  154. if (cmValue def =
  155. this->Makefile->GetDefinition("CMAKE_FIND_USE_PACKAGE_REGISTRY")) {
  156. this->NoUserRegistry = !cmIsOn(*def);
  157. } else if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY")) {
  158. this->NoUserRegistry = true;
  159. }
  160. // Check if System Package Registry should be disabled
  161. // The `CMAKE_FIND_USE_SYSTEM_PACKAGE_REGISTRY` has
  162. // priority over the deprecated CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY
  163. if (cmValue def = this->Makefile->GetDefinition(
  164. "CMAKE_FIND_USE_SYSTEM_PACKAGE_REGISTRY")) {
  165. this->NoSystemRegistry = !cmIsOn(*def);
  166. } else if (this->Makefile->IsOn(
  167. "CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY")) {
  168. this->NoSystemRegistry = true;
  169. }
  170. // Check whether we should resolve symlinks when finding packages
  171. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS")) {
  172. this->UseRealPath = true;
  173. }
  174. // Check if Sorting should be enabled
  175. if (cmValue so =
  176. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_ORDER")) {
  177. if (*so == "NAME") {
  178. this->SortOrder = Name_order;
  179. } else if (*so == "NATURAL") {
  180. this->SortOrder = Natural;
  181. } else {
  182. this->SortOrder = None;
  183. }
  184. }
  185. if (cmValue sd =
  186. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_DIRECTION")) {
  187. this->SortDirection = (*sd == "ASC") ? Asc : Dec;
  188. }
  189. // Find what search path locations have been enabled/disable
  190. this->SelectDefaultSearchModes();
  191. // Find the current root path mode.
  192. this->SelectDefaultRootPathMode();
  193. // Find the current bundle/framework search policy.
  194. this->SelectDefaultMacMode();
  195. // Record options.
  196. this->Name = args[0];
  197. std::string components;
  198. const char* components_sep = "";
  199. std::set<std::string> requiredComponents;
  200. std::set<std::string> optionalComponents;
  201. // Always search directly in a generated path.
  202. this->SearchPathSuffixes.emplace_back();
  203. // Process debug mode
  204. cmMakefile::DebugFindPkgRAII debugFindPkgRAII(this->Makefile, this->Name);
  205. this->DebugMode = this->ComputeIfDebugModeWanted();
  206. // Parse the arguments.
  207. enum Doing
  208. {
  209. DoingNone,
  210. DoingComponents,
  211. DoingOptionalComponents,
  212. DoingNames,
  213. DoingPaths,
  214. DoingPathSuffixes,
  215. DoingConfigs,
  216. DoingHints
  217. };
  218. Doing doing = DoingNone;
  219. cmsys::RegularExpression versionRegex(
  220. R"V(^([0-9]+(\.[0-9]+)*)(\.\.\.(<?)([0-9]+(\.[0-9]+)*))?$)V");
  221. bool haveVersion = false;
  222. std::set<unsigned int> configArgs;
  223. std::set<unsigned int> moduleArgs;
  224. for (unsigned int i = 1; i < args.size(); ++i) {
  225. if (args[i] == "QUIET") {
  226. this->Quiet = true;
  227. doing = DoingNone;
  228. } else if (args[i] == "EXACT") {
  229. this->VersionExact = true;
  230. doing = DoingNone;
  231. } else if (args[i] == "MODULE") {
  232. moduleArgs.insert(i);
  233. doing = DoingNone;
  234. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  235. // NOLINTNEXTLINE(bugprone-branch-clone)
  236. } else if (args[i] == "CONFIG") {
  237. configArgs.insert(i);
  238. doing = DoingNone;
  239. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  240. // NOLINTNEXTLINE(bugprone-branch-clone)
  241. } else if (args[i] == "NO_MODULE") {
  242. configArgs.insert(i);
  243. doing = DoingNone;
  244. } else if (args[i] == "REQUIRED") {
  245. this->Required = true;
  246. doing = DoingComponents;
  247. } else if (args[i] == "COMPONENTS") {
  248. doing = DoingComponents;
  249. } else if (args[i] == "OPTIONAL_COMPONENTS") {
  250. doing = DoingOptionalComponents;
  251. } else if (args[i] == "NAMES") {
  252. configArgs.insert(i);
  253. doing = DoingNames;
  254. } else if (args[i] == "PATHS") {
  255. configArgs.insert(i);
  256. doing = DoingPaths;
  257. } else if (args[i] == "HINTS") {
  258. configArgs.insert(i);
  259. doing = DoingHints;
  260. } else if (args[i] == "PATH_SUFFIXES") {
  261. configArgs.insert(i);
  262. doing = DoingPathSuffixes;
  263. } else if (args[i] == "CONFIGS") {
  264. configArgs.insert(i);
  265. doing = DoingConfigs;
  266. } else if (args[i] == "NO_POLICY_SCOPE") {
  267. this->PolicyScope = false;
  268. doing = DoingNone;
  269. } else if (args[i] == "NO_CMAKE_PACKAGE_REGISTRY") {
  270. this->NoUserRegistry = true;
  271. configArgs.insert(i);
  272. doing = DoingNone;
  273. } else if (args[i] == "NO_CMAKE_SYSTEM_PACKAGE_REGISTRY") {
  274. this->NoSystemRegistry = true;
  275. configArgs.insert(i);
  276. doing = DoingNone;
  277. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  278. // NOLINTNEXTLINE(bugprone-branch-clone)
  279. } else if (args[i] == "NO_CMAKE_BUILDS_PATH") {
  280. // Ignore legacy option.
  281. configArgs.insert(i);
  282. doing = DoingNone;
  283. } else if (this->CheckCommonArgument(args[i])) {
  284. configArgs.insert(i);
  285. doing = DoingNone;
  286. } else if ((doing == DoingComponents) ||
  287. (doing == DoingOptionalComponents)) {
  288. // Set a variable telling the find script whether this component
  289. // is required.
  290. const char* isRequired = "1";
  291. if (doing == DoingOptionalComponents) {
  292. isRequired = "0";
  293. optionalComponents.insert(args[i]);
  294. } else {
  295. requiredComponents.insert(args[i]);
  296. }
  297. std::string req_var = this->Name + "_FIND_REQUIRED_" + args[i];
  298. this->AddFindDefinition(req_var, isRequired);
  299. // Append to the list of required components.
  300. components += components_sep;
  301. components += args[i];
  302. components_sep = ";";
  303. } else if (doing == DoingNames) {
  304. this->Names.push_back(args[i]);
  305. } else if (doing == DoingPaths) {
  306. this->UserGuessArgs.push_back(args[i]);
  307. } else if (doing == DoingHints) {
  308. this->UserHintsArgs.push_back(args[i]);
  309. } else if (doing == DoingPathSuffixes) {
  310. this->AddPathSuffix(args[i]);
  311. } else if (doing == DoingConfigs) {
  312. if (args[i].find_first_of(":/\\") != std::string::npos ||
  313. cmSystemTools::GetFilenameLastExtension(args[i]) != ".cmake") {
  314. this->SetError(cmStrCat(
  315. "given CONFIGS option followed by invalid file name \"", args[i],
  316. "\". The names given must be file names without "
  317. "a path and with a \".cmake\" extension."));
  318. return false;
  319. }
  320. this->Configs.push_back(args[i]);
  321. } else if (!haveVersion && versionRegex.find(args[i])) {
  322. haveVersion = true;
  323. this->VersionComplete = args[i];
  324. } else {
  325. this->SetError(
  326. cmStrCat("called with invalid argument \"", args[i], "\""));
  327. return false;
  328. }
  329. }
  330. std::vector<std::string> doubledComponents;
  331. std::set_intersection(requiredComponents.begin(), requiredComponents.end(),
  332. optionalComponents.begin(), optionalComponents.end(),
  333. std::back_inserter(doubledComponents));
  334. if (!doubledComponents.empty()) {
  335. this->SetError(
  336. cmStrCat("called with components that are both required and "
  337. "optional:\n",
  338. cmWrap(" ", doubledComponents, "", "\n"), "\n"));
  339. return false;
  340. }
  341. // Maybe choose one mode exclusively.
  342. this->UseFindModules = configArgs.empty();
  343. this->UseConfigFiles = moduleArgs.empty();
  344. if (!this->UseFindModules && !this->UseConfigFiles) {
  345. std::ostringstream e;
  346. e << "given options exclusive to Module mode:\n";
  347. for (unsigned int si : moduleArgs) {
  348. e << " " << args[si] << "\n";
  349. }
  350. e << "and options exclusive to Config mode:\n";
  351. for (unsigned int si : configArgs) {
  352. e << " " << args[si] << "\n";
  353. }
  354. e << "The options are incompatible.";
  355. this->SetError(e.str());
  356. return false;
  357. }
  358. // Ignore EXACT with no version.
  359. if (this->VersionComplete.empty() && this->VersionExact) {
  360. this->VersionExact = false;
  361. this->Makefile->IssueMessage(
  362. MessageType::AUTHOR_WARNING,
  363. "Ignoring EXACT since no version is requested.");
  364. }
  365. if (this->VersionComplete.empty() || components.empty()) {
  366. // Check whether we are recursing inside "Find<name>.cmake" within
  367. // another find_package(<name>) call.
  368. std::string mod = cmStrCat(this->Name, "_FIND_MODULE");
  369. if (this->Makefile->IsOn(mod)) {
  370. if (this->VersionComplete.empty()) {
  371. // Get version information from the outer call if necessary.
  372. // Requested version string.
  373. std::string ver = cmStrCat(this->Name, "_FIND_VERSION_COMPLETE");
  374. this->VersionComplete = this->Makefile->GetSafeDefinition(ver);
  375. // Whether an exact version is required.
  376. std::string exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT");
  377. this->VersionExact = this->Makefile->IsOn(exact);
  378. }
  379. if (components.empty()) {
  380. std::string components_var = this->Name + "_FIND_COMPONENTS";
  381. components = this->Makefile->GetSafeDefinition(components_var);
  382. }
  383. }
  384. }
  385. // fill various parts of version specification
  386. if (!this->VersionComplete.empty()) {
  387. if (!versionRegex.find(this->VersionComplete)) {
  388. this->SetError("called with invalid version specification.");
  389. return false;
  390. }
  391. this->Version = versionRegex.match(1);
  392. this->VersionMax = versionRegex.match(5);
  393. if (versionRegex.match(4) == "<"_s) {
  394. this->VersionRangeMax = VERSION_ENDPOINT_EXCLUDED;
  395. }
  396. if (!this->VersionMax.empty()) {
  397. this->VersionRange = this->VersionComplete;
  398. }
  399. }
  400. if (!this->VersionRange.empty()) {
  401. // version range must not be empty
  402. if ((this->VersionRangeMax == VERSION_ENDPOINT_INCLUDED &&
  403. cmSystemTools::VersionCompareGreater(this->Version,
  404. this->VersionMax)) ||
  405. (this->VersionRangeMax == VERSION_ENDPOINT_EXCLUDED &&
  406. cmSystemTools::VersionCompareGreaterEq(this->Version,
  407. this->VersionMax))) {
  408. this->SetError("specified version range is empty.");
  409. return false;
  410. }
  411. }
  412. if (this->VersionExact && !this->VersionRange.empty()) {
  413. this->SetError("EXACT cannot be specified with a version range.");
  414. return false;
  415. }
  416. // Parse the version number and store the results that were
  417. // successfully parsed.
  418. auto parseVersion = [](const std::string& version, unsigned int& major,
  419. unsigned int& minor, unsigned int& patch,
  420. unsigned int& tweak) -> unsigned int {
  421. return sscanf(version.c_str(), "%u.%u.%u.%u", &major, &minor, &patch,
  422. &tweak);
  423. };
  424. if (!this->Version.empty()) {
  425. this->VersionCount =
  426. parseVersion(this->Version, this->VersionMajor, this->VersionMinor,
  427. this->VersionPatch, this->VersionTweak);
  428. }
  429. if (!this->VersionMax.empty()) {
  430. this->VersionMaxCount = parseVersion(
  431. this->VersionMax, this->VersionMaxMajor, this->VersionMaxMinor,
  432. this->VersionMaxPatch, this->VersionMaxTweak);
  433. }
  434. const std::string makePackageRequiredVar =
  435. cmStrCat("CMAKE_REQUIRE_FIND_PACKAGE_", this->Name);
  436. const bool makePackageRequiredSet =
  437. this->Makefile->IsOn(makePackageRequiredVar);
  438. if (makePackageRequiredSet) {
  439. if (this->Required) {
  440. this->Makefile->IssueMessage(
  441. MessageType::WARNING,
  442. cmStrCat("for module ", this->Name,
  443. " already called with REQUIRED, thus ",
  444. makePackageRequiredVar, " has no effect."));
  445. } else {
  446. this->Required = true;
  447. }
  448. }
  449. std::string disableFindPackageVar =
  450. cmStrCat("CMAKE_DISABLE_FIND_PACKAGE_", this->Name);
  451. if (this->Makefile->IsOn(disableFindPackageVar)) {
  452. if (this->Required) {
  453. this->SetError(
  454. cmStrCat("for module ", this->Name,
  455. (makePackageRequiredSet
  456. ? " was made REQUIRED with " + makePackageRequiredVar
  457. : " called with REQUIRED, "),
  458. " but ", disableFindPackageVar,
  459. " is enabled. A REQUIRED package cannot be disabled."));
  460. return false;
  461. }
  462. return true;
  463. }
  464. {
  465. // Allocate a PACKAGE_ROOT_PATH for the current find_package call.
  466. this->Makefile->FindPackageRootPathStack.emplace_back();
  467. std::vector<std::string>& rootPaths =
  468. this->Makefile->FindPackageRootPathStack.back();
  469. // Add root paths from <PackageName>_ROOT CMake and environment variables,
  470. // subject to CMP0074.
  471. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0074)) {
  472. case cmPolicies::WARN:
  473. this->Makefile->MaybeWarnCMP0074(this->Name);
  474. CM_FALLTHROUGH;
  475. case cmPolicies::OLD:
  476. // OLD behavior is to ignore the <pkg>_ROOT variables.
  477. break;
  478. case cmPolicies::REQUIRED_IF_USED:
  479. case cmPolicies::REQUIRED_ALWAYS:
  480. this->Makefile->IssueMessage(
  481. MessageType::FATAL_ERROR,
  482. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0074));
  483. break;
  484. case cmPolicies::NEW: {
  485. // NEW behavior is to honor the <pkg>_ROOT variables.
  486. std::string const rootVar = this->Name + "_ROOT";
  487. this->Makefile->GetDefExpandList(rootVar, rootPaths, false);
  488. cmSystemTools::GetPath(rootPaths, rootVar.c_str());
  489. } break;
  490. }
  491. }
  492. this->SetModuleVariables(components);
  493. // See if there is a Find<PackageName>.cmake module.
  494. bool loadedPackage = false;
  495. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  496. if (this->UseConfigFiles && this->FindPackageUsingConfigMode()) {
  497. loadedPackage = true;
  498. } else {
  499. if (this->FindPackageUsingModuleMode()) {
  500. loadedPackage = true;
  501. } else {
  502. // The package was not loaded. Report errors.
  503. if (this->HandlePackageMode(HandlePackageModeType::Module)) {
  504. loadedPackage = true;
  505. }
  506. }
  507. }
  508. } else {
  509. if (this->UseFindModules && this->FindPackageUsingModuleMode()) {
  510. loadedPackage = true;
  511. } else {
  512. // Handle CMAKE_FIND_PACKAGE_WARN_NO_MODULE (warn when CONFIG mode is
  513. // implicitly assumed)
  514. if (this->UseFindModules && this->UseConfigFiles &&
  515. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_WARN_NO_MODULE")) {
  516. std::ostringstream aw;
  517. if (this->RequiredCMakeVersion >= CMake_VERSION_ENCODE(2, 8, 8)) {
  518. aw << "find_package called without either MODULE or CONFIG option "
  519. "and "
  520. "no Find"
  521. << this->Name
  522. << ".cmake module is in CMAKE_MODULE_PATH. "
  523. "Add MODULE to exclusively request Module mode and fail if "
  524. "Find"
  525. << this->Name
  526. << ".cmake is missing. "
  527. "Add CONFIG to exclusively request Config mode and search for "
  528. "a "
  529. "package configuration file provided by "
  530. << this->Name << " (" << this->Name << "Config.cmake or "
  531. << cmSystemTools::LowerCase(this->Name) << "-config.cmake). ";
  532. } else {
  533. aw << "find_package called without NO_MODULE option and no "
  534. "Find"
  535. << this->Name
  536. << ".cmake module is in CMAKE_MODULE_PATH. "
  537. "Add NO_MODULE to exclusively request Config mode and search "
  538. "for a "
  539. "package configuration file provided by "
  540. << this->Name << " (" << this->Name << "Config.cmake or "
  541. << cmSystemTools::LowerCase(this->Name)
  542. << "-config.cmake). "
  543. "Otherwise make Find"
  544. << this->Name
  545. << ".cmake available in "
  546. "CMAKE_MODULE_PATH.";
  547. }
  548. aw << "\n"
  549. "(Variable CMAKE_FIND_PACKAGE_WARN_NO_MODULE enabled this "
  550. "warning.)";
  551. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  552. }
  553. if (this->FindPackageUsingConfigMode()) {
  554. loadedPackage = true;
  555. }
  556. }
  557. }
  558. this->AppendSuccessInformation();
  559. if (!this->DebugBuffer.empty()) {
  560. this->DebugMessage(this->DebugBuffer);
  561. }
  562. return loadedPackage;
  563. }
  564. bool cmFindPackageCommand::FindPackageUsingModuleMode()
  565. {
  566. bool foundModule = false;
  567. if (!this->FindModule(foundModule)) {
  568. return false;
  569. }
  570. return foundModule;
  571. }
  572. bool cmFindPackageCommand::FindPackageUsingConfigMode()
  573. {
  574. this->Variable = cmStrCat(this->Name, "_DIR");
  575. // Add the default name.
  576. if (this->Names.empty()) {
  577. this->Names.push_back(this->Name);
  578. }
  579. // Add the default configs.
  580. if (this->Configs.empty()) {
  581. for (std::string const& n : this->Names) {
  582. std::string config = cmStrCat(n, "Config.cmake");
  583. this->Configs.push_back(config);
  584. config = cmStrCat(cmSystemTools::LowerCase(n), "-config.cmake");
  585. this->Configs.push_back(std::move(config));
  586. }
  587. }
  588. // get igonored paths from vars and reroot them.
  589. std::vector<std::string> ignored;
  590. this->GetIgnoredPaths(ignored);
  591. this->RerootPaths(ignored);
  592. // Construct a set of ignored paths
  593. this->IgnoredPaths.clear();
  594. this->IgnoredPaths.insert(ignored.begin(), ignored.end());
  595. // get igonored prefix paths from vars and reroot them.
  596. std::vector<std::string> ignoredPrefixes;
  597. this->GetIgnoredPrefixPaths(ignoredPrefixes);
  598. this->RerootPaths(ignoredPrefixes);
  599. // Construct a set of ignored prefix paths
  600. this->IgnoredPrefixPaths.clear();
  601. this->IgnoredPrefixPaths.insert(ignoredPrefixes.begin(),
  602. ignoredPrefixes.end());
  603. // Find and load the package.
  604. return this->HandlePackageMode(HandlePackageModeType::Config);
  605. }
  606. void cmFindPackageCommand::SetVersionVariables(
  607. const std::function<void(const std::string&, cm::string_view)>&
  608. addDefinition,
  609. const std::string& prefix, const std::string& version, unsigned int count,
  610. unsigned int major, unsigned int minor, unsigned int patch,
  611. unsigned int tweak)
  612. {
  613. addDefinition(prefix, version);
  614. char buf[64];
  615. snprintf(buf, sizeof(buf), "%u", major);
  616. addDefinition(prefix + "_MAJOR", buf);
  617. sprintf(buf, "%u", minor);
  618. addDefinition(prefix + "_MINOR", buf);
  619. sprintf(buf, "%u", patch);
  620. addDefinition(prefix + "_PATCH", buf);
  621. sprintf(buf, "%u", tweak);
  622. addDefinition(prefix + "_TWEAK", buf);
  623. sprintf(buf, "%u", count);
  624. addDefinition(prefix + "_COUNT", buf);
  625. }
  626. void cmFindPackageCommand::SetModuleVariables(const std::string& components)
  627. {
  628. this->AddFindDefinition("CMAKE_FIND_PACKAGE_NAME", this->Name);
  629. // Store the list of components.
  630. std::string components_var = this->Name + "_FIND_COMPONENTS";
  631. this->AddFindDefinition(components_var, components);
  632. if (this->Quiet) {
  633. // Tell the module that is about to be read that it should find
  634. // quietly.
  635. std::string quietly = cmStrCat(this->Name, "_FIND_QUIETLY");
  636. this->AddFindDefinition(quietly, "1"_s);
  637. }
  638. if (this->Required) {
  639. // Tell the module that is about to be read that it should report
  640. // a fatal error if the package is not found.
  641. std::string req = cmStrCat(this->Name, "_FIND_REQUIRED");
  642. this->AddFindDefinition(req, "1"_s);
  643. }
  644. if (!this->VersionComplete.empty()) {
  645. std::string req = cmStrCat(this->Name, "_FIND_VERSION_COMPLETE");
  646. this->AddFindDefinition(req, this->VersionComplete);
  647. }
  648. // Tell the module that is about to be read what version of the
  649. // package has been requested.
  650. auto addDefinition = [this](const std::string& variable,
  651. cm::string_view value) {
  652. this->AddFindDefinition(variable, value);
  653. };
  654. if (!this->Version.empty()) {
  655. auto prefix = cmStrCat(this->Name, "_FIND_VERSION"_s);
  656. this->SetVersionVariables(addDefinition, prefix, this->Version,
  657. this->VersionCount, this->VersionMajor,
  658. this->VersionMinor, this->VersionPatch,
  659. this->VersionTweak);
  660. // Tell the module whether an exact version has been requested.
  661. auto exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT");
  662. this->AddFindDefinition(exact, this->VersionExact ? "1"_s : "0"_s);
  663. }
  664. if (!this->VersionRange.empty()) {
  665. auto prefix = cmStrCat(this->Name, "_FIND_VERSION_MIN"_s);
  666. this->SetVersionVariables(addDefinition, prefix, this->Version,
  667. this->VersionCount, this->VersionMajor,
  668. this->VersionMinor, this->VersionPatch,
  669. this->VersionTweak);
  670. prefix = cmStrCat(this->Name, "_FIND_VERSION_MAX"_s);
  671. this->SetVersionVariables(addDefinition, prefix, this->VersionMax,
  672. this->VersionMaxCount, this->VersionMaxMajor,
  673. this->VersionMaxMinor, this->VersionMaxPatch,
  674. this->VersionMaxTweak);
  675. auto id = cmStrCat(this->Name, "_FIND_VERSION_RANGE");
  676. this->AddFindDefinition(id, this->VersionRange);
  677. id = cmStrCat(this->Name, "_FIND_VERSION_RANGE_MIN");
  678. this->AddFindDefinition(id, this->VersionRangeMin);
  679. id = cmStrCat(this->Name, "_FIND_VERSION_RANGE_MAX");
  680. this->AddFindDefinition(id, this->VersionRangeMax);
  681. }
  682. }
  683. void cmFindPackageCommand::AddFindDefinition(const std::string& var,
  684. cm::string_view value)
  685. {
  686. if (cmValue old = this->Makefile->GetDefinition(var)) {
  687. this->OriginalDefs[var].exists = true;
  688. this->OriginalDefs[var].value = *old;
  689. } else {
  690. this->OriginalDefs[var].exists = false;
  691. }
  692. this->Makefile->AddDefinition(var, value);
  693. }
  694. void cmFindPackageCommand::RestoreFindDefinitions()
  695. {
  696. for (auto const& i : this->OriginalDefs) {
  697. OriginalDef const& od = i.second;
  698. if (od.exists) {
  699. this->Makefile->AddDefinition(i.first, od.value);
  700. } else {
  701. this->Makefile->RemoveDefinition(i.first);
  702. }
  703. }
  704. }
  705. bool cmFindPackageCommand::FindModule(bool& found)
  706. {
  707. std::string moduleFileName = cmStrCat("Find", this->Name, ".cmake");
  708. bool system = false;
  709. std::string debugBuffer = cmStrCat(
  710. "find_package considered the following paths for ", moduleFileName, ":\n");
  711. std::string mfile = this->Makefile->GetModulesFile(
  712. moduleFileName, system, this->DebugMode, debugBuffer);
  713. if (this->DebugMode) {
  714. if (mfile.empty()) {
  715. debugBuffer = cmStrCat(debugBuffer, "The file was not found.\n");
  716. } else {
  717. debugBuffer =
  718. cmStrCat(debugBuffer, "The file was found at\n ", mfile, "\n");
  719. }
  720. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  721. }
  722. if (!mfile.empty()) {
  723. if (system) {
  724. auto it = this->DeprecatedFindModules.find(this->Name);
  725. if (it != this->DeprecatedFindModules.end()) {
  726. cmPolicies::PolicyStatus status =
  727. this->Makefile->GetPolicyStatus(it->second);
  728. switch (status) {
  729. case cmPolicies::WARN: {
  730. this->Makefile->IssueMessage(
  731. MessageType::AUTHOR_WARNING,
  732. cmStrCat(cmPolicies::GetPolicyWarning(it->second), "\n"));
  733. CM_FALLTHROUGH;
  734. }
  735. case cmPolicies::OLD:
  736. break;
  737. case cmPolicies::REQUIRED_IF_USED:
  738. case cmPolicies::REQUIRED_ALWAYS:
  739. case cmPolicies::NEW:
  740. return true;
  741. }
  742. }
  743. }
  744. // Load the module we found, and set "<name>_FIND_MODULE" to true
  745. // while inside it.
  746. found = true;
  747. std::string var = cmStrCat(this->Name, "_FIND_MODULE");
  748. this->Makefile->AddDefinition(var, "1");
  749. bool result = this->ReadListFile(mfile, DoPolicyScope);
  750. this->Makefile->RemoveDefinition(var);
  751. if (this->DebugMode) {
  752. std::string foundVar = cmStrCat(this->Name, "_FOUND");
  753. if (this->Makefile->IsDefinitionSet(foundVar) &&
  754. !this->Makefile->IsOn(foundVar)) {
  755. this->DebugBuffer = cmStrCat(
  756. this->DebugBuffer, "The module is considered not found due to ",
  757. foundVar, " being FALSE.");
  758. }
  759. }
  760. return result;
  761. }
  762. return true;
  763. }
  764. bool cmFindPackageCommand::HandlePackageMode(
  765. HandlePackageModeType handlePackageModeType)
  766. {
  767. this->ConsideredConfigs.clear();
  768. // Try to find the config file.
  769. cmValue def = this->Makefile->GetDefinition(this->Variable);
  770. // Try to load the config file if the directory is known
  771. bool fileFound = false;
  772. if (this->UseConfigFiles) {
  773. if (!cmIsOff(def)) {
  774. // Get the directory from the variable value.
  775. std::string dir = *def;
  776. cmSystemTools::ConvertToUnixSlashes(dir);
  777. // Treat relative paths with respect to the current source dir.
  778. if (!cmSystemTools::FileIsFullPath(dir)) {
  779. dir = "/" + dir;
  780. dir = this->Makefile->GetCurrentSourceDirectory() + dir;
  781. }
  782. // The file location was cached. Look for the correct file.
  783. std::string file;
  784. if (this->FindConfigFile(dir, file)) {
  785. this->FileFound = file;
  786. fileFound = true;
  787. }
  788. def = this->Makefile->GetDefinition(this->Variable);
  789. }
  790. // Search for the config file if it is not already found.
  791. if (cmIsOff(def) || !fileFound) {
  792. fileFound = this->FindConfig();
  793. }
  794. // Sanity check.
  795. if (fileFound && this->FileFound.empty()) {
  796. this->Makefile->IssueMessage(
  797. MessageType::INTERNAL_ERROR,
  798. "fileFound is true but FileFound is empty!");
  799. fileFound = false;
  800. }
  801. }
  802. std::string foundVar = cmStrCat(this->Name, "_FOUND");
  803. std::string notFoundMessageVar = cmStrCat(this->Name, "_NOT_FOUND_MESSAGE");
  804. std::string notFoundMessage;
  805. // If the directory for the config file was found, try to read the file.
  806. bool result = true;
  807. bool found = false;
  808. bool configFileSetFOUNDFalse = false;
  809. if (fileFound) {
  810. if (this->Makefile->IsDefinitionSet(foundVar) &&
  811. !this->Makefile->IsOn(foundVar)) {
  812. // by removing Foo_FOUND here if it is FALSE, we don't really change
  813. // the situation for the Config file which is about to be included,
  814. // but we make it possible to detect later on whether the Config file
  815. // has set Foo_FOUND to FALSE itself:
  816. this->Makefile->RemoveDefinition(foundVar);
  817. }
  818. this->Makefile->RemoveDefinition(notFoundMessageVar);
  819. // Set the version variables before loading the config file.
  820. // It may override them.
  821. this->StoreVersionFound();
  822. // Parse the configuration file.
  823. if (this->ReadListFile(this->FileFound, DoPolicyScope)) {
  824. // The package has been found.
  825. found = true;
  826. // Check whether the Config file has set Foo_FOUND to FALSE:
  827. if (this->Makefile->IsDefinitionSet(foundVar) &&
  828. !this->Makefile->IsOn(foundVar)) {
  829. // we get here if the Config file has set Foo_FOUND actively to FALSE
  830. found = false;
  831. configFileSetFOUNDFalse = true;
  832. notFoundMessage =
  833. this->Makefile->GetSafeDefinition(notFoundMessageVar);
  834. }
  835. } else {
  836. // The configuration file is invalid.
  837. result = false;
  838. }
  839. }
  840. if (this->UseFindModules && !found &&
  841. handlePackageModeType == HandlePackageModeType::Config &&
  842. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  843. // Config mode failed. Allow Module case.
  844. result = false;
  845. }
  846. // package not found
  847. if (result && !found) {
  848. // warn if package required or neither quiet nor in config mode
  849. if (this->Required ||
  850. !(this->Quiet ||
  851. (this->UseConfigFiles && !this->UseFindModules &&
  852. this->ConsideredConfigs.empty()))) {
  853. // The variable is not set.
  854. std::ostringstream e;
  855. std::ostringstream aw;
  856. if (configFileSetFOUNDFalse) {
  857. /* clang-format off */
  858. e << "Found package configuration file:\n"
  859. " " << this->FileFound << "\n"
  860. "but it set " << foundVar << " to FALSE so package \"" <<
  861. this->Name << "\" is considered to be NOT FOUND.";
  862. /* clang-format on */
  863. if (!notFoundMessage.empty()) {
  864. e << " Reason given by package: \n" << notFoundMessage << "\n";
  865. }
  866. }
  867. // If there are files in ConsideredConfigs, it means that FooConfig.cmake
  868. // have been found, but they didn't have appropriate versions.
  869. else if (!this->ConsideredConfigs.empty()) {
  870. auto duplicate_end = cmRemoveDuplicates(this->ConsideredConfigs);
  871. e << "Could not find a configuration file for package \"" << this->Name
  872. << "\" that "
  873. << (this->VersionExact ? "exactly matches" : "is compatible with")
  874. << " requested version "
  875. << (this->VersionRange.empty() ? "" : "range ") << "\""
  876. << this->VersionComplete << "\".\n"
  877. << "The following configuration files were considered but not "
  878. "accepted:\n";
  879. for (ConfigFileInfo const& info :
  880. cmMakeRange(this->ConsideredConfigs.cbegin(), duplicate_end)) {
  881. e << " " << info.filename << ", version: " << info.version << "\n";
  882. }
  883. } else {
  884. std::string requestedVersionString;
  885. if (!this->VersionComplete.empty()) {
  886. requestedVersionString =
  887. cmStrCat(" (requested version ", this->VersionComplete, ')');
  888. }
  889. if (this->UseConfigFiles) {
  890. if (this->UseFindModules) {
  891. e << "By not providing \"Find" << this->Name
  892. << ".cmake\" in "
  893. "CMAKE_MODULE_PATH this project has asked CMake to find a "
  894. "package configuration file provided by \""
  895. << this->Name
  896. << "\", "
  897. "but CMake did not find one.\n";
  898. }
  899. if (this->Configs.size() == 1) {
  900. e << "Could not find a package configuration file named \""
  901. << this->Configs[0] << "\" provided by package \"" << this->Name
  902. << "\"" << requestedVersionString << ".\n";
  903. } else {
  904. e << "Could not find a package configuration file provided by \""
  905. << this->Name << "\"" << requestedVersionString
  906. << " with any of the following names:\n"
  907. << cmWrap(" ", this->Configs, "", "\n") << "\n";
  908. }
  909. e << "Add the installation prefix of \"" << this->Name
  910. << "\" to "
  911. "CMAKE_PREFIX_PATH or set \""
  912. << this->Variable
  913. << "\" to a "
  914. "directory containing one of the above files. "
  915. "If \""
  916. << this->Name
  917. << "\" provides a separate development "
  918. "package or SDK, be sure it has been installed.";
  919. } else // if(!this->UseFindModules && !this->UseConfigFiles)
  920. {
  921. e << "No \"Find" << this->Name << ".cmake\" found in "
  922. << "CMAKE_MODULE_PATH.";
  923. aw
  924. << "Find" << this->Name
  925. << ".cmake must either be part of this "
  926. "project itself, in this case adjust CMAKE_MODULE_PATH so that "
  927. "it points to the correct location inside its source tree.\n"
  928. "Or it must be installed by a package which has already been "
  929. "found via find_package(). In this case make sure that "
  930. "package has indeed been found and adjust CMAKE_MODULE_PATH to "
  931. "contain the location where that package has installed "
  932. "Find"
  933. << this->Name
  934. << ".cmake. This must be a location "
  935. "provided by that package. This error in general means that "
  936. "the buildsystem of this project is relying on a Find-module "
  937. "without ensuring that it is actually available.\n";
  938. }
  939. }
  940. this->Makefile->IssueMessage(this->Required ? MessageType::FATAL_ERROR
  941. : MessageType::WARNING,
  942. e.str());
  943. if (this->Required) {
  944. cmSystemTools::SetFatalErrorOccured();
  945. }
  946. if (!aw.str().empty()) {
  947. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  948. }
  949. }
  950. // output result if in config mode but not in quiet mode
  951. else if (!this->Quiet) {
  952. this->Makefile->DisplayStatus(cmStrCat("Could NOT find ", this->Name,
  953. " (missing: ", this->Name,
  954. "_DIR)"),
  955. -1);
  956. }
  957. }
  958. // Set a variable marking whether the package was found.
  959. this->Makefile->AddDefinition(foundVar, found ? "1" : "0");
  960. // Set a variable naming the configuration file that was found.
  961. std::string fileVar = cmStrCat(this->Name, "_CONFIG");
  962. if (found) {
  963. this->Makefile->AddDefinition(fileVar, this->FileFound);
  964. } else {
  965. this->Makefile->RemoveDefinition(fileVar);
  966. }
  967. std::string consideredConfigsVar =
  968. cmStrCat(this->Name, "_CONSIDERED_CONFIGS");
  969. std::string consideredVersionsVar =
  970. cmStrCat(this->Name, "_CONSIDERED_VERSIONS");
  971. std::string consideredConfigFiles;
  972. std::string consideredVersions;
  973. const char* sep = "";
  974. for (ConfigFileInfo const& i : this->ConsideredConfigs) {
  975. consideredConfigFiles += sep;
  976. consideredVersions += sep;
  977. consideredConfigFiles += i.filename;
  978. consideredVersions += i.version;
  979. sep = ";";
  980. }
  981. this->Makefile->AddDefinition(consideredConfigsVar, consideredConfigFiles);
  982. this->Makefile->AddDefinition(consideredVersionsVar, consideredVersions);
  983. return result;
  984. }
  985. bool cmFindPackageCommand::FindConfig()
  986. {
  987. // Compute the set of search prefixes.
  988. this->ComputePrefixes();
  989. // Look for the project's configuration file.
  990. bool found = false;
  991. if (this->DebugMode) {
  992. this->DebugBuffer = cmStrCat(this->DebugBuffer,
  993. "find_package considered the following "
  994. "locations for ",
  995. this->Name, "'s Config module:\n");
  996. }
  997. // Search for frameworks.
  998. if (!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly)) {
  999. found = this->FindFrameworkConfig();
  1000. }
  1001. // Search for apps.
  1002. if (!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly)) {
  1003. found = this->FindAppBundleConfig();
  1004. }
  1005. // Search prefixes.
  1006. if (!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly)) {
  1007. found = this->FindPrefixedConfig();
  1008. }
  1009. // Search for frameworks.
  1010. if (!found && this->SearchFrameworkLast) {
  1011. found = this->FindFrameworkConfig();
  1012. }
  1013. // Search for apps.
  1014. if (!found && this->SearchAppBundleLast) {
  1015. found = this->FindAppBundleConfig();
  1016. }
  1017. if (this->DebugMode) {
  1018. if (found) {
  1019. this->DebugBuffer = cmStrCat(
  1020. this->DebugBuffer, "The file was found at\n ", this->FileFound, "\n");
  1021. } else {
  1022. this->DebugBuffer =
  1023. cmStrCat(this->DebugBuffer, "The file was not found.\n");
  1024. }
  1025. }
  1026. // Store the entry in the cache so it can be set by the user.
  1027. std::string init;
  1028. if (found) {
  1029. init = cmSystemTools::GetFilenamePath(this->FileFound);
  1030. } else {
  1031. init = this->Variable + "-NOTFOUND";
  1032. }
  1033. std::string help =
  1034. cmStrCat("The directory containing a CMake configuration file for ",
  1035. this->Name, '.');
  1036. // We force the value since we do not get here if it was already set.
  1037. this->Makefile->AddCacheDefinition(this->Variable, init, help.c_str(),
  1038. cmStateEnums::PATH, true);
  1039. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0126) ==
  1040. cmPolicies::NEW &&
  1041. this->Makefile->IsNormalDefinitionSet(this->Variable)) {
  1042. this->Makefile->AddDefinition(this->Variable, init);
  1043. }
  1044. return found;
  1045. }
  1046. bool cmFindPackageCommand::FindPrefixedConfig()
  1047. {
  1048. std::vector<std::string> const& prefixes = this->SearchPaths;
  1049. return std::any_of(
  1050. prefixes.begin(), prefixes.end(),
  1051. [this](std::string const& p) -> bool { return this->SearchPrefix(p); });
  1052. }
  1053. bool cmFindPackageCommand::FindFrameworkConfig()
  1054. {
  1055. std::vector<std::string> const& prefixes = this->SearchPaths;
  1056. return std::any_of(prefixes.begin(), prefixes.end(),
  1057. [this](std::string const& p) -> bool {
  1058. return this->SearchFrameworkPrefix(p);
  1059. });
  1060. }
  1061. bool cmFindPackageCommand::FindAppBundleConfig()
  1062. {
  1063. std::vector<std::string> const& prefixes = this->SearchPaths;
  1064. return std::any_of(prefixes.begin(), prefixes.end(),
  1065. [this](std::string const& p) -> bool {
  1066. return this->SearchAppBundlePrefix(p);
  1067. });
  1068. }
  1069. bool cmFindPackageCommand::ReadListFile(const std::string& f,
  1070. PolicyScopeRule psr)
  1071. {
  1072. const bool noPolicyScope = !this->PolicyScope || psr == NoPolicyScope;
  1073. if (this->Makefile->ReadDependentFile(f, noPolicyScope)) {
  1074. return true;
  1075. }
  1076. std::string e = cmStrCat("Error reading CMake code from \"", f, "\".");
  1077. this->SetError(e);
  1078. return false;
  1079. }
  1080. void cmFindPackageCommand::AppendToFoundProperty(bool found)
  1081. {
  1082. std::vector<std::string> foundContents;
  1083. cmValue foundProp =
  1084. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_FOUND");
  1085. if (cmNonempty(foundProp)) {
  1086. cmExpandList(*foundProp, foundContents, false);
  1087. auto nameIt =
  1088. std::find(foundContents.begin(), foundContents.end(), this->Name);
  1089. if (nameIt != foundContents.end()) {
  1090. foundContents.erase(nameIt);
  1091. }
  1092. }
  1093. std::vector<std::string> notFoundContents;
  1094. cmValue notFoundProp =
  1095. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_NOT_FOUND");
  1096. if (cmNonempty(notFoundProp)) {
  1097. cmExpandList(*notFoundProp, notFoundContents, false);
  1098. auto nameIt =
  1099. std::find(notFoundContents.begin(), notFoundContents.end(), this->Name);
  1100. if (nameIt != notFoundContents.end()) {
  1101. notFoundContents.erase(nameIt);
  1102. }
  1103. }
  1104. if (found) {
  1105. foundContents.push_back(this->Name);
  1106. } else {
  1107. notFoundContents.push_back(this->Name);
  1108. }
  1109. std::string tmp = cmJoin(foundContents, ";");
  1110. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_FOUND", tmp.c_str());
  1111. tmp = cmJoin(notFoundContents, ";");
  1112. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_NOT_FOUND",
  1113. tmp.c_str());
  1114. }
  1115. void cmFindPackageCommand::AppendSuccessInformation()
  1116. {
  1117. {
  1118. std::string transitivePropName =
  1119. cmStrCat("_CMAKE_", this->Name, "_TRANSITIVE_DEPENDENCY");
  1120. this->Makefile->GetState()->SetGlobalProperty(transitivePropName, "False");
  1121. }
  1122. std::string found = cmStrCat(this->Name, "_FOUND");
  1123. std::string upperFound = cmSystemTools::UpperCase(found);
  1124. bool upperResult = this->Makefile->IsOn(upperFound);
  1125. bool result = this->Makefile->IsOn(found);
  1126. bool packageFound = (result || upperResult);
  1127. this->AppendToFoundProperty(packageFound);
  1128. // Record whether the find was quiet or not, so this can be used
  1129. // e.g. in FeatureSummary.cmake
  1130. std::string quietInfoPropName = cmStrCat("_CMAKE_", this->Name, "_QUIET");
  1131. this->Makefile->GetState()->SetGlobalProperty(
  1132. quietInfoPropName, this->Quiet ? "TRUE" : "FALSE");
  1133. // set a global property to record the required version of this package
  1134. std::string versionInfoPropName =
  1135. cmStrCat("_CMAKE_", this->Name, "_REQUIRED_VERSION");
  1136. std::string versionInfo;
  1137. if (!this->VersionRange.empty()) {
  1138. versionInfo = this->VersionRange;
  1139. } else if (!this->Version.empty()) {
  1140. versionInfo =
  1141. cmStrCat(this->VersionExact ? "==" : ">=", ' ', this->Version);
  1142. }
  1143. this->Makefile->GetState()->SetGlobalProperty(versionInfoPropName,
  1144. versionInfo.c_str());
  1145. if (this->Required) {
  1146. std::string requiredInfoPropName =
  1147. cmStrCat("_CMAKE_", this->Name, "_TYPE");
  1148. this->Makefile->GetState()->SetGlobalProperty(requiredInfoPropName,
  1149. "REQUIRED");
  1150. }
  1151. // Restore original state of "_FIND_" variables we set.
  1152. this->RestoreFindDefinitions();
  1153. // Pop the package stack
  1154. this->Makefile->FindPackageRootPathStack.pop_back();
  1155. }
  1156. inline std::size_t collectPathsForDebug(std::string& buffer,
  1157. cmSearchPath const& searchPath,
  1158. std::size_t startIndex = 0)
  1159. {
  1160. const auto& paths = searchPath.GetPaths();
  1161. if (paths.empty()) {
  1162. buffer += " none\n";
  1163. return 0;
  1164. }
  1165. for (std::size_t i = startIndex; i < paths.size(); i++) {
  1166. buffer += " " + paths[i].Path + "\n";
  1167. }
  1168. return paths.size();
  1169. }
  1170. void cmFindPackageCommand::ComputePrefixes()
  1171. {
  1172. if (!this->NoDefaultPath) {
  1173. if (!this->NoPackageRootPath) {
  1174. this->FillPrefixesPackageRoot();
  1175. }
  1176. if (!this->NoCMakePath) {
  1177. this->FillPrefixesCMakeVariable();
  1178. }
  1179. if (!this->NoCMakeEnvironmentPath) {
  1180. this->FillPrefixesCMakeEnvironment();
  1181. }
  1182. }
  1183. this->FillPrefixesUserHints();
  1184. if (!this->NoDefaultPath) {
  1185. if (!this->NoSystemEnvironmentPath) {
  1186. this->FillPrefixesSystemEnvironment();
  1187. }
  1188. if (!this->NoUserRegistry) {
  1189. this->FillPrefixesUserRegistry();
  1190. }
  1191. if (!this->NoCMakeSystemPath) {
  1192. this->FillPrefixesCMakeSystemVariable();
  1193. }
  1194. if (!this->NoSystemRegistry) {
  1195. this->FillPrefixesSystemRegistry();
  1196. }
  1197. }
  1198. this->FillPrefixesUserGuess();
  1199. this->ComputeFinalPaths(IgnorePaths::No);
  1200. }
  1201. void cmFindPackageCommand::FillPrefixesPackageRoot()
  1202. {
  1203. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot];
  1204. // Add the PACKAGE_ROOT_PATH from each enclosing find_package call.
  1205. for (auto pkgPaths = this->Makefile->FindPackageRootPathStack.rbegin();
  1206. pkgPaths != this->Makefile->FindPackageRootPathStack.rend();
  1207. ++pkgPaths) {
  1208. for (std::string const& path : *pkgPaths) {
  1209. paths.AddPath(path);
  1210. }
  1211. }
  1212. if (this->DebugMode) {
  1213. std::string debugBuffer = "<PackageName>_ROOT CMake variable "
  1214. "[CMAKE_FIND_USE_PACKAGE_ROOT_PATH].\n";
  1215. collectPathsForDebug(debugBuffer, paths);
  1216. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1217. }
  1218. }
  1219. void cmFindPackageCommand::FillPrefixesCMakeEnvironment()
  1220. {
  1221. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeEnvironment];
  1222. std::string debugBuffer;
  1223. std::size_t debugOffset = 0;
  1224. // Check the environment variable with the same name as the cache
  1225. // entry.
  1226. paths.AddEnvPath(this->Variable);
  1227. if (this->DebugMode) {
  1228. debugBuffer = cmStrCat("Env variable ", this->Variable,
  1229. " [CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
  1230. debugOffset = collectPathsForDebug(debugBuffer, paths);
  1231. }
  1232. // And now the general CMake environment variables
  1233. paths.AddEnvPath("CMAKE_PREFIX_PATH");
  1234. if (this->DebugMode) {
  1235. debugBuffer = cmStrCat(debugBuffer,
  1236. "CMAKE_PREFIX_PATH env variable "
  1237. "[CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
  1238. debugOffset = collectPathsForDebug(debugBuffer, paths, debugOffset);
  1239. }
  1240. paths.AddEnvPath("CMAKE_FRAMEWORK_PATH");
  1241. paths.AddEnvPath("CMAKE_APPBUNDLE_PATH");
  1242. if (this->DebugMode) {
  1243. debugBuffer =
  1244. cmStrCat(debugBuffer,
  1245. "CMAKE_FRAMEWORK_PATH and CMAKE_APPBUNDLE_PATH env "
  1246. "variables [CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
  1247. collectPathsForDebug(debugBuffer, paths, debugOffset);
  1248. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1249. }
  1250. }
  1251. void cmFindPackageCommand::FillPrefixesCMakeVariable()
  1252. {
  1253. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMake];
  1254. std::string debugBuffer;
  1255. std::size_t debugOffset = 0;
  1256. paths.AddCMakePath("CMAKE_PREFIX_PATH");
  1257. if (this->DebugMode) {
  1258. debugBuffer = "CMAKE_PREFIX_PATH variable [CMAKE_FIND_USE_CMAKE_PATH].\n";
  1259. debugOffset = collectPathsForDebug(debugBuffer, paths);
  1260. }
  1261. paths.AddCMakePath("CMAKE_FRAMEWORK_PATH");
  1262. paths.AddCMakePath("CMAKE_APPBUNDLE_PATH");
  1263. if (this->DebugMode) {
  1264. debugBuffer =
  1265. cmStrCat(debugBuffer,
  1266. "CMAKE_FRAMEWORK_PATH and CMAKE_APPBUNDLE_PATH variables "
  1267. "[CMAKE_FIND_USE_CMAKE_PATH].\n");
  1268. collectPathsForDebug(debugBuffer, paths, debugOffset);
  1269. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1270. }
  1271. }
  1272. void cmFindPackageCommand::FillPrefixesSystemEnvironment()
  1273. {
  1274. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemEnvironment];
  1275. // Use the system search path to generate prefixes.
  1276. // Relative paths are interpreted with respect to the current
  1277. // working directory.
  1278. std::vector<std::string> tmp;
  1279. cmSystemTools::GetPath(tmp);
  1280. for (std::string const& i : tmp) {
  1281. // If the path is a PREFIX/bin case then add its parent instead.
  1282. if ((cmHasLiteralSuffix(i, "/bin")) || (cmHasLiteralSuffix(i, "/sbin"))) {
  1283. paths.AddPath(cmSystemTools::GetFilenamePath(i));
  1284. } else {
  1285. paths.AddPath(i);
  1286. }
  1287. }
  1288. if (this->DebugMode) {
  1289. std::string debugBuffer = "Standard system environment variables "
  1290. "[CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH].\n";
  1291. collectPathsForDebug(debugBuffer, paths);
  1292. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1293. }
  1294. }
  1295. void cmFindPackageCommand::FillPrefixesUserRegistry()
  1296. {
  1297. #if defined(_WIN32) && !defined(__CYGWIN__)
  1298. this->LoadPackageRegistryWinUser();
  1299. #elif defined(__HAIKU__)
  1300. char dir[B_PATH_NAME_LENGTH];
  1301. if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  1302. B_OK) {
  1303. std::string fname = cmStrCat(dir, "/cmake/packages/", Name);
  1304. this->LoadPackageRegistryDir(fname,
  1305. this->LabeledPaths[PathLabel::UserRegistry]);
  1306. }
  1307. #else
  1308. std::string dir;
  1309. if (cmSystemTools::GetEnv("HOME", dir)) {
  1310. dir += "/.cmake/packages/";
  1311. dir += this->Name;
  1312. this->LoadPackageRegistryDir(dir,
  1313. this->LabeledPaths[PathLabel::UserRegistry]);
  1314. }
  1315. #endif
  1316. if (this->DebugMode) {
  1317. std::string debugBuffer =
  1318. "CMake User Package Registry [CMAKE_FIND_USE_PACKAGE_REGISTRY].\n";
  1319. collectPathsForDebug(debugBuffer,
  1320. this->LabeledPaths[PathLabel::UserRegistry]);
  1321. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1322. }
  1323. }
  1324. void cmFindPackageCommand::FillPrefixesSystemRegistry()
  1325. {
  1326. if (this->NoSystemRegistry || this->NoDefaultPath) {
  1327. return;
  1328. }
  1329. #if defined(_WIN32) && !defined(__CYGWIN__)
  1330. this->LoadPackageRegistryWinSystem();
  1331. #endif
  1332. if (this->DebugMode) {
  1333. std::string debugBuffer =
  1334. "CMake System Package Registry "
  1335. "[CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY].\n";
  1336. collectPathsForDebug(debugBuffer,
  1337. this->LabeledPaths[PathLabel::SystemRegistry]);
  1338. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1339. }
  1340. }
  1341. #if defined(_WIN32) && !defined(__CYGWIN__)
  1342. # include <windows.h>
  1343. // http://msdn.microsoft.com/en-us/library/aa384253%28v=vs.85%29.aspx
  1344. # if !defined(KEY_WOW64_32KEY)
  1345. # define KEY_WOW64_32KEY 0x0200
  1346. # endif
  1347. # if !defined(KEY_WOW64_64KEY)
  1348. # define KEY_WOW64_64KEY 0x0100
  1349. # endif
  1350. void cmFindPackageCommand::LoadPackageRegistryWinUser()
  1351. {
  1352. // HKEY_CURRENT_USER\\Software shares 32-bit and 64-bit views.
  1353. this->LoadPackageRegistryWin(true, 0,
  1354. this->LabeledPaths[PathLabel::UserRegistry]);
  1355. }
  1356. void cmFindPackageCommand::LoadPackageRegistryWinSystem()
  1357. {
  1358. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemRegistry];
  1359. // HKEY_LOCAL_MACHINE\\SOFTWARE has separate 32-bit and 64-bit views.
  1360. // Prefer the target platform view first.
  1361. if (this->Makefile->PlatformIs64Bit()) {
  1362. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1363. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1364. } else {
  1365. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1366. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1367. }
  1368. }
  1369. void cmFindPackageCommand::LoadPackageRegistryWin(bool user, unsigned int view,
  1370. cmSearchPath& outPaths)
  1371. {
  1372. std::wstring key = L"Software\\Kitware\\CMake\\Packages\\";
  1373. key += cmsys::Encoding::ToWide(this->Name);
  1374. std::set<std::wstring> bad;
  1375. HKEY hKey;
  1376. if (RegOpenKeyExW(user ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, key.c_str(),
  1377. 0, KEY_QUERY_VALUE | view, &hKey) == ERROR_SUCCESS) {
  1378. DWORD valueType = REG_NONE;
  1379. wchar_t name[16383]; // RegEnumValue docs limit name to 32767 _bytes_
  1380. std::vector<wchar_t> data(512);
  1381. bool done = false;
  1382. DWORD index = 0;
  1383. while (!done) {
  1384. DWORD nameSize = static_cast<DWORD>(sizeof(name));
  1385. DWORD dataSize = static_cast<DWORD>(data.size() * sizeof(data[0]));
  1386. switch (RegEnumValueW(hKey, index, name, &nameSize, 0, &valueType,
  1387. (BYTE*)&data[0], &dataSize)) {
  1388. case ERROR_SUCCESS:
  1389. ++index;
  1390. if (valueType == REG_SZ) {
  1391. data[dataSize] = 0;
  1392. if (!this->CheckPackageRegistryEntry(
  1393. cmsys::Encoding::ToNarrow(&data[0]), outPaths)) {
  1394. // The entry is invalid.
  1395. bad.insert(name);
  1396. }
  1397. }
  1398. break;
  1399. case ERROR_MORE_DATA:
  1400. data.resize((dataSize + sizeof(data[0]) - 1) / sizeof(data[0]));
  1401. break;
  1402. case ERROR_NO_MORE_ITEMS:
  1403. default:
  1404. done = true;
  1405. break;
  1406. }
  1407. }
  1408. RegCloseKey(hKey);
  1409. }
  1410. // Remove bad values if possible.
  1411. if (user && !bad.empty() &&
  1412. RegOpenKeyExW(HKEY_CURRENT_USER, key.c_str(), 0, KEY_SET_VALUE | view,
  1413. &hKey) == ERROR_SUCCESS) {
  1414. for (std::wstring const& v : bad) {
  1415. RegDeleteValueW(hKey, v.c_str());
  1416. }
  1417. RegCloseKey(hKey);
  1418. }
  1419. }
  1420. #else
  1421. class cmFindPackageCommandHoldFile
  1422. {
  1423. const char* File;
  1424. public:
  1425. cmFindPackageCommandHoldFile(const char* f)
  1426. : File(f)
  1427. {
  1428. }
  1429. ~cmFindPackageCommandHoldFile()
  1430. {
  1431. if (this->File) {
  1432. cmSystemTools::RemoveFile(this->File);
  1433. }
  1434. }
  1435. cmFindPackageCommandHoldFile(const cmFindPackageCommandHoldFile&) = delete;
  1436. cmFindPackageCommandHoldFile& operator=(
  1437. const cmFindPackageCommandHoldFile&) = delete;
  1438. void Release() { this->File = nullptr; }
  1439. };
  1440. void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir,
  1441. cmSearchPath& outPaths)
  1442. {
  1443. cmsys::Directory files;
  1444. if (!files.Load(dir)) {
  1445. return;
  1446. }
  1447. std::string fname;
  1448. for (unsigned long i = 0; i < files.GetNumberOfFiles(); ++i) {
  1449. fname = cmStrCat(dir, '/', files.GetFile(i));
  1450. if (!cmSystemTools::FileIsDirectory(fname)) {
  1451. // Hold this file hostage until it behaves.
  1452. cmFindPackageCommandHoldFile holdFile(fname.c_str());
  1453. // Load the file.
  1454. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  1455. std::string fentry;
  1456. if (fin && cmSystemTools::GetLineFromStream(fin, fentry) &&
  1457. this->CheckPackageRegistryEntry(fentry, outPaths)) {
  1458. // The file references an existing package, so release it.
  1459. holdFile.Release();
  1460. }
  1461. }
  1462. }
  1463. // TODO: Wipe out the directory if it is empty.
  1464. }
  1465. #endif
  1466. bool cmFindPackageCommand::CheckPackageRegistryEntry(const std::string& fname,
  1467. cmSearchPath& outPaths)
  1468. {
  1469. // Parse the content of one package registry entry.
  1470. if (cmSystemTools::FileIsFullPath(fname)) {
  1471. // The first line in the stream is the full path to a file or
  1472. // directory containing the package.
  1473. if (cmSystemTools::FileExists(fname)) {
  1474. // The path exists. Look for the package here.
  1475. if (!cmSystemTools::FileIsDirectory(fname)) {
  1476. outPaths.AddPath(cmSystemTools::GetFilenamePath(fname));
  1477. } else {
  1478. outPaths.AddPath(fname);
  1479. }
  1480. return true;
  1481. }
  1482. // The path does not exist. Assume the stream content is
  1483. // associated with an old package that no longer exists, and
  1484. // delete it to keep the package registry clean.
  1485. return false;
  1486. }
  1487. // The first line in the stream is not the full path to a file or
  1488. // directory. Assume the stream content was created by a future
  1489. // version of CMake that uses a different format, and leave it.
  1490. return true;
  1491. }
  1492. void cmFindPackageCommand::FillPrefixesCMakeSystemVariable()
  1493. {
  1494. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeSystem];
  1495. paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
  1496. paths.AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
  1497. paths.AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
  1498. if (this->DebugMode) {
  1499. std::string debugBuffer = "CMake variables defined in the Platform file "
  1500. "[CMAKE_FIND_USE_CMAKE_SYSTEM_PATH].\n";
  1501. collectPathsForDebug(debugBuffer, paths);
  1502. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1503. }
  1504. }
  1505. void cmFindPackageCommand::FillPrefixesUserGuess()
  1506. {
  1507. cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
  1508. for (std::string const& p : this->UserGuessArgs) {
  1509. paths.AddUserPath(p);
  1510. }
  1511. if (this->DebugMode) {
  1512. std::string debugBuffer =
  1513. "Paths specified by the find_package PATHS option.\n";
  1514. collectPathsForDebug(debugBuffer, paths);
  1515. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1516. }
  1517. }
  1518. void cmFindPackageCommand::FillPrefixesUserHints()
  1519. {
  1520. cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
  1521. for (std::string const& p : this->UserHintsArgs) {
  1522. paths.AddUserPath(p);
  1523. }
  1524. if (this->DebugMode) {
  1525. std::string debugBuffer =
  1526. "Paths specified by the find_package HINTS option.\n";
  1527. collectPathsForDebug(debugBuffer, paths);
  1528. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1529. }
  1530. }
  1531. bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
  1532. {
  1533. assert(!dir.empty() && dir.back() == '/');
  1534. // Check each path suffix on this directory.
  1535. for (std::string const& s : this->SearchPathSuffixes) {
  1536. std::string d = dir;
  1537. if (!s.empty()) {
  1538. d += s;
  1539. d += "/";
  1540. }
  1541. if (this->CheckDirectory(d)) {
  1542. return true;
  1543. }
  1544. }
  1545. return false;
  1546. }
  1547. bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
  1548. {
  1549. assert(!dir.empty() && dir.back() == '/');
  1550. // Look for the file in this directory.
  1551. std::string d = dir.substr(0, dir.size() - 1);
  1552. if (this->FindConfigFile(d, this->FileFound)) {
  1553. // Remove duplicate slashes.
  1554. cmSystemTools::ConvertToUnixSlashes(this->FileFound);
  1555. return true;
  1556. }
  1557. return false;
  1558. }
  1559. bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
  1560. std::string& file)
  1561. {
  1562. if (this->IgnoredPaths.count(dir)) {
  1563. return false;
  1564. }
  1565. for (std::string const& c : this->Configs) {
  1566. file = cmStrCat(dir, '/', c);
  1567. if (this->DebugMode) {
  1568. this->DebugBuffer = cmStrCat(this->DebugBuffer, " ", file, "\n");
  1569. }
  1570. if (cmSystemTools::FileExists(file, true) && this->CheckVersion(file)) {
  1571. // Allow resolving symlinks when the config file is found through a link
  1572. if (this->UseRealPath) {
  1573. file = cmSystemTools::GetRealPath(file);
  1574. }
  1575. return true;
  1576. }
  1577. }
  1578. return false;
  1579. }
  1580. bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
  1581. {
  1582. bool result = false; // by default, assume the version is not ok.
  1583. bool haveResult = false;
  1584. std::string version = "unknown";
  1585. // Get the filename without the .cmake extension.
  1586. std::string::size_type pos = config_file.rfind('.');
  1587. std::string version_file_base = config_file.substr(0, pos);
  1588. // Look for foo-config-version.cmake
  1589. std::string version_file = cmStrCat(version_file_base, "-version.cmake");
  1590. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1591. result = this->CheckVersionFile(version_file, version);
  1592. haveResult = true;
  1593. }
  1594. // Look for fooConfigVersion.cmake
  1595. version_file = cmStrCat(version_file_base, "Version.cmake");
  1596. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1597. result = this->CheckVersionFile(version_file, version);
  1598. haveResult = true;
  1599. }
  1600. // If no version was requested a versionless package is acceptable.
  1601. if (!haveResult && this->Version.empty()) {
  1602. result = true;
  1603. }
  1604. ConfigFileInfo configFileInfo;
  1605. configFileInfo.filename = config_file;
  1606. configFileInfo.version = version;
  1607. this->ConsideredConfigs.push_back(std::move(configFileInfo));
  1608. return result;
  1609. }
  1610. bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file,
  1611. std::string& result_version)
  1612. {
  1613. // The version file will be loaded in an isolated scope.
  1614. cmMakefile::ScopePushPop varScope(this->Makefile);
  1615. cmMakefile::PolicyPushPop polScope(this->Makefile);
  1616. static_cast<void>(varScope);
  1617. static_cast<void>(polScope);
  1618. // Clear the output variables.
  1619. this->Makefile->RemoveDefinition("PACKAGE_VERSION");
  1620. this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
  1621. this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
  1622. this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
  1623. // Set the input variables.
  1624. this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name);
  1625. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COMPLETE",
  1626. this->VersionComplete);
  1627. auto addDefinition = [this](const std::string& variable,
  1628. cm::string_view value) {
  1629. this->Makefile->AddDefinition(variable, value);
  1630. };
  1631. this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION",
  1632. this->Version, this->VersionCount,
  1633. this->VersionMajor, this->VersionMinor,
  1634. this->VersionPatch, this->VersionTweak);
  1635. if (!this->VersionRange.empty()) {
  1636. this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION_MIN",
  1637. this->Version, this->VersionCount,
  1638. this->VersionMajor, this->VersionMinor,
  1639. this->VersionPatch, this->VersionTweak);
  1640. this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION_MAX",
  1641. this->VersionMax, this->VersionMaxCount,
  1642. this->VersionMaxMajor, this->VersionMaxMinor,
  1643. this->VersionMaxPatch, this->VersionMaxTweak);
  1644. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE",
  1645. this->VersionComplete);
  1646. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE_MIN",
  1647. this->VersionRangeMin);
  1648. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE_MAX",
  1649. this->VersionRangeMax);
  1650. }
  1651. // Load the version check file. Pass NoPolicyScope because we do
  1652. // our own policy push/pop independent of CMP0011.
  1653. bool suitable = false;
  1654. if (this->ReadListFile(version_file, NoPolicyScope)) {
  1655. // Check the output variables.
  1656. bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
  1657. bool unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
  1658. if (!okay && !this->VersionExact) {
  1659. okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
  1660. }
  1661. // The package is suitable if the version is okay and not
  1662. // explicitly unsuitable.
  1663. suitable = !unsuitable && (okay || this->Version.empty());
  1664. if (suitable) {
  1665. // Get the version found.
  1666. this->VersionFound =
  1667. this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1668. // Try to parse the version number and store the results that were
  1669. // successfully parsed.
  1670. unsigned int parsed_major;
  1671. unsigned int parsed_minor;
  1672. unsigned int parsed_patch;
  1673. unsigned int parsed_tweak;
  1674. this->VersionFoundCount =
  1675. sscanf(this->VersionFound.c_str(), "%u.%u.%u.%u", &parsed_major,
  1676. &parsed_minor, &parsed_patch, &parsed_tweak);
  1677. switch (this->VersionFoundCount) {
  1678. case 4:
  1679. this->VersionFoundTweak = parsed_tweak;
  1680. CM_FALLTHROUGH;
  1681. case 3:
  1682. this->VersionFoundPatch = parsed_patch;
  1683. CM_FALLTHROUGH;
  1684. case 2:
  1685. this->VersionFoundMinor = parsed_minor;
  1686. CM_FALLTHROUGH;
  1687. case 1:
  1688. this->VersionFoundMajor = parsed_major;
  1689. CM_FALLTHROUGH;
  1690. default:
  1691. break;
  1692. }
  1693. }
  1694. }
  1695. result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1696. if (result_version.empty()) {
  1697. result_version = "unknown";
  1698. }
  1699. // Succeed if the version is suitable.
  1700. return suitable;
  1701. }
  1702. void cmFindPackageCommand::StoreVersionFound()
  1703. {
  1704. // Store the whole version string.
  1705. std::string ver = cmStrCat(this->Name, "_VERSION");
  1706. auto addDefinition = [this](const std::string& variable,
  1707. cm::string_view value) {
  1708. this->Makefile->AddDefinition(variable, value);
  1709. };
  1710. this->SetVersionVariables(addDefinition, ver, this->VersionFound,
  1711. this->VersionFoundCount, this->VersionFoundMajor,
  1712. this->VersionFoundMinor, this->VersionFoundPatch,
  1713. this->VersionFoundTweak);
  1714. if (this->VersionFound.empty()) {
  1715. this->Makefile->RemoveDefinition(ver);
  1716. }
  1717. }
  1718. class cmFileListGeneratorBase
  1719. {
  1720. public:
  1721. virtual ~cmFileListGeneratorBase() = default;
  1722. protected:
  1723. bool Consider(std::string const& fullPath, cmFileList& listing);
  1724. private:
  1725. bool Search(cmFileList&);
  1726. virtual bool Search(std::string const& parent, cmFileList&) = 0;
  1727. virtual std::unique_ptr<cmFileListGeneratorBase> Clone() const = 0;
  1728. friend class cmFileList;
  1729. cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next);
  1730. std::unique_ptr<cmFileListGeneratorBase> Next;
  1731. };
  1732. class cmFileList
  1733. {
  1734. public:
  1735. virtual ~cmFileList() = default;
  1736. cmFileList& operator/(cmFileListGeneratorBase const& rhs)
  1737. {
  1738. if (this->Last) {
  1739. this->Last = this->Last->SetNext(rhs);
  1740. } else {
  1741. this->First = rhs.Clone();
  1742. this->Last = this->First.get();
  1743. }
  1744. return *this;
  1745. }
  1746. bool Search()
  1747. {
  1748. if (this->First) {
  1749. return this->First->Search(*this);
  1750. }
  1751. return false;
  1752. }
  1753. private:
  1754. virtual bool Visit(std::string const& fullPath) = 0;
  1755. friend class cmFileListGeneratorBase;
  1756. std::unique_ptr<cmFileListGeneratorBase> First;
  1757. cmFileListGeneratorBase* Last = nullptr;
  1758. };
  1759. class cmFindPackageFileList : public cmFileList
  1760. {
  1761. public:
  1762. cmFindPackageFileList(cmFindPackageCommand* fpc, bool use_suffixes = true)
  1763. : FPC(fpc)
  1764. , UseSuffixes(use_suffixes)
  1765. {
  1766. }
  1767. private:
  1768. bool Visit(std::string const& fullPath) override
  1769. {
  1770. if (this->UseSuffixes) {
  1771. return this->FPC->SearchDirectory(fullPath);
  1772. }
  1773. return this->FPC->CheckDirectory(fullPath);
  1774. }
  1775. cmFindPackageCommand* FPC;
  1776. bool UseSuffixes;
  1777. };
  1778. bool cmFileListGeneratorBase::Search(cmFileList& listing)
  1779. {
  1780. return this->Search("", listing);
  1781. }
  1782. cmFileListGeneratorBase* cmFileListGeneratorBase::SetNext(
  1783. cmFileListGeneratorBase const& next)
  1784. {
  1785. this->Next = next.Clone();
  1786. return this->Next.get();
  1787. }
  1788. bool cmFileListGeneratorBase::Consider(std::string const& fullPath,
  1789. cmFileList& listing)
  1790. {
  1791. if (!fullPath.empty() && !cmSystemTools::FileIsDirectory(fullPath)) {
  1792. return false;
  1793. }
  1794. if (this->Next) {
  1795. return this->Next->Search(fullPath + "/", listing);
  1796. }
  1797. return listing.Visit(fullPath + "/");
  1798. }
  1799. class cmFileListGeneratorFixed : public cmFileListGeneratorBase
  1800. {
  1801. public:
  1802. cmFileListGeneratorFixed(std::string str)
  1803. : String(std::move(str))
  1804. {
  1805. }
  1806. cmFileListGeneratorFixed(cmFileListGeneratorFixed const& r)
  1807. : String(r.String)
  1808. {
  1809. }
  1810. private:
  1811. std::string String;
  1812. bool Search(std::string const& parent, cmFileList& lister) override
  1813. {
  1814. std::string fullPath = parent + this->String;
  1815. return this->Consider(fullPath, lister);
  1816. }
  1817. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1818. {
  1819. std::unique_ptr<cmFileListGeneratorBase> g(
  1820. new cmFileListGeneratorFixed(*this));
  1821. return g;
  1822. }
  1823. };
  1824. class cmFileListGeneratorEnumerate : public cmFileListGeneratorBase
  1825. {
  1826. public:
  1827. cmFileListGeneratorEnumerate(std::vector<std::string> const& v)
  1828. : Vector(v)
  1829. {
  1830. }
  1831. cmFileListGeneratorEnumerate(cmFileListGeneratorEnumerate const& r)
  1832. : Vector(r.Vector)
  1833. {
  1834. }
  1835. private:
  1836. std::vector<std::string> const& Vector;
  1837. bool Search(std::string const& parent, cmFileList& lister) override
  1838. {
  1839. for (std::string const& i : this->Vector) {
  1840. if (this->Consider(parent + i, lister)) {
  1841. return true;
  1842. }
  1843. }
  1844. return false;
  1845. }
  1846. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1847. {
  1848. std::unique_ptr<cmFileListGeneratorBase> g(
  1849. new cmFileListGeneratorEnumerate(*this));
  1850. return g;
  1851. }
  1852. };
  1853. class cmFileListGeneratorProject : public cmFileListGeneratorBase
  1854. {
  1855. public:
  1856. cmFileListGeneratorProject(std::vector<std::string> const& names,
  1857. cmFindPackageCommand::SortOrderType so,
  1858. cmFindPackageCommand::SortDirectionType sd)
  1859. : Names(names)
  1860. {
  1861. this->SetSort(so, sd);
  1862. }
  1863. cmFileListGeneratorProject(cmFileListGeneratorProject const& r)
  1864. : Names(r.Names)
  1865. {
  1866. this->SetSort(r.SortOrder, r.SortDirection);
  1867. }
  1868. void SetSort(cmFindPackageCommand::SortOrderType o,
  1869. cmFindPackageCommand::SortDirectionType d)
  1870. {
  1871. this->SortOrder = o;
  1872. this->SortDirection = d;
  1873. }
  1874. protected:
  1875. // sort parameters
  1876. cmFindPackageCommand::SortOrderType SortOrder;
  1877. cmFindPackageCommand::SortDirectionType SortDirection;
  1878. private:
  1879. std::vector<std::string> const& Names;
  1880. bool Search(std::string const& parent, cmFileList& lister) override
  1881. {
  1882. // Construct a list of matches.
  1883. std::vector<std::string> matches;
  1884. cmsys::Directory d;
  1885. d.Load(parent);
  1886. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1887. const char* fname = d.GetFile(i);
  1888. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1889. continue;
  1890. }
  1891. for (std::string const& n : this->Names) {
  1892. if (cmsysString_strncasecmp(fname, n.c_str(), n.length()) == 0) {
  1893. matches.emplace_back(fname);
  1894. }
  1895. }
  1896. }
  1897. // before testing the matches check if there is a specific sorting order to
  1898. // perform
  1899. if (this->SortOrder != cmFindPackageCommand::None) {
  1900. cmFindPackageCommand::Sort(matches.begin(), matches.end(),
  1901. this->SortOrder, this->SortDirection);
  1902. }
  1903. for (std::string const& i : matches) {
  1904. if (this->Consider(parent + i, lister)) {
  1905. return true;
  1906. }
  1907. }
  1908. return false;
  1909. }
  1910. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1911. {
  1912. std::unique_ptr<cmFileListGeneratorBase> g(
  1913. new cmFileListGeneratorProject(*this));
  1914. return g;
  1915. }
  1916. };
  1917. class cmFileListGeneratorMacProject : public cmFileListGeneratorBase
  1918. {
  1919. public:
  1920. cmFileListGeneratorMacProject(std::vector<std::string> const& names,
  1921. const char* ext)
  1922. : Names(names)
  1923. , Extension(ext)
  1924. {
  1925. }
  1926. cmFileListGeneratorMacProject(cmFileListGeneratorMacProject const& r)
  1927. : Names(r.Names)
  1928. , Extension(r.Extension)
  1929. {
  1930. }
  1931. private:
  1932. std::vector<std::string> const& Names;
  1933. std::string Extension;
  1934. bool Search(std::string const& parent, cmFileList& lister) override
  1935. {
  1936. // Construct a list of matches.
  1937. std::vector<std::string> matches;
  1938. cmsys::Directory d;
  1939. d.Load(parent);
  1940. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1941. const char* fname = d.GetFile(i);
  1942. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1943. continue;
  1944. }
  1945. for (std::string name : this->Names) {
  1946. name += this->Extension;
  1947. if (cmsysString_strcasecmp(fname, name.c_str()) == 0) {
  1948. matches.emplace_back(fname);
  1949. }
  1950. }
  1951. }
  1952. for (std::string const& i : matches) {
  1953. if (this->Consider(parent + i, lister)) {
  1954. return true;
  1955. }
  1956. }
  1957. return false;
  1958. }
  1959. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1960. {
  1961. std::unique_ptr<cmFileListGeneratorBase> g(
  1962. new cmFileListGeneratorMacProject(*this));
  1963. return g;
  1964. }
  1965. };
  1966. class cmFileListGeneratorCaseInsensitive : public cmFileListGeneratorBase
  1967. {
  1968. public:
  1969. cmFileListGeneratorCaseInsensitive(std::string str)
  1970. : String(std::move(str))
  1971. {
  1972. }
  1973. cmFileListGeneratorCaseInsensitive(
  1974. cmFileListGeneratorCaseInsensitive const& r)
  1975. : String(r.String)
  1976. {
  1977. }
  1978. private:
  1979. std::string String;
  1980. bool Search(std::string const& parent, cmFileList& lister) override
  1981. {
  1982. // Look for matching files.
  1983. std::vector<std::string> matches;
  1984. cmsys::Directory d;
  1985. d.Load(parent);
  1986. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1987. const char* fname = d.GetFile(i);
  1988. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1989. continue;
  1990. }
  1991. if (cmsysString_strcasecmp(fname, this->String.c_str()) == 0) {
  1992. if (this->Consider(parent + fname, lister)) {
  1993. return true;
  1994. }
  1995. }
  1996. }
  1997. return false;
  1998. }
  1999. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  2000. {
  2001. std::unique_ptr<cmFileListGeneratorBase> g(
  2002. new cmFileListGeneratorCaseInsensitive(*this));
  2003. return g;
  2004. }
  2005. };
  2006. class cmFileListGeneratorGlob : public cmFileListGeneratorBase
  2007. {
  2008. public:
  2009. cmFileListGeneratorGlob(std::string str)
  2010. : Pattern(std::move(str))
  2011. {
  2012. }
  2013. cmFileListGeneratorGlob(cmFileListGeneratorGlob const& r)
  2014. : Pattern(r.Pattern)
  2015. {
  2016. }
  2017. private:
  2018. std::string Pattern;
  2019. bool Search(std::string const& parent, cmFileList& lister) override
  2020. {
  2021. // Glob the set of matching files.
  2022. std::string expr = cmStrCat(parent, this->Pattern);
  2023. cmsys::Glob g;
  2024. if (!g.FindFiles(expr)) {
  2025. return false;
  2026. }
  2027. std::vector<std::string> const& files = g.GetFiles();
  2028. // Look for directories among the matches.
  2029. for (std::string const& f : files) {
  2030. if (this->Consider(f, lister)) {
  2031. return true;
  2032. }
  2033. }
  2034. return false;
  2035. }
  2036. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  2037. {
  2038. return cm::make_unique<cmFileListGeneratorGlob>(*this);
  2039. }
  2040. };
  2041. bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
  2042. {
  2043. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2044. // Skip this if the prefix does not exist.
  2045. if (!cmSystemTools::FileIsDirectory(prefix_in)) {
  2046. return false;
  2047. }
  2048. // Skip this if it's in ignored paths.
  2049. std::string prefixWithoutSlash = prefix_in;
  2050. if (prefixWithoutSlash != "/" && prefixWithoutSlash.back() == '/') {
  2051. prefixWithoutSlash.erase(prefixWithoutSlash.length() - 1);
  2052. }
  2053. if (this->IgnoredPaths.count(prefixWithoutSlash) ||
  2054. this->IgnoredPrefixPaths.count(prefixWithoutSlash)) {
  2055. return false;
  2056. }
  2057. // PREFIX/ (useful on windows or in build trees)
  2058. if (this->SearchDirectory(prefix_in)) {
  2059. return true;
  2060. }
  2061. // Strip the trailing slash because the path generator is about to
  2062. // add one.
  2063. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2064. // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
  2065. {
  2066. cmFindPackageFileList lister(this);
  2067. lister / cmFileListGeneratorFixed(prefix) /
  2068. cmFileListGeneratorCaseInsensitive("cmake");
  2069. if (lister.Search()) {
  2070. return true;
  2071. }
  2072. }
  2073. // PREFIX/(Foo|foo|FOO).*/
  2074. {
  2075. cmFindPackageFileList lister(this);
  2076. lister / cmFileListGeneratorFixed(prefix) /
  2077. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2078. this->SortDirection);
  2079. if (lister.Search()) {
  2080. return true;
  2081. }
  2082. }
  2083. // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
  2084. {
  2085. cmFindPackageFileList lister(this);
  2086. lister / cmFileListGeneratorFixed(prefix) /
  2087. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2088. this->SortDirection) /
  2089. cmFileListGeneratorCaseInsensitive("cmake");
  2090. if (lister.Search()) {
  2091. return true;
  2092. }
  2093. }
  2094. // Construct list of common install locations (lib and share).
  2095. std::vector<std::string> common;
  2096. if (!this->LibraryArchitecture.empty()) {
  2097. common.push_back("lib/" + this->LibraryArchitecture);
  2098. }
  2099. if (this->UseLib32Paths) {
  2100. common.emplace_back("lib32");
  2101. }
  2102. if (this->UseLib64Paths) {
  2103. common.emplace_back("lib64");
  2104. }
  2105. if (this->UseLibx32Paths) {
  2106. common.emplace_back("libx32");
  2107. }
  2108. common.emplace_back("lib");
  2109. common.emplace_back("share");
  2110. // PREFIX/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  2111. {
  2112. cmFindPackageFileList lister(this);
  2113. lister / cmFileListGeneratorFixed(prefix) /
  2114. cmFileListGeneratorEnumerate(common) /
  2115. cmFileListGeneratorFixed("cmake") /
  2116. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2117. this->SortDirection);
  2118. if (lister.Search()) {
  2119. return true;
  2120. }
  2121. }
  2122. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  2123. {
  2124. cmFindPackageFileList lister(this);
  2125. lister / cmFileListGeneratorFixed(prefix) /
  2126. cmFileListGeneratorEnumerate(common) /
  2127. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2128. this->SortDirection);
  2129. if (lister.Search()) {
  2130. return true;
  2131. }
  2132. }
  2133. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  2134. {
  2135. cmFindPackageFileList lister(this);
  2136. lister / cmFileListGeneratorFixed(prefix) /
  2137. cmFileListGeneratorEnumerate(common) /
  2138. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2139. this->SortDirection) /
  2140. cmFileListGeneratorCaseInsensitive("cmake");
  2141. if (lister.Search()) {
  2142. return true;
  2143. }
  2144. }
  2145. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  2146. {
  2147. cmFindPackageFileList lister(this);
  2148. lister / cmFileListGeneratorFixed(prefix) /
  2149. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2150. this->SortDirection) /
  2151. cmFileListGeneratorEnumerate(common) /
  2152. cmFileListGeneratorFixed("cmake") /
  2153. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2154. this->SortDirection);
  2155. if (lister.Search()) {
  2156. return true;
  2157. }
  2158. }
  2159. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  2160. {
  2161. cmFindPackageFileList lister(this);
  2162. lister / cmFileListGeneratorFixed(prefix) /
  2163. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2164. this->SortDirection) /
  2165. cmFileListGeneratorEnumerate(common) /
  2166. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2167. this->SortDirection);
  2168. if (lister.Search()) {
  2169. return true;
  2170. }
  2171. }
  2172. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  2173. {
  2174. cmFindPackageFileList lister(this);
  2175. lister / cmFileListGeneratorFixed(prefix) /
  2176. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2177. this->SortDirection) /
  2178. cmFileListGeneratorEnumerate(common) /
  2179. cmFileListGeneratorProject(this->Names, this->SortOrder,
  2180. this->SortDirection) /
  2181. cmFileListGeneratorCaseInsensitive("cmake");
  2182. if (lister.Search()) {
  2183. return true;
  2184. }
  2185. }
  2186. return false;
  2187. }
  2188. bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
  2189. {
  2190. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2191. // Strip the trailing slash because the path generator is about to
  2192. // add one.
  2193. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2194. // <prefix>/Foo.framework/Resources/
  2195. {
  2196. cmFindPackageFileList lister(this);
  2197. lister / cmFileListGeneratorFixed(prefix) /
  2198. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2199. cmFileListGeneratorFixed("Resources");
  2200. if (lister.Search()) {
  2201. return true;
  2202. }
  2203. }
  2204. // <prefix>/Foo.framework/Resources/CMake/
  2205. {
  2206. cmFindPackageFileList lister(this);
  2207. lister / cmFileListGeneratorFixed(prefix) /
  2208. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2209. cmFileListGeneratorFixed("Resources") /
  2210. cmFileListGeneratorCaseInsensitive("cmake");
  2211. if (lister.Search()) {
  2212. return true;
  2213. }
  2214. }
  2215. // <prefix>/Foo.framework/Versions/*/Resources/
  2216. {
  2217. cmFindPackageFileList lister(this);
  2218. lister / cmFileListGeneratorFixed(prefix) /
  2219. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2220. cmFileListGeneratorFixed("Versions") /
  2221. cmFileListGeneratorGlob("*/Resources");
  2222. if (lister.Search()) {
  2223. return true;
  2224. }
  2225. }
  2226. // <prefix>/Foo.framework/Versions/*/Resources/CMake/
  2227. {
  2228. cmFindPackageFileList lister(this);
  2229. lister / cmFileListGeneratorFixed(prefix) /
  2230. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2231. cmFileListGeneratorFixed("Versions") /
  2232. cmFileListGeneratorGlob("*/Resources") /
  2233. cmFileListGeneratorCaseInsensitive("cmake");
  2234. if (lister.Search()) {
  2235. return true;
  2236. }
  2237. }
  2238. return false;
  2239. }
  2240. bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
  2241. {
  2242. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2243. // Strip the trailing slash because the path generator is about to
  2244. // add one.
  2245. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2246. // <prefix>/Foo.app/Contents/Resources
  2247. {
  2248. cmFindPackageFileList lister(this);
  2249. lister / cmFileListGeneratorFixed(prefix) /
  2250. cmFileListGeneratorMacProject(this->Names, ".app") /
  2251. cmFileListGeneratorFixed("Contents/Resources");
  2252. if (lister.Search()) {
  2253. return true;
  2254. }
  2255. }
  2256. // <prefix>/Foo.app/Contents/Resources/CMake
  2257. {
  2258. cmFindPackageFileList lister(this);
  2259. lister / cmFileListGeneratorFixed(prefix) /
  2260. cmFileListGeneratorMacProject(this->Names, ".app") /
  2261. cmFileListGeneratorFixed("Contents/Resources") /
  2262. cmFileListGeneratorCaseInsensitive("cmake");
  2263. if (lister.Search()) {
  2264. return true;
  2265. }
  2266. }
  2267. return false;
  2268. }
  2269. // TODO: Debug cmsys::Glob double slash problem.
  2270. bool cmFindPackage(std::vector<std::string> const& args,
  2271. cmExecutionStatus& status)
  2272. {
  2273. return cmFindPackageCommand(status).InitialPass(args);
  2274. }