cmFindPackageCommand.cxx 79 KB

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