cmFindPackageCommand.cxx 80 KB

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