cmFindPackageCommand.cxx 81 KB

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