cmFindPackageCommand.cxx 82 KB

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