cmFindPackageCommand.cxx 80 KB

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