cmFindPackageCommand.cxx 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310
  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 <deque>
  8. #include <functional>
  9. #include <iterator>
  10. #include <sstream>
  11. #include <utility>
  12. #include <cm/optional>
  13. #include <cmext/algorithm>
  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 "cmDependencyProvider.h"
  22. #include "cmExecutionStatus.h"
  23. #include "cmExperimental.h"
  24. #include "cmList.h"
  25. #include "cmListFileCache.h"
  26. #include "cmMakefile.h"
  27. #include "cmMessageType.h"
  28. #include "cmPolicies.h"
  29. #include "cmRange.h"
  30. #include "cmSearchPath.h"
  31. #include "cmState.h"
  32. #include "cmStateTypes.h"
  33. #include "cmStringAlgorithms.h"
  34. #include "cmSystemTools.h"
  35. #include "cmValue.h"
  36. #include "cmVersion.h"
  37. #include "cmWindowsRegistry.h"
  38. #if defined(__HAIKU__)
  39. # include <FindDirectory.h>
  40. # include <StorageDefs.h>
  41. #endif
  42. #if defined(_WIN32) && !defined(__CYGWIN__)
  43. # include <windows.h>
  44. // http://msdn.microsoft.com/en-us/library/aa384253%28v=vs.85%29.aspx
  45. # if !defined(KEY_WOW64_32KEY)
  46. # define KEY_WOW64_32KEY 0x0200
  47. # endif
  48. # if !defined(KEY_WOW64_64KEY)
  49. # define KEY_WOW64_64KEY 0x0100
  50. # endif
  51. #endif
  52. namespace {
  53. using pdt = cmFindPackageCommand::PackageDescriptionType;
  54. using ParsedVersion = cmPackageInfoReader::Pep440Version;
  55. template <template <typename> class Op>
  56. struct StrverscmpOp
  57. {
  58. bool operator()(std::string const& lhs, std::string const& rhs) const
  59. {
  60. return Op<int>()(cmSystemTools::strverscmp(lhs, rhs), 0);
  61. }
  62. };
  63. std::size_t collectPathsForDebug(std::string& buffer,
  64. cmSearchPath const& searchPath,
  65. std::size_t const startIndex = 0)
  66. {
  67. auto const& paths = searchPath.GetPaths();
  68. if (paths.empty()) {
  69. buffer += " none\n";
  70. return 0;
  71. }
  72. for (auto i = startIndex; i < paths.size(); i++) {
  73. buffer += " " + paths[i].Path + "\n";
  74. }
  75. return paths.size();
  76. }
  77. #if !(defined(_WIN32) && !defined(__CYGWIN__))
  78. class cmFindPackageCommandHoldFile
  79. {
  80. char const* File;
  81. public:
  82. cmFindPackageCommandHoldFile(char const* const f)
  83. : File(f)
  84. {
  85. }
  86. ~cmFindPackageCommandHoldFile()
  87. {
  88. if (this->File) {
  89. cmSystemTools::RemoveFile(this->File);
  90. }
  91. }
  92. cmFindPackageCommandHoldFile(cmFindPackageCommandHoldFile const&) = delete;
  93. cmFindPackageCommandHoldFile& operator=(
  94. cmFindPackageCommandHoldFile const&) = delete;
  95. void Release() { this->File = nullptr; }
  96. };
  97. #endif
  98. bool isDirentryToIgnore(char const* const fname)
  99. {
  100. assert(fname);
  101. assert(fname[0] != 0);
  102. return fname[0] == '.' &&
  103. (fname[1] == 0 || (fname[1] == '.' && fname[2] == 0));
  104. }
  105. class cmAppendPathSegmentGenerator
  106. {
  107. public:
  108. cmAppendPathSegmentGenerator(cm::string_view dirName)
  109. : DirName{ dirName }
  110. {
  111. }
  112. std::string GetNextCandidate(std::string const& parent)
  113. {
  114. if (this->NeedReset) {
  115. return {};
  116. }
  117. this->NeedReset = true;
  118. return cmStrCat(parent, this->DirName, '/');
  119. }
  120. void Reset() { this->NeedReset = false; }
  121. private:
  122. cm::string_view const DirName;
  123. bool NeedReset = false;
  124. };
  125. class cmEnumPathSegmentsGenerator
  126. {
  127. public:
  128. cmEnumPathSegmentsGenerator(std::vector<cm::string_view> const& init)
  129. : Names{ init }
  130. , Current{ this->Names.get().cbegin() }
  131. {
  132. }
  133. std::string GetNextCandidate(std::string const& parent)
  134. {
  135. if (this->Current != this->Names.get().cend()) {
  136. return cmStrCat(parent, *this->Current++, '/');
  137. }
  138. return {};
  139. }
  140. void Reset() { this->Current = this->Names.get().cbegin(); }
  141. private:
  142. std::reference_wrapper<std::vector<cm::string_view> const> Names;
  143. std::vector<cm::string_view>::const_iterator Current;
  144. };
  145. class cmCaseInsensitiveDirectoryListGenerator
  146. {
  147. public:
  148. cmCaseInsensitiveDirectoryListGenerator(cm::string_view name)
  149. : DirName{ name }
  150. {
  151. }
  152. std::string GetNextCandidate(std::string const& parent)
  153. {
  154. if (!this->Loaded) {
  155. this->CurrentIdx = 0ul;
  156. this->Loaded = true;
  157. if (!this->DirectoryLister.Load(parent)) {
  158. return {};
  159. }
  160. }
  161. while (this->CurrentIdx < this->DirectoryLister.GetNumberOfFiles()) {
  162. char const* const fname =
  163. this->DirectoryLister.GetFile(this->CurrentIdx++);
  164. if (isDirentryToIgnore(fname)) {
  165. continue;
  166. }
  167. if (cmsysString_strcasecmp(fname, this->DirName.data()) == 0) {
  168. auto candidate = cmStrCat(parent, fname, '/');
  169. if (cmSystemTools::FileIsDirectory(candidate)) {
  170. return candidate;
  171. }
  172. }
  173. }
  174. return {};
  175. }
  176. void Reset() { this->Loaded = false; }
  177. private:
  178. cmsys::Directory DirectoryLister;
  179. cm::string_view const DirName;
  180. unsigned long CurrentIdx = 0ul;
  181. bool Loaded = false;
  182. };
  183. class cmDirectoryListGenerator
  184. {
  185. public:
  186. cmDirectoryListGenerator(std::vector<std::string> const* names,
  187. bool exactMatch)
  188. : Names{ names }
  189. , ExactMatch{ exactMatch }
  190. , Current{ this->Matches.cbegin() }
  191. {
  192. assert(names || !exactMatch);
  193. assert(!names || !names->empty());
  194. }
  195. virtual ~cmDirectoryListGenerator() = default;
  196. std::string GetNextCandidate(std::string const& parent)
  197. {
  198. // Construct a list of matches if not yet
  199. if (this->Matches.empty()) {
  200. cmsys::Directory directoryLister;
  201. // ALERT `Directory::Load()` keeps only names
  202. // internally and LOST entry type from `dirent`.
  203. // So, `Directory::FileIsDirectory` gonna use
  204. // `SystemTools::FileIsDirectory()` and waste a syscall.
  205. // TODO Need to enhance the `Directory` class.
  206. directoryLister.Load(parent);
  207. // ATTENTION Is it guaranteed that first two entries are
  208. // `.` and `..`?
  209. // TODO If so, just start with index 2 and drop the
  210. // `isDirentryToIgnore(i)` condition to check.
  211. for (auto i = 0ul; i < directoryLister.GetNumberOfFiles(); ++i) {
  212. char const* const fname = directoryLister.GetFile(i);
  213. // Skip entries to ignore or that aren't directories.
  214. if (isDirentryToIgnore(fname) || !directoryLister.FileIsDirectory(i)) {
  215. continue;
  216. }
  217. if (!this->Names) {
  218. this->Matches.emplace_back(fname);
  219. } else {
  220. for (auto const& n : *this->Names) {
  221. // NOTE Customization point for
  222. // `cmMacProjectDirectoryListGenerator`
  223. auto const name = this->TransformNameBeforeCmp(n);
  224. // Skip entries that don't match.
  225. auto const equal =
  226. ((this->ExactMatch
  227. ? cmsysString_strcasecmp(fname, name.c_str())
  228. : cmsysString_strncasecmp(fname, name.c_str(),
  229. name.length())) == 0);
  230. if (equal) {
  231. this->Matches.emplace_back(fname);
  232. break;
  233. }
  234. }
  235. }
  236. }
  237. // NOTE Customization point for `cmProjectDirectoryListGenerator`
  238. this->OnMatchesLoaded();
  239. this->Current = this->Matches.cbegin();
  240. }
  241. if (this->Current != this->Matches.cend()) {
  242. auto candidate = cmStrCat(parent, *this->Current++, '/');
  243. return candidate;
  244. }
  245. return {};
  246. }
  247. void Reset()
  248. {
  249. this->Matches.clear();
  250. this->Current = this->Matches.cbegin();
  251. }
  252. protected:
  253. virtual void OnMatchesLoaded() {}
  254. virtual std::string TransformNameBeforeCmp(std::string same) { return same; }
  255. std::vector<std::string> const* Names;
  256. bool const ExactMatch;
  257. std::vector<std::string> Matches;
  258. std::vector<std::string>::const_iterator Current;
  259. };
  260. class cmProjectDirectoryListGenerator : public cmDirectoryListGenerator
  261. {
  262. public:
  263. cmProjectDirectoryListGenerator(std::vector<std::string> const* names,
  264. cmFindPackageCommand::SortOrderType so,
  265. cmFindPackageCommand::SortDirectionType sd,
  266. bool exactMatch)
  267. : cmDirectoryListGenerator{ names, exactMatch }
  268. , SortOrder{ so }
  269. , SortDirection{ sd }
  270. {
  271. }
  272. protected:
  273. void OnMatchesLoaded() override
  274. {
  275. // check if there is a specific sorting order to perform
  276. if (this->SortOrder != cmFindPackageCommand::None) {
  277. cmFindPackageCommand::Sort(this->Matches.begin(), this->Matches.end(),
  278. this->SortOrder, this->SortDirection);
  279. }
  280. }
  281. private:
  282. // sort parameters
  283. cmFindPackageCommand::SortOrderType const SortOrder;
  284. cmFindPackageCommand::SortDirectionType const SortDirection;
  285. };
  286. class cmMacProjectDirectoryListGenerator : public cmDirectoryListGenerator
  287. {
  288. public:
  289. cmMacProjectDirectoryListGenerator(std::vector<std::string> const* names,
  290. cm::string_view ext)
  291. : cmDirectoryListGenerator{ names, true }
  292. , Extension{ ext }
  293. {
  294. }
  295. protected:
  296. std::string TransformNameBeforeCmp(std::string name) override
  297. {
  298. return cmStrCat(name, this->Extension);
  299. }
  300. private:
  301. cm::string_view const Extension;
  302. };
  303. class cmAnyDirectoryListGenerator : public cmProjectDirectoryListGenerator
  304. {
  305. public:
  306. cmAnyDirectoryListGenerator(cmFindPackageCommand::SortOrderType so,
  307. cmFindPackageCommand::SortDirectionType sd)
  308. : cmProjectDirectoryListGenerator(nullptr, so, sd, false)
  309. {
  310. }
  311. };
  312. #if defined(__LCC__)
  313. # define CM_LCC_DIAG_SUPPRESS_1222
  314. # pragma diag_suppress 1222 // invalid error number (3288, but works anyway)
  315. # define CM_LCC_DIAG_SUPPRESS_3288
  316. # pragma diag_suppress 3288 // parameter was declared but never referenced
  317. # define CM_LCC_DIAG_SUPPRESS_3301
  318. # pragma diag_suppress 3301 // parameter was declared but never referenced
  319. # define CM_LCC_DIAG_SUPPRESS_3308
  320. # pragma diag_suppress 3308 // parameter was declared but never referenced
  321. #endif
  322. void ResetGenerator()
  323. {
  324. }
  325. template <typename Generator>
  326. void ResetGenerator(Generator&& generator)
  327. {
  328. std::forward<Generator&&>(generator).Reset();
  329. }
  330. template <typename Generator, typename... Generators>
  331. void ResetGenerator(Generator&& generator, Generators&&... generators)
  332. {
  333. ResetGenerator(std::forward<Generator&&>(generator));
  334. ResetGenerator(std::forward<Generators&&>(generators)...);
  335. }
  336. template <typename CallbackFn>
  337. bool TryGeneratedPaths(CallbackFn&& filesCollector,
  338. cmFindPackageCommand::PackageDescriptionType type,
  339. std::string const& fullPath)
  340. {
  341. assert(!fullPath.empty() && fullPath.back() == '/');
  342. return std::forward<CallbackFn&&>(filesCollector)(fullPath, type);
  343. }
  344. template <typename CallbackFn, typename Generator, typename... Rest>
  345. bool TryGeneratedPaths(CallbackFn&& filesCollector,
  346. cmFindPackageCommand::PackageDescriptionType type,
  347. std::string const& startPath, Generator&& gen,
  348. Rest&&... tail)
  349. {
  350. ResetGenerator(std::forward<Generator&&>(gen));
  351. for (auto path = gen.GetNextCandidate(startPath); !path.empty();
  352. path = gen.GetNextCandidate(startPath)) {
  353. ResetGenerator(std::forward<Rest&&>(tail)...);
  354. if (TryGeneratedPaths(std::forward<CallbackFn&&>(filesCollector), type,
  355. path, std::forward<Rest&&>(tail)...)) {
  356. return true;
  357. }
  358. }
  359. return false;
  360. }
  361. #ifdef CM_LCC_DIAG_SUPPRESS_3308
  362. # undef CM_LCC_DIAG_SUPPRESS_3308
  363. # pragma diag_default 3308
  364. #endif
  365. #ifdef CM_LCC_DIAG_SUPPRESS_3301
  366. # undef CM_LCC_DIAG_SUPPRESS_3301
  367. # pragma diag_default 3301
  368. #endif
  369. #ifdef CM_LCC_DIAG_SUPPRESS_3288
  370. # undef CM_LCC_DIAG_SUPPRESS_3288
  371. # pragma diag_default 3288
  372. #endif
  373. #ifdef CM_LCC_DIAG_SUPPRESS_1222
  374. # undef CM_LCC_DIAG_SUPPRESS_1222
  375. # pragma diag_default 1222
  376. #endif
  377. // Parse the version number and store the results that were
  378. // successfully parsed.
  379. unsigned int parseVersion(std::string const& version, unsigned int& major,
  380. unsigned int& minor, unsigned int& patch,
  381. unsigned int& tweak)
  382. {
  383. return static_cast<unsigned int>(std::sscanf(
  384. version.c_str(), "%u.%u.%u.%u", &major, &minor, &patch, &tweak));
  385. }
  386. } // anonymous namespace
  387. class cmFindPackageCommand::FlushDebugBufferOnExit
  388. {
  389. cmFindPackageCommand& Command;
  390. public:
  391. FlushDebugBufferOnExit(cmFindPackageCommand& command)
  392. : Command(command)
  393. {
  394. }
  395. ~FlushDebugBufferOnExit()
  396. {
  397. if (!Command.DebugBuffer.empty()) {
  398. Command.DebugMessage(Command.DebugBuffer);
  399. }
  400. }
  401. };
  402. class cmFindPackageCommand::PushPopRootPathStack
  403. {
  404. cmFindPackageCommand& Command;
  405. public:
  406. PushPopRootPathStack(cmFindPackageCommand& command)
  407. : Command(command)
  408. {
  409. Command.PushFindPackageRootPathStack();
  410. }
  411. ~PushPopRootPathStack() { Command.PopFindPackageRootPathStack(); }
  412. };
  413. class cmFindPackageCommand::SetRestoreFindDefinitions
  414. {
  415. cmFindPackageCommand& Command;
  416. public:
  417. SetRestoreFindDefinitions(cmFindPackageCommand& command)
  418. : Command(command)
  419. {
  420. Command.SetModuleVariables();
  421. }
  422. ~SetRestoreFindDefinitions() { Command.RestoreFindDefinitions(); }
  423. };
  424. cmFindPackageCommand::PathLabel
  425. cmFindPackageCommand::PathLabel::PackageRedirect("PACKAGE_REDIRECT");
  426. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::UserRegistry(
  427. "PACKAGE_REGISTRY");
  428. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::Builds(
  429. "BUILDS");
  430. cmFindPackageCommand::PathLabel
  431. cmFindPackageCommand::PathLabel::SystemRegistry("SYSTEM_PACKAGE_REGISTRY");
  432. cm::string_view const cmFindPackageCommand::VERSION_ENDPOINT_INCLUDED(
  433. "INCLUDE");
  434. cm::string_view const cmFindPackageCommand::VERSION_ENDPOINT_EXCLUDED(
  435. "EXCLUDE");
  436. void cmFindPackageCommand::Sort(std::vector<std::string>::iterator begin,
  437. std::vector<std::string>::iterator end,
  438. SortOrderType const order,
  439. SortDirectionType const dir)
  440. {
  441. if (order == Name_order) {
  442. if (dir == Dec) {
  443. std::sort(begin, end, std::greater<std::string>());
  444. } else {
  445. std::sort(begin, end);
  446. }
  447. } else if (order == Natural) {
  448. // natural order uses letters and numbers (contiguous numbers digit are
  449. // compared such that e.g. 000 00 < 01 < 010 < 09 < 0 < 1 < 9 < 10
  450. if (dir == Dec) {
  451. std::sort(begin, end, StrverscmpOp<std::greater>());
  452. } else {
  453. std::sort(begin, end, StrverscmpOp<std::less>());
  454. }
  455. }
  456. // else do not sort
  457. }
  458. cmFindPackageCommand::cmFindPackageCommand(cmExecutionStatus& status)
  459. : cmFindCommon(status)
  460. , VersionRangeMin(VERSION_ENDPOINT_INCLUDED)
  461. , VersionRangeMax(VERSION_ENDPOINT_INCLUDED)
  462. {
  463. this->CMakePathName = "PACKAGE";
  464. this->DebugMode = false;
  465. this->AppendSearchPathGroups();
  466. this->DeprecatedFindModules["Boost"] = cmPolicies::CMP0167;
  467. this->DeprecatedFindModules["CUDA"] = cmPolicies::CMP0146;
  468. this->DeprecatedFindModules["Dart"] = cmPolicies::CMP0145;
  469. this->DeprecatedFindModules["GCCXML"] = cmPolicies::CMP0188;
  470. this->DeprecatedFindModules["PythonInterp"] = cmPolicies::CMP0148;
  471. this->DeprecatedFindModules["PythonLibs"] = cmPolicies::CMP0148;
  472. this->DeprecatedFindModules["Qt"] = cmPolicies::CMP0084;
  473. }
  474. void cmFindPackageCommand::AppendSearchPathGroups()
  475. {
  476. // Update the All group with new paths. Note that package redirection must
  477. // take precedence over everything else, so it has to be first in the array.
  478. std::vector<cmFindCommon::PathLabel>* const labels =
  479. &this->PathGroupLabelMap[PathGroup::All];
  480. labels->insert(labels->begin(), PathLabel::PackageRedirect);
  481. labels->insert(
  482. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  483. PathLabel::UserRegistry);
  484. labels->insert(
  485. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  486. PathLabel::Builds);
  487. labels->insert(std::find(labels->begin(), labels->end(), PathLabel::Guess),
  488. PathLabel::SystemRegistry);
  489. // Create the new path objects
  490. this->LabeledPaths.emplace(PathLabel::PackageRedirect, cmSearchPath{ this });
  491. this->LabeledPaths.emplace(PathLabel::UserRegistry, cmSearchPath{ this });
  492. this->LabeledPaths.emplace(PathLabel::Builds, cmSearchPath{ this });
  493. this->LabeledPaths.emplace(PathLabel::SystemRegistry, cmSearchPath{ this });
  494. }
  495. void cmFindPackageCommand::InheritOptions(cmFindPackageCommand* other)
  496. {
  497. this->RequiredCMakeVersion = other->RequiredCMakeVersion;
  498. this->LibraryArchitecture = other->LibraryArchitecture;
  499. this->UseLib32Paths = other->UseLib32Paths;
  500. this->UseLib64Paths = other->UseLib64Paths;
  501. this->UseLibx32Paths = other->UseLibx32Paths;
  502. this->NoUserRegistry = other->NoUserRegistry;
  503. this->NoSystemRegistry = other->NoSystemRegistry;
  504. this->UseRealPath = other->UseRealPath;
  505. this->SortOrder = other->SortOrder;
  506. this->SortDirection = other->SortDirection;
  507. this->GlobalScope = other->GlobalScope;
  508. this->RegistryView = other->RegistryView;
  509. this->NoDefaultPath = other->NoDefaultPath;
  510. this->NoPackageRootPath = other->NoPackageRootPath;
  511. this->NoCMakePath = other->NoCMakePath;
  512. this->NoCMakeEnvironmentPath = other->NoCMakeEnvironmentPath;
  513. this->NoSystemEnvironmentPath = other->NoSystemEnvironmentPath;
  514. this->NoCMakeSystemPath = other->NoCMakeSystemPath;
  515. this->NoCMakeInstallPath = other->NoCMakeInstallPath;
  516. this->FindRootPathMode = other->FindRootPathMode;
  517. this->SearchFrameworkLast = other->SearchFrameworkLast;
  518. this->SearchFrameworkFirst = other->SearchFrameworkFirst;
  519. this->SearchFrameworkOnly = other->SearchFrameworkOnly;
  520. this->SearchAppBundleLast = other->SearchAppBundleLast;
  521. this->SearchAppBundleFirst = other->SearchAppBundleFirst;
  522. this->SearchAppBundleOnly = other->SearchAppBundleOnly;
  523. this->SearchPathSuffixes = other->SearchPathSuffixes;
  524. this->Quiet = other->Quiet;
  525. }
  526. bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args)
  527. {
  528. if (args.empty()) {
  529. this->SetError("called with incorrect number of arguments");
  530. return false;
  531. }
  532. // Lookup required version of CMake.
  533. if (cmValue const rv =
  534. this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION")) {
  535. unsigned int v[3] = { 0, 0, 0 };
  536. std::sscanf(rv->c_str(), "%u.%u.%u", &v[0], &v[1], &v[2]);
  537. this->RequiredCMakeVersion = CMake_VERSION_ENCODE(v[0], v[1], v[2]);
  538. }
  539. // Lookup target architecture, if any.
  540. if (cmValue const arch =
  541. this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE")) {
  542. this->LibraryArchitecture = *arch;
  543. }
  544. // Lookup whether lib32 paths should be used.
  545. if (this->Makefile->PlatformIs32Bit() &&
  546. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  547. "FIND_LIBRARY_USE_LIB32_PATHS")) {
  548. this->UseLib32Paths = true;
  549. }
  550. // Lookup whether lib64 paths should be used.
  551. if (this->Makefile->PlatformIs64Bit() &&
  552. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  553. "FIND_LIBRARY_USE_LIB64_PATHS")) {
  554. this->UseLib64Paths = true;
  555. }
  556. // Lookup whether libx32 paths should be used.
  557. if (this->Makefile->PlatformIsx32() &&
  558. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  559. "FIND_LIBRARY_USE_LIBX32_PATHS")) {
  560. this->UseLibx32Paths = true;
  561. }
  562. // Check if User Package Registry should be disabled
  563. // The `CMAKE_FIND_USE_PACKAGE_REGISTRY` has
  564. // priority over the deprecated CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY
  565. if (cmValue const def =
  566. this->Makefile->GetDefinition("CMAKE_FIND_USE_PACKAGE_REGISTRY")) {
  567. this->NoUserRegistry = !def.IsOn();
  568. } else if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY")) {
  569. this->NoUserRegistry = true;
  570. }
  571. // Check if System Package Registry should be disabled
  572. // The `CMAKE_FIND_USE_SYSTEM_PACKAGE_REGISTRY` has
  573. // priority over the deprecated CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY
  574. if (cmValue const def = this->Makefile->GetDefinition(
  575. "CMAKE_FIND_USE_SYSTEM_PACKAGE_REGISTRY")) {
  576. this->NoSystemRegistry = !def.IsOn();
  577. } else if (this->Makefile->IsOn(
  578. "CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY")) {
  579. this->NoSystemRegistry = true;
  580. }
  581. // Check whether we should resolve symlinks when finding packages
  582. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS")) {
  583. this->UseRealPath = true;
  584. }
  585. // Check if Sorting should be enabled
  586. if (cmValue const so =
  587. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_ORDER")) {
  588. if (*so == "NAME") {
  589. this->SortOrder = Name_order;
  590. } else if (*so == "NATURAL") {
  591. this->SortOrder = Natural;
  592. } else {
  593. this->SortOrder = None;
  594. }
  595. }
  596. if (cmValue const sd =
  597. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_DIRECTION")) {
  598. this->SortDirection = (*sd == "DEC") ? Dec : Asc;
  599. }
  600. // Find what search path locations have been enabled/disable.
  601. this->SelectDefaultSearchModes();
  602. // Find the current root path mode.
  603. this->SelectDefaultRootPathMode();
  604. // Find the current bundle/framework search policy.
  605. this->SelectDefaultMacMode();
  606. // Record options.
  607. this->Name = args[0];
  608. cm::string_view componentsSep = ""_s;
  609. bool bypassProvider = false;
  610. // Always search directly in a generated path.
  611. this->SearchPathSuffixes.emplace_back();
  612. // Process debug mode
  613. cmMakefile::DebugFindPkgRAII debugFindPkgRAII(this->Makefile, this->Name);
  614. this->DebugMode = this->ComputeIfDebugModeWanted();
  615. // Parse the arguments.
  616. enum Doing
  617. {
  618. DoingNone,
  619. DoingComponents,
  620. DoingOptionalComponents,
  621. DoingNames,
  622. DoingPaths,
  623. DoingPathSuffixes,
  624. DoingConfigs,
  625. DoingHints
  626. };
  627. Doing doing = DoingNone;
  628. cmsys::RegularExpression versionRegex(
  629. R"V(^([0-9]+(\.[0-9]+)*)(\.\.\.(<?)([0-9]+(\.[0-9]+)*))?$)V");
  630. bool haveVersion = false;
  631. std::vector<std::size_t> configArgs;
  632. std::vector<std::size_t> moduleArgs;
  633. for (std::size_t i = 1u; i < args.size(); ++i) {
  634. if (args[i] == "QUIET") {
  635. this->Quiet = true;
  636. doing = DoingNone;
  637. } else if (args[i] == "BYPASS_PROVIDER") {
  638. bypassProvider = true;
  639. doing = DoingNone;
  640. } else if (args[i] == "EXACT") {
  641. this->VersionExact = true;
  642. doing = DoingNone;
  643. } else if (args[i] == "GLOBAL") {
  644. this->GlobalScope = true;
  645. doing = DoingNone;
  646. } else if (args[i] == "MODULE") {
  647. moduleArgs.push_back(i);
  648. doing = DoingNone;
  649. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  650. // NOLINTNEXTLINE(bugprone-branch-clone)
  651. } else if (args[i] == "CONFIG") {
  652. configArgs.push_back(i);
  653. doing = DoingNone;
  654. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  655. // NOLINTNEXTLINE(bugprone-branch-clone)
  656. } else if (args[i] == "NO_MODULE") {
  657. configArgs.push_back(i);
  658. doing = DoingNone;
  659. } else if (args[i] == "REQUIRED") {
  660. if (this->Required == RequiredStatus::OptionalExplicit) {
  661. this->SetError("cannot be both REQUIRED and OPTIONAL");
  662. return false;
  663. }
  664. this->Required = RequiredStatus::RequiredExplicit;
  665. doing = DoingComponents;
  666. } else if (args[i] == "OPTIONAL") {
  667. if (this->Required == RequiredStatus::RequiredExplicit) {
  668. this->SetError("cannot be both REQUIRED and OPTIONAL");
  669. return false;
  670. }
  671. this->Required = RequiredStatus::OptionalExplicit;
  672. doing = DoingComponents;
  673. } else if (args[i] == "COMPONENTS") {
  674. doing = DoingComponents;
  675. } else if (args[i] == "OPTIONAL_COMPONENTS") {
  676. doing = DoingOptionalComponents;
  677. } else if (args[i] == "NAMES") {
  678. configArgs.push_back(i);
  679. doing = DoingNames;
  680. } else if (args[i] == "PATHS") {
  681. configArgs.push_back(i);
  682. doing = DoingPaths;
  683. } else if (args[i] == "HINTS") {
  684. configArgs.push_back(i);
  685. doing = DoingHints;
  686. } else if (args[i] == "PATH_SUFFIXES") {
  687. configArgs.push_back(i);
  688. doing = DoingPathSuffixes;
  689. } else if (args[i] == "CONFIGS") {
  690. configArgs.push_back(i);
  691. doing = DoingConfigs;
  692. } else if (args[i] == "NO_POLICY_SCOPE") {
  693. this->PolicyScope = false;
  694. doing = DoingNone;
  695. } else if (args[i] == "NO_CMAKE_PACKAGE_REGISTRY") {
  696. this->NoUserRegistry = true;
  697. configArgs.push_back(i);
  698. doing = DoingNone;
  699. } else if (args[i] == "NO_CMAKE_SYSTEM_PACKAGE_REGISTRY") {
  700. this->NoSystemRegistry = true;
  701. configArgs.push_back(i);
  702. doing = DoingNone;
  703. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  704. // NOLINTNEXTLINE(bugprone-branch-clone)
  705. } else if (args[i] == "NO_CMAKE_BUILDS_PATH") {
  706. // Ignore legacy option.
  707. configArgs.push_back(i);
  708. doing = DoingNone;
  709. } else if (args[i] == "REGISTRY_VIEW") {
  710. if (++i == args.size()) {
  711. this->SetError("missing required argument for REGISTRY_VIEW");
  712. return false;
  713. }
  714. auto view = cmWindowsRegistry::ToView(args[i]);
  715. if (view) {
  716. this->RegistryView = *view;
  717. this->RegistryViewDefined = true;
  718. } else {
  719. this->SetError(
  720. cmStrCat("given invalid value for REGISTRY_VIEW: ", args[i]));
  721. return false;
  722. }
  723. } else if (this->CheckCommonArgument(args[i])) {
  724. configArgs.push_back(i);
  725. doing = DoingNone;
  726. } else if ((doing == DoingComponents) ||
  727. (doing == DoingOptionalComponents)) {
  728. // Set a variable telling the find script whether this component
  729. // is required.
  730. if (doing == DoingOptionalComponents) {
  731. this->OptionalComponents.insert(args[i]);
  732. } else {
  733. this->RequiredComponents.insert(args[i]);
  734. }
  735. // Append to the list of required components.
  736. this->Components += componentsSep;
  737. this->Components += args[i];
  738. componentsSep = ";"_s;
  739. } else if (doing == DoingNames) {
  740. this->Names.push_back(args[i]);
  741. } else if (doing == DoingPaths) {
  742. this->UserGuessArgs.push_back(args[i]);
  743. } else if (doing == DoingHints) {
  744. this->UserHintsArgs.push_back(args[i]);
  745. } else if (doing == DoingPathSuffixes) {
  746. this->AddPathSuffix(args[i]);
  747. } else if (doing == DoingConfigs) {
  748. if (args[i].find_first_of(":/\\") != std::string::npos ||
  749. cmSystemTools::GetFilenameLastExtension(args[i]) != ".cmake") {
  750. this->SetError(cmStrCat(
  751. "given CONFIGS option followed by invalid file name \"", args[i],
  752. "\". The names given must be file names without "
  753. "a path and with a \".cmake\" extension."));
  754. return false;
  755. }
  756. this->Configs.emplace_back(args[i], pdt::CMake);
  757. } else if (!haveVersion && versionRegex.find(args[i])) {
  758. haveVersion = true;
  759. this->VersionComplete = args[i];
  760. } else {
  761. this->SetError(
  762. cmStrCat("called with invalid argument \"", args[i], "\""));
  763. return false;
  764. }
  765. }
  766. if (this->Required == RequiredStatus::Optional &&
  767. this->Makefile->IsOn("CMAKE_FIND_REQUIRED")) {
  768. this->Required = RequiredStatus::RequiredFromFindVar;
  769. }
  770. if (!this->GlobalScope) {
  771. cmValue value(
  772. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_TARGETS_GLOBAL"));
  773. this->GlobalScope = value.IsOn();
  774. }
  775. std::vector<std::string> doubledComponents;
  776. std::set_intersection(
  777. this->RequiredComponents.begin(), this->RequiredComponents.end(),
  778. this->OptionalComponents.begin(), this->OptionalComponents.end(),
  779. std::back_inserter(doubledComponents));
  780. if (!doubledComponents.empty()) {
  781. this->SetError(
  782. cmStrCat("called with components that are both required and "
  783. "optional:\n",
  784. cmWrap(" ", doubledComponents, "", "\n"), '\n'));
  785. return false;
  786. }
  787. // Check and eliminate search modes not allowed by the args provided
  788. this->UseFindModules = configArgs.empty();
  789. this->UseConfigFiles = moduleArgs.empty();
  790. if (this->UseConfigFiles &&
  791. cmExperimental::HasSupportEnabled(
  792. *this->Makefile, cmExperimental::Feature::ImportPackageInfo)) {
  793. this->UseCpsFiles = this->Configs.empty();
  794. } else {
  795. this->UseCpsFiles = false;
  796. }
  797. if (!this->UseFindModules && !this->UseConfigFiles) {
  798. std::ostringstream e;
  799. e << "given options exclusive to Module mode:\n";
  800. for (auto si : moduleArgs) {
  801. e << " " << args[si] << "\n";
  802. }
  803. e << "and options exclusive to Config mode:\n";
  804. for (auto si : configArgs) {
  805. e << " " << args[si] << "\n";
  806. }
  807. e << "The options are incompatible.";
  808. this->SetError(e.str());
  809. return false;
  810. }
  811. // Ignore EXACT with no version.
  812. if (this->VersionComplete.empty() && this->VersionExact) {
  813. this->VersionExact = false;
  814. this->Makefile->IssueMessage(
  815. MessageType::AUTHOR_WARNING,
  816. "Ignoring EXACT since no version is requested.");
  817. }
  818. if (this->VersionComplete.empty() || this->Components.empty()) {
  819. // Check whether we are recursing inside "Find<name>.cmake" within
  820. // another find_package(<name>) call.
  821. std::string const mod = cmStrCat(this->Name, "_FIND_MODULE");
  822. if (this->Makefile->IsOn(mod)) {
  823. if (this->VersionComplete.empty()) {
  824. // Get version information from the outer call if necessary.
  825. // Requested version string.
  826. std::string const ver = cmStrCat(this->Name, "_FIND_VERSION_COMPLETE");
  827. this->VersionComplete = this->Makefile->GetSafeDefinition(ver);
  828. // Whether an exact version is required.
  829. std::string const exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT");
  830. this->VersionExact = this->Makefile->IsOn(exact);
  831. }
  832. if (this->Components.empty()) {
  833. std::string const components_var = this->Name + "_FIND_COMPONENTS";
  834. this->Components = this->Makefile->GetSafeDefinition(components_var);
  835. for (auto const& component : cmList{ this->Components }) {
  836. this->RequiredComponents.insert(component);
  837. }
  838. }
  839. }
  840. }
  841. // fill various parts of version specification
  842. if (!this->VersionComplete.empty()) {
  843. if (!versionRegex.find(this->VersionComplete)) {
  844. this->SetError("called with invalid version specification.");
  845. return false;
  846. }
  847. this->Version = versionRegex.match(1);
  848. this->VersionMax = versionRegex.match(5);
  849. if (versionRegex.match(4) == "<"_s) {
  850. this->VersionRangeMax = VERSION_ENDPOINT_EXCLUDED;
  851. }
  852. if (!this->VersionMax.empty()) {
  853. this->VersionRange = this->VersionComplete;
  854. }
  855. }
  856. if (!this->VersionRange.empty()) {
  857. // version range must not be empty
  858. if ((this->VersionRangeMax == VERSION_ENDPOINT_INCLUDED &&
  859. cmSystemTools::VersionCompareGreater(this->Version,
  860. this->VersionMax)) ||
  861. (this->VersionRangeMax == VERSION_ENDPOINT_EXCLUDED &&
  862. cmSystemTools::VersionCompareGreaterEq(this->Version,
  863. this->VersionMax))) {
  864. this->SetError("specified version range is empty.");
  865. return false;
  866. }
  867. }
  868. if (this->VersionExact && !this->VersionRange.empty()) {
  869. this->SetError("EXACT cannot be specified with a version range.");
  870. return false;
  871. }
  872. if (!this->Version.empty()) {
  873. this->VersionCount =
  874. parseVersion(this->Version, this->VersionMajor, this->VersionMinor,
  875. this->VersionPatch, this->VersionTweak);
  876. }
  877. if (!this->VersionMax.empty()) {
  878. this->VersionMaxCount = parseVersion(
  879. this->VersionMax, this->VersionMaxMajor, this->VersionMaxMinor,
  880. this->VersionMaxPatch, this->VersionMaxTweak);
  881. }
  882. return this->FindPackage(bypassProvider ? std::vector<std::string>{} : args);
  883. }
  884. bool cmFindPackageCommand::FindPackage(
  885. std::vector<std::string> const& argsForProvider)
  886. {
  887. std::string const makePackageRequiredVar =
  888. cmStrCat("CMAKE_REQUIRE_FIND_PACKAGE_", this->Name);
  889. bool const makePackageRequiredSet =
  890. this->Makefile->IsOn(makePackageRequiredVar);
  891. if (makePackageRequiredSet) {
  892. if (this->IsRequired()) {
  893. this->Makefile->IssueMessage(
  894. MessageType::WARNING,
  895. cmStrCat("for module ", this->Name,
  896. " already called with REQUIRED, thus ",
  897. makePackageRequiredVar, " has no effect."));
  898. } else {
  899. this->Required = RequiredStatus::RequiredFromPackageVar;
  900. }
  901. }
  902. std::string const disableFindPackageVar =
  903. cmStrCat("CMAKE_DISABLE_FIND_PACKAGE_", this->Name);
  904. if (this->Makefile->IsOn(disableFindPackageVar)) {
  905. if (this->IsRequired()) {
  906. this->SetError(
  907. cmStrCat("for module ", this->Name,
  908. (makePackageRequiredSet
  909. ? " was made REQUIRED with " + makePackageRequiredVar
  910. : " called with REQUIRED, "),
  911. " but ", disableFindPackageVar,
  912. " is enabled. A REQUIRED package cannot be disabled."));
  913. return false;
  914. }
  915. return true;
  916. }
  917. // Restore PACKAGE_PREFIX_DIR to its pre-call value when we return. If our
  918. // caller is a file generated by configure_package_config_file(), and if
  919. // the package we are about to load also has a config file created by that
  920. // command, it will overwrite PACKAGE_PREFIX_DIR. We need to restore it in
  921. // case something still refers to it in our caller's scope after we return.
  922. class RestoreVariableOnLeavingScope
  923. {
  924. cmMakefile* makefile_;
  925. cm::optional<std::string> value_;
  926. public:
  927. RestoreVariableOnLeavingScope(cmMakefile* makefile)
  928. : makefile_(makefile)
  929. {
  930. cmValue v = makefile->GetDefinition("PACKAGE_PREFIX_DIR");
  931. if (v) {
  932. value_ = *v;
  933. }
  934. }
  935. ~RestoreVariableOnLeavingScope()
  936. {
  937. if (this->value_) {
  938. makefile_->AddDefinition("PACKAGE_PREFIX_DIR", *value_);
  939. } else {
  940. makefile_->RemoveDefinition("PACKAGE_PREFIX_DIR");
  941. }
  942. }
  943. };
  944. RestoreVariableOnLeavingScope restorePackagePrefixDir(this->Makefile);
  945. // Now choose what method(s) we will use to satisfy the request. Note that
  946. // we still want all the above checking of arguments, etc. regardless of the
  947. // method used. This will ensure ill-formed arguments are caught earlier,
  948. // before things like dependency providers need to deal with them.
  949. // A dependency provider (if set) gets first look before other methods.
  950. // We do this before modifying the package root path stack because a
  951. // provider might use methods that ignore that.
  952. cmState* const state = this->Makefile->GetState();
  953. cmState::Command const providerCommand = state->GetDependencyProviderCommand(
  954. cmDependencyProvider::Method::FindPackage);
  955. if (argsForProvider.empty()) {
  956. if (this->DebugMode && providerCommand) {
  957. this->DebugMessage(
  958. "BYPASS_PROVIDER given, skipping dependency provider");
  959. }
  960. } else if (providerCommand) {
  961. if (this->DebugMode) {
  962. this->DebugMessage(cmStrCat("Trying dependency provider command: ",
  963. state->GetDependencyProvider()->GetCommand(),
  964. "()"));
  965. }
  966. std::vector<cmListFileArgument> listFileArgs(argsForProvider.size() + 1);
  967. listFileArgs[0] =
  968. cmListFileArgument("FIND_PACKAGE", cmListFileArgument::Unquoted, 0);
  969. std::transform(argsForProvider.begin(), argsForProvider.end(),
  970. listFileArgs.begin() + 1, [](std::string const& arg) {
  971. return cmListFileArgument(arg,
  972. cmListFileArgument::Bracket, 0);
  973. });
  974. if (!providerCommand(listFileArgs, this->Status)) {
  975. return false;
  976. }
  977. if (this->Makefile->IsOn(cmStrCat(this->Name, "_FOUND"))) {
  978. if (this->DebugMode) {
  979. this->DebugMessage("Package was found by the dependency provider");
  980. }
  981. this->AppendSuccessInformation();
  982. return true;
  983. }
  984. }
  985. // Limit package nesting depth well below the recursion depth limit because
  986. // find_package nesting uses more stack space than normal recursion.
  987. {
  988. static std::size_t const findPackageDepthMinMax = 100;
  989. std::size_t const findPackageDepthMax = std::max(
  990. this->Makefile->GetRecursionDepthLimit() / 2, findPackageDepthMinMax);
  991. std::size_t const findPackageDepth =
  992. this->Makefile->FindPackageRootPathStack.size() + 1;
  993. if (findPackageDepth > findPackageDepthMax) {
  994. this->SetError(cmStrCat("maximum nesting depth of ", findPackageDepthMax,
  995. " exceeded."));
  996. return false;
  997. }
  998. }
  999. // RAII objects to ensure we leave this function with consistent state.
  1000. FlushDebugBufferOnExit flushDebugBufferOnExit(*this);
  1001. PushPopRootPathStack pushPopRootPathStack(*this);
  1002. SetRestoreFindDefinitions setRestoreFindDefinitions(*this);
  1003. cmMakefile::FindPackageStackRAII findPackageStackRAII(this->Makefile,
  1004. this->Name);
  1005. // See if we have been told to delegate to FetchContent or some other
  1006. // redirected config package first. We have to check all names that
  1007. // find_package() may look for, but only need to invoke the override for the
  1008. // first one that matches.
  1009. auto overrideNames = this->Names;
  1010. if (overrideNames.empty()) {
  1011. overrideNames.push_back(this->Name);
  1012. }
  1013. bool forceConfigMode = false;
  1014. auto const redirectsDir =
  1015. this->Makefile->GetSafeDefinition("CMAKE_FIND_PACKAGE_REDIRECTS_DIR");
  1016. for (auto const& overrideName : overrideNames) {
  1017. auto const nameLower = cmSystemTools::LowerCase(overrideName);
  1018. auto const delegatePropName =
  1019. cmStrCat("_FetchContent_", nameLower, "_override_find_package");
  1020. cmValue const delegateToFetchContentProp =
  1021. this->Makefile->GetState()->GetGlobalProperty(delegatePropName);
  1022. if (delegateToFetchContentProp.IsOn()) {
  1023. // When this property is set, the FetchContent module has already been
  1024. // included at least once, so we know the FetchContent_MakeAvailable()
  1025. // command will be defined. Any future find_package() calls after this
  1026. // one for this package will by-pass this once-only delegation.
  1027. // The following call will typically create a <name>-config.cmake file
  1028. // in the redirectsDir, which we still want to process like any other
  1029. // config file to ensure we follow normal find_package() processing.
  1030. cmListFileFunction func(
  1031. "FetchContent_MakeAvailable", 0, 0,
  1032. { cmListFileArgument(overrideName, cmListFileArgument::Unquoted, 0) });
  1033. if (!this->Makefile->ExecuteCommand(func, this->Status)) {
  1034. return false;
  1035. }
  1036. }
  1037. if (cmSystemTools::FileExists(
  1038. cmStrCat(redirectsDir, '/', nameLower, "-config.cmake")) ||
  1039. cmSystemTools::FileExists(
  1040. cmStrCat(redirectsDir, '/', overrideName, "Config.cmake"))) {
  1041. // Force the use of this redirected config package file, regardless of
  1042. // the type of find_package() call. Files in the redirectsDir must always
  1043. // take priority over everything else.
  1044. forceConfigMode = true;
  1045. this->UseConfigFiles = true;
  1046. this->UseFindModules = false;
  1047. this->Names.clear();
  1048. this->Names.emplace_back(overrideName); // Force finding this one
  1049. this->Variable = cmStrCat(this->Name, "_DIR");
  1050. this->SetConfigDirCacheVariable(redirectsDir);
  1051. break;
  1052. }
  1053. }
  1054. // See if there is a Find<PackageName>.cmake module.
  1055. bool loadedPackage = false;
  1056. if (forceConfigMode) {
  1057. loadedPackage = this->FindPackageUsingConfigMode();
  1058. } else if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  1059. if (this->UseConfigFiles && this->FindPackageUsingConfigMode()) {
  1060. loadedPackage = true;
  1061. } else {
  1062. if (this->FindPackageUsingModuleMode()) {
  1063. loadedPackage = true;
  1064. } else {
  1065. // The package was not loaded. Report errors.
  1066. if (this->HandlePackageMode(HandlePackageModeType::Module)) {
  1067. loadedPackage = true;
  1068. }
  1069. }
  1070. }
  1071. } else {
  1072. if (this->UseFindModules && this->FindPackageUsingModuleMode()) {
  1073. loadedPackage = true;
  1074. } else {
  1075. // Handle CMAKE_FIND_PACKAGE_WARN_NO_MODULE (warn when CONFIG mode is
  1076. // implicitly assumed)
  1077. if (this->UseFindModules && this->UseConfigFiles &&
  1078. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_WARN_NO_MODULE")) {
  1079. std::ostringstream aw;
  1080. if (this->RequiredCMakeVersion >= CMake_VERSION_ENCODE(2, 8, 8)) {
  1081. aw << "find_package called without either MODULE or CONFIG option "
  1082. "and "
  1083. "no Find"
  1084. << this->Name
  1085. << ".cmake module is in CMAKE_MODULE_PATH. "
  1086. "Add MODULE to exclusively request Module mode and fail if "
  1087. "Find"
  1088. << this->Name
  1089. << ".cmake is missing. "
  1090. "Add CONFIG to exclusively request Config mode and search for "
  1091. "a "
  1092. "package configuration file provided by "
  1093. << this->Name << " (" << this->Name << "Config.cmake or "
  1094. << cmSystemTools::LowerCase(this->Name) << "-config.cmake). ";
  1095. } else {
  1096. aw << "find_package called without NO_MODULE option and no "
  1097. "Find"
  1098. << this->Name
  1099. << ".cmake module is in CMAKE_MODULE_PATH. "
  1100. "Add NO_MODULE to exclusively request Config mode and search "
  1101. "for a "
  1102. "package configuration file provided by "
  1103. << this->Name << " (" << this->Name << "Config.cmake or "
  1104. << cmSystemTools::LowerCase(this->Name)
  1105. << "-config.cmake). Otherwise make Find" << this->Name
  1106. << ".cmake available in CMAKE_MODULE_PATH.";
  1107. }
  1108. aw << "\n"
  1109. "(Variable CMAKE_FIND_PACKAGE_WARN_NO_MODULE enabled this "
  1110. "warning.)";
  1111. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  1112. }
  1113. if (this->FindPackageUsingConfigMode()) {
  1114. loadedPackage = true;
  1115. }
  1116. }
  1117. }
  1118. this->AppendSuccessInformation();
  1119. return loadedPackage;
  1120. }
  1121. bool cmFindPackageCommand::FindPackageUsingModuleMode()
  1122. {
  1123. bool foundModule = false;
  1124. if (!this->FindModule(foundModule)) {
  1125. return false;
  1126. }
  1127. return foundModule;
  1128. }
  1129. bool cmFindPackageCommand::FindPackageUsingConfigMode()
  1130. {
  1131. this->Variable = cmStrCat(this->Name, "_DIR");
  1132. // Add the default name.
  1133. if (this->Names.empty()) {
  1134. this->Names.push_back(this->Name);
  1135. }
  1136. // Add the default configs.
  1137. if (this->Configs.empty()) {
  1138. for (std::string const& n : this->Names) {
  1139. std::string config;
  1140. if (this->UseCpsFiles) {
  1141. config = cmStrCat(n, ".cps");
  1142. this->Configs.emplace_back(std::move(config), pdt::Cps);
  1143. config = cmStrCat(cmSystemTools::LowerCase(n), ".cps");
  1144. if (config != this->Configs.front().Name) {
  1145. this->Configs.emplace_back(std::move(config), pdt::Cps);
  1146. }
  1147. }
  1148. config = cmStrCat(n, "Config.cmake");
  1149. this->Configs.emplace_back(std::move(config), pdt::CMake);
  1150. config = cmStrCat(cmSystemTools::LowerCase(n), "-config.cmake");
  1151. this->Configs.emplace_back(std::move(config), pdt::CMake);
  1152. }
  1153. }
  1154. // get igonored paths from vars and reroot them.
  1155. std::vector<std::string> ignored;
  1156. this->GetIgnoredPaths(ignored);
  1157. this->RerootPaths(ignored);
  1158. // Construct a set of ignored paths
  1159. this->IgnoredPaths.clear();
  1160. this->IgnoredPaths.insert(ignored.begin(), ignored.end());
  1161. // get igonored prefix paths from vars and reroot them.
  1162. std::vector<std::string> ignoredPrefixes;
  1163. this->GetIgnoredPrefixPaths(ignoredPrefixes);
  1164. this->RerootPaths(ignoredPrefixes);
  1165. // Construct a set of ignored prefix paths
  1166. this->IgnoredPrefixPaths.clear();
  1167. this->IgnoredPrefixPaths.insert(ignoredPrefixes.begin(),
  1168. ignoredPrefixes.end());
  1169. // Find and load the package.
  1170. return this->HandlePackageMode(HandlePackageModeType::Config);
  1171. }
  1172. void cmFindPackageCommand::SetVersionVariables(
  1173. std::function<void(std::string const&, cm::string_view)> const&
  1174. addDefinition,
  1175. std::string const& prefix, std::string const& version,
  1176. unsigned int const count, unsigned int const major, unsigned int const minor,
  1177. unsigned int const patch, unsigned int const tweak)
  1178. {
  1179. addDefinition(prefix, version);
  1180. char buf[64];
  1181. snprintf(buf, sizeof(buf), "%u", major);
  1182. addDefinition(prefix + "_MAJOR", buf);
  1183. snprintf(buf, sizeof(buf), "%u", minor);
  1184. addDefinition(prefix + "_MINOR", buf);
  1185. snprintf(buf, sizeof(buf), "%u", patch);
  1186. addDefinition(prefix + "_PATCH", buf);
  1187. snprintf(buf, sizeof(buf), "%u", tweak);
  1188. addDefinition(prefix + "_TWEAK", buf);
  1189. snprintf(buf, sizeof(buf), "%u", count);
  1190. addDefinition(prefix + "_COUNT", buf);
  1191. }
  1192. void cmFindPackageCommand::SetModuleVariables()
  1193. {
  1194. this->AddFindDefinition("CMAKE_FIND_PACKAGE_NAME", this->Name);
  1195. // Nested find calls are not automatically required.
  1196. this->AddFindDefinition("CMAKE_FIND_REQUIRED", ""_s);
  1197. // Store the list of components and associated variable definitions.
  1198. std::string components_var = this->Name + "_FIND_COMPONENTS";
  1199. this->AddFindDefinition(components_var, this->Components);
  1200. for (auto const& component : this->OptionalComponents) {
  1201. this->AddFindDefinition(
  1202. cmStrCat(this->Name, "_FIND_REQUIRED_"_s, component), "0"_s);
  1203. }
  1204. for (auto const& component : this->RequiredComponents) {
  1205. this->AddFindDefinition(
  1206. cmStrCat(this->Name, "_FIND_REQUIRED_"_s, component), "1"_s);
  1207. }
  1208. if (this->Quiet) {
  1209. // Tell the module that is about to be read that it should find
  1210. // quietly.
  1211. std::string quietly = cmStrCat(this->Name, "_FIND_QUIETLY");
  1212. this->AddFindDefinition(quietly, "1"_s);
  1213. }
  1214. if (this->IsRequired()) {
  1215. // Tell the module that is about to be read that it should report
  1216. // a fatal error if the package is not found.
  1217. std::string req = cmStrCat(this->Name, "_FIND_REQUIRED");
  1218. this->AddFindDefinition(req, "1"_s);
  1219. }
  1220. if (!this->VersionComplete.empty()) {
  1221. std::string req = cmStrCat(this->Name, "_FIND_VERSION_COMPLETE");
  1222. this->AddFindDefinition(req, this->VersionComplete);
  1223. }
  1224. // Tell the module that is about to be read what version of the
  1225. // package has been requested.
  1226. auto addDefinition = [this](std::string const& variable,
  1227. cm::string_view value) {
  1228. this->AddFindDefinition(variable, value);
  1229. };
  1230. if (!this->Version.empty()) {
  1231. auto prefix = cmStrCat(this->Name, "_FIND_VERSION"_s);
  1232. this->SetVersionVariables(addDefinition, prefix, this->Version,
  1233. this->VersionCount, this->VersionMajor,
  1234. this->VersionMinor, this->VersionPatch,
  1235. this->VersionTweak);
  1236. // Tell the module whether an exact version has been requested.
  1237. auto exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT");
  1238. this->AddFindDefinition(exact, this->VersionExact ? "1"_s : "0"_s);
  1239. }
  1240. if (!this->VersionRange.empty()) {
  1241. auto prefix = cmStrCat(this->Name, "_FIND_VERSION_MIN"_s);
  1242. this->SetVersionVariables(addDefinition, prefix, this->Version,
  1243. this->VersionCount, this->VersionMajor,
  1244. this->VersionMinor, this->VersionPatch,
  1245. this->VersionTweak);
  1246. prefix = cmStrCat(this->Name, "_FIND_VERSION_MAX"_s);
  1247. this->SetVersionVariables(addDefinition, prefix, this->VersionMax,
  1248. this->VersionMaxCount, this->VersionMaxMajor,
  1249. this->VersionMaxMinor, this->VersionMaxPatch,
  1250. this->VersionMaxTweak);
  1251. auto id = cmStrCat(this->Name, "_FIND_VERSION_RANGE");
  1252. this->AddFindDefinition(id, this->VersionRange);
  1253. id = cmStrCat(this->Name, "_FIND_VERSION_RANGE_MIN");
  1254. this->AddFindDefinition(id, this->VersionRangeMin);
  1255. id = cmStrCat(this->Name, "_FIND_VERSION_RANGE_MAX");
  1256. this->AddFindDefinition(id, this->VersionRangeMax);
  1257. }
  1258. if (this->RegistryViewDefined) {
  1259. this->AddFindDefinition(cmStrCat(this->Name, "_FIND_REGISTRY_VIEW"),
  1260. cmWindowsRegistry::FromView(this->RegistryView));
  1261. }
  1262. }
  1263. void cmFindPackageCommand::AddFindDefinition(std::string const& var,
  1264. cm::string_view const value)
  1265. {
  1266. if (cmValue old = this->Makefile->GetDefinition(var)) {
  1267. this->OriginalDefs[var].exists = true;
  1268. this->OriginalDefs[var].value = *old;
  1269. } else {
  1270. this->OriginalDefs[var].exists = false;
  1271. }
  1272. this->Makefile->AddDefinition(var, value);
  1273. }
  1274. void cmFindPackageCommand::RestoreFindDefinitions()
  1275. {
  1276. for (auto const& i : this->OriginalDefs) {
  1277. OriginalDef const& od = i.second;
  1278. if (od.exists) {
  1279. this->Makefile->AddDefinition(i.first, od.value);
  1280. } else {
  1281. this->Makefile->RemoveDefinition(i.first);
  1282. }
  1283. }
  1284. }
  1285. bool cmFindPackageCommand::FindModule(bool& found)
  1286. {
  1287. std::string moduleFileName = cmStrCat("Find", this->Name, ".cmake");
  1288. bool system = false;
  1289. std::string debugBuffer = cmStrCat(
  1290. "find_package considered the following paths for ", moduleFileName, ":\n");
  1291. std::string mfile = this->Makefile->GetModulesFile(
  1292. moduleFileName, system, this->DebugMode, debugBuffer);
  1293. if (this->DebugMode) {
  1294. if (mfile.empty()) {
  1295. debugBuffer = cmStrCat(debugBuffer, "The file was not found.\n");
  1296. } else {
  1297. debugBuffer =
  1298. cmStrCat(debugBuffer, "The file was found at\n ", mfile, '\n');
  1299. }
  1300. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1301. }
  1302. if (!mfile.empty()) {
  1303. if (system) {
  1304. auto const it = this->DeprecatedFindModules.find(this->Name);
  1305. if (it != this->DeprecatedFindModules.end()) {
  1306. cmPolicies::PolicyStatus status =
  1307. this->Makefile->GetPolicyStatus(it->second);
  1308. switch (status) {
  1309. case cmPolicies::WARN: {
  1310. this->Makefile->IssueMessage(
  1311. MessageType::AUTHOR_WARNING,
  1312. cmStrCat(cmPolicies::GetPolicyWarning(it->second), '\n'));
  1313. CM_FALLTHROUGH;
  1314. }
  1315. case cmPolicies::OLD:
  1316. break;
  1317. case cmPolicies::NEW:
  1318. return true;
  1319. }
  1320. }
  1321. }
  1322. // Load the module we found, and set "<name>_FIND_MODULE" to true
  1323. // while inside it.
  1324. found = true;
  1325. std::string const var = cmStrCat(this->Name, "_FIND_MODULE");
  1326. this->Makefile->AddDefinition(var, "1");
  1327. bool result = this->ReadListFile(mfile, DoPolicyScope);
  1328. this->Makefile->RemoveDefinition(var);
  1329. if (this->DebugMode) {
  1330. std::string const foundVar = cmStrCat(this->Name, "_FOUND");
  1331. if (this->Makefile->IsDefinitionSet(foundVar) &&
  1332. !this->Makefile->IsOn(foundVar)) {
  1333. this->DebugBuffer = cmStrCat(
  1334. this->DebugBuffer, "The module is considered not found due to ",
  1335. foundVar, " being FALSE.");
  1336. }
  1337. }
  1338. return result;
  1339. }
  1340. return true;
  1341. }
  1342. bool cmFindPackageCommand::HandlePackageMode(
  1343. HandlePackageModeType const handlePackageModeType)
  1344. {
  1345. this->ConsideredConfigs.clear();
  1346. // Try to find the config file.
  1347. cmValue def = this->Makefile->GetDefinition(this->Variable);
  1348. // Try to load the config file if the directory is known
  1349. bool fileFound = false;
  1350. if (this->UseConfigFiles) {
  1351. if (!def.IsOff()) {
  1352. // Get the directory from the variable value.
  1353. std::string dir = *def;
  1354. cmSystemTools::ConvertToUnixSlashes(dir);
  1355. // Treat relative paths with respect to the current source dir.
  1356. if (!cmSystemTools::FileIsFullPath(dir)) {
  1357. dir = "/" + dir;
  1358. dir = this->Makefile->GetCurrentSourceDirectory() + dir;
  1359. }
  1360. // The file location was cached. Look for the correct file.
  1361. std::string file;
  1362. if (this->FindConfigFile(dir, pdt::Any, file)) {
  1363. this->FileFound = std::move(file);
  1364. fileFound = true;
  1365. }
  1366. def = this->Makefile->GetDefinition(this->Variable);
  1367. }
  1368. // Search for the config file if it is not already found.
  1369. if (def.IsOff() || !fileFound) {
  1370. fileFound = this->FindConfig();
  1371. }
  1372. // Sanity check.
  1373. if (fileFound && this->FileFound.empty()) {
  1374. this->Makefile->IssueMessage(
  1375. MessageType::INTERNAL_ERROR,
  1376. "fileFound is true but FileFound is empty!");
  1377. fileFound = false;
  1378. }
  1379. }
  1380. std::string const foundVar = cmStrCat(this->Name, "_FOUND");
  1381. std::string const notFoundMessageVar =
  1382. cmStrCat(this->Name, "_NOT_FOUND_MESSAGE");
  1383. std::string notFoundMessage;
  1384. // If the directory for the config file was found, try to read the file.
  1385. bool result = true;
  1386. bool found = false;
  1387. bool configFileSetFOUNDFalse = false;
  1388. if (fileFound) {
  1389. if (this->Makefile->IsDefinitionSet(foundVar) &&
  1390. !this->Makefile->IsOn(foundVar)) {
  1391. // by removing Foo_FOUND here if it is FALSE, we don't really change
  1392. // the situation for the Config file which is about to be included,
  1393. // but we make it possible to detect later on whether the Config file
  1394. // has set Foo_FOUND to FALSE itself:
  1395. this->Makefile->RemoveDefinition(foundVar);
  1396. }
  1397. this->Makefile->RemoveDefinition(notFoundMessageVar);
  1398. // Set the version variables before loading the config file.
  1399. // It may override them.
  1400. this->StoreVersionFound();
  1401. // Parse the configuration file.
  1402. if (this->CpsReader) {
  1403. // The package has been found.
  1404. found = true;
  1405. result = this->ReadPackage();
  1406. } else if (this->ReadListFile(this->FileFound, DoPolicyScope)) {
  1407. // The package has been found.
  1408. found = true;
  1409. // Check whether the Config file has set Foo_FOUND to FALSE:
  1410. if (this->Makefile->IsDefinitionSet(foundVar) &&
  1411. !this->Makefile->IsOn(foundVar)) {
  1412. // we get here if the Config file has set Foo_FOUND actively to FALSE
  1413. found = false;
  1414. configFileSetFOUNDFalse = true;
  1415. notFoundMessage =
  1416. this->Makefile->GetSafeDefinition(notFoundMessageVar);
  1417. }
  1418. } else {
  1419. // The configuration file is invalid.
  1420. result = false;
  1421. }
  1422. }
  1423. if (this->UseFindModules && !found &&
  1424. handlePackageModeType == HandlePackageModeType::Config &&
  1425. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  1426. // Config mode failed. Allow Module case.
  1427. result = false;
  1428. }
  1429. // package not found
  1430. if (result && !found) {
  1431. // warn if package required or
  1432. // (neither quiet nor in config mode and not explicitly optional)
  1433. if (this->IsRequired() ||
  1434. (!(this->Quiet ||
  1435. (this->UseConfigFiles && !this->UseFindModules &&
  1436. this->ConsideredConfigs.empty())) &&
  1437. this->Required != RequiredStatus::OptionalExplicit)) {
  1438. // The variable is not set.
  1439. std::ostringstream e;
  1440. std::ostringstream aw;
  1441. if (configFileSetFOUNDFalse) {
  1442. e << "Found package configuration file:\n"
  1443. " "
  1444. << this->FileFound
  1445. << "\n"
  1446. "but it set "
  1447. << foundVar << " to FALSE so package \"" << this->Name
  1448. << "\" is considered to be NOT FOUND.";
  1449. if (!notFoundMessage.empty()) {
  1450. e << " Reason given by package: \n" << notFoundMessage << "\n";
  1451. }
  1452. }
  1453. // If there are files in ConsideredConfigs, it means that FooConfig.cmake
  1454. // have been found, but they didn't have appropriate versions.
  1455. else if (!this->ConsideredConfigs.empty()) {
  1456. auto duplicate_end = cmRemoveDuplicates(this->ConsideredConfigs);
  1457. e << "Could not find a configuration file for package \"" << this->Name
  1458. << "\" that "
  1459. << (this->VersionExact ? "exactly matches" : "is compatible with")
  1460. << " requested version "
  1461. << (this->VersionRange.empty() ? "" : "range ") << '"'
  1462. << this->VersionComplete
  1463. << "\".\n"
  1464. "The following configuration files were considered but not "
  1465. "accepted:\n";
  1466. for (ConfigFileInfo const& info :
  1467. cmMakeRange(this->ConsideredConfigs.cbegin(), duplicate_end)) {
  1468. e << " " << info.filename << ", version: " << info.version << '\n';
  1469. }
  1470. } else {
  1471. std::string requestedVersionString;
  1472. if (!this->VersionComplete.empty()) {
  1473. requestedVersionString =
  1474. cmStrCat(" (requested version ", this->VersionComplete, ')');
  1475. }
  1476. if (this->UseConfigFiles) {
  1477. if (this->UseFindModules) {
  1478. e << "By not providing \"Find" << this->Name
  1479. << ".cmake\" in "
  1480. "CMAKE_MODULE_PATH this project has asked CMake to find a "
  1481. "package configuration file provided by \""
  1482. << this->Name
  1483. << "\", "
  1484. "but CMake did not find one.\n";
  1485. }
  1486. if (this->Configs.size() == 1) {
  1487. e << "Could not find a package configuration file named \""
  1488. << this->Configs[0].Name << "\" provided by package \""
  1489. << this->Name << "\"" << requestedVersionString << ".\n";
  1490. } else {
  1491. auto configs = cmMakeRange(this->Configs);
  1492. auto configNames =
  1493. configs.transform([](ConfigName const& cn) { return cn.Name; });
  1494. e << "Could not find a package configuration file provided by \""
  1495. << this->Name << "\"" << requestedVersionString
  1496. << " with any of the following names:\n"
  1497. << cmWrap(" "_s, configNames, ""_s, "\n"_s) << '\n';
  1498. }
  1499. e << "Add the installation prefix of \"" << this->Name
  1500. << "\" to CMAKE_PREFIX_PATH or set \"" << this->Variable
  1501. << "\" to a directory containing one of the above files. "
  1502. "If \""
  1503. << this->Name
  1504. << "\" provides a separate development "
  1505. "package or SDK, be sure it has been installed.";
  1506. } else // if(!this->UseFindModules && !this->UseConfigFiles)
  1507. {
  1508. e << "No \"Find" << this->Name
  1509. << ".cmake\" found in "
  1510. "CMAKE_MODULE_PATH.";
  1511. aw
  1512. << "Find" << this->Name
  1513. << ".cmake must either be part of this "
  1514. "project itself, in this case adjust CMAKE_MODULE_PATH so that "
  1515. "it points to the correct location inside its source tree.\n"
  1516. "Or it must be installed by a package which has already been "
  1517. "found via find_package(). In this case make sure that "
  1518. "package has indeed been found and adjust CMAKE_MODULE_PATH to "
  1519. "contain the location where that package has installed "
  1520. "Find"
  1521. << this->Name
  1522. << ".cmake. This must be a location "
  1523. "provided by that package. This error in general means that "
  1524. "the buildsystem of this project is relying on a Find-module "
  1525. "without ensuring that it is actually available.\n";
  1526. }
  1527. }
  1528. if (this->Required == RequiredStatus::RequiredFromFindVar) {
  1529. e << "\nThis package is considered required because the "
  1530. "CMAKE_FIND_REQUIRED variable has been enabled.\n";
  1531. } else if (this->Required == RequiredStatus::RequiredFromPackageVar) {
  1532. e << "\nThis package is considered required because the "
  1533. << cmStrCat("CMAKE_REQUIRE_FIND_PACKAGE_", this->Name)
  1534. << " variable has been enabled.\n";
  1535. }
  1536. this->Makefile->IssueMessage(
  1537. this->IsRequired() ? MessageType::FATAL_ERROR : MessageType::WARNING,
  1538. e.str());
  1539. if (this->IsRequired()) {
  1540. cmSystemTools::SetFatalErrorOccurred();
  1541. }
  1542. if (!aw.str().empty()) {
  1543. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  1544. }
  1545. }
  1546. // output result if in config mode but not in quiet mode
  1547. else if (!this->Quiet) {
  1548. this->Makefile->DisplayStatus(cmStrCat("Could NOT find ", this->Name,
  1549. " (missing: ", this->Name,
  1550. "_DIR)"),
  1551. -1);
  1552. }
  1553. }
  1554. // Set a variable marking whether the package was found.
  1555. this->Makefile->AddDefinition(foundVar, found ? "1" : "0");
  1556. // Set a variable naming the configuration file that was found.
  1557. std::string const fileVar = cmStrCat(this->Name, "_CONFIG");
  1558. if (found) {
  1559. this->Makefile->AddDefinition(fileVar, this->FileFound);
  1560. } else {
  1561. this->Makefile->RemoveDefinition(fileVar);
  1562. }
  1563. std::string const consideredConfigsVar =
  1564. cmStrCat(this->Name, "_CONSIDERED_CONFIGS");
  1565. std::string const consideredVersionsVar =
  1566. cmStrCat(this->Name, "_CONSIDERED_VERSIONS");
  1567. std::string consideredConfigFiles;
  1568. std::string consideredVersions;
  1569. char const* sep = "";
  1570. for (ConfigFileInfo const& i : this->ConsideredConfigs) {
  1571. consideredConfigFiles += sep;
  1572. consideredVersions += sep;
  1573. consideredConfigFiles += i.filename;
  1574. consideredVersions += i.version;
  1575. sep = ";";
  1576. }
  1577. this->Makefile->AddDefinition(consideredConfigsVar, consideredConfigFiles);
  1578. this->Makefile->AddDefinition(consideredVersionsVar, consideredVersions);
  1579. return result;
  1580. }
  1581. bool cmFindPackageCommand::FindConfig()
  1582. {
  1583. // Compute the set of search prefixes.
  1584. this->ComputePrefixes();
  1585. // Look for the project's configuration file.
  1586. bool found = false;
  1587. if (this->DebugMode) {
  1588. this->DebugBuffer = cmStrCat(this->DebugBuffer,
  1589. "find_package considered the following "
  1590. "locations for ",
  1591. this->Name, "'s Config module:\n");
  1592. }
  1593. if (!found && this->UseCpsFiles) {
  1594. found = this->FindEnvironmentConfig();
  1595. }
  1596. // Search for frameworks.
  1597. if (!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly)) {
  1598. found = this->FindFrameworkConfig();
  1599. }
  1600. // Search for apps.
  1601. if (!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly)) {
  1602. found = this->FindAppBundleConfig();
  1603. }
  1604. // Search prefixes.
  1605. if (!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly)) {
  1606. found = this->FindPrefixedConfig();
  1607. }
  1608. // Search for frameworks.
  1609. if (!found && this->SearchFrameworkLast) {
  1610. found = this->FindFrameworkConfig();
  1611. }
  1612. // Search for apps.
  1613. if (!found && this->SearchAppBundleLast) {
  1614. found = this->FindAppBundleConfig();
  1615. }
  1616. if (this->DebugMode) {
  1617. if (found) {
  1618. this->DebugBuffer = cmStrCat(
  1619. this->DebugBuffer, "The file was found at\n ", this->FileFound, '\n');
  1620. } else {
  1621. this->DebugBuffer =
  1622. cmStrCat(this->DebugBuffer, "The file was not found.\n");
  1623. }
  1624. }
  1625. // Store the entry in the cache so it can be set by the user.
  1626. std::string init;
  1627. if (found) {
  1628. init = cmSystemTools::GetFilenamePath(this->FileFound);
  1629. } else {
  1630. init = this->Variable + "-NOTFOUND";
  1631. }
  1632. // We force the value since we do not get here if it was already set.
  1633. this->SetConfigDirCacheVariable(init);
  1634. return found;
  1635. }
  1636. void cmFindPackageCommand::SetConfigDirCacheVariable(std::string const& value)
  1637. {
  1638. std::string const help =
  1639. cmStrCat("The directory containing a CMake configuration file for ",
  1640. this->Name, '.');
  1641. this->Makefile->AddCacheDefinition(this->Variable, value, help,
  1642. cmStateEnums::PATH, true);
  1643. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0126) ==
  1644. cmPolicies::NEW &&
  1645. this->Makefile->IsNormalDefinitionSet(this->Variable)) {
  1646. this->Makefile->AddDefinition(this->Variable, value);
  1647. }
  1648. }
  1649. bool cmFindPackageCommand::FindPrefixedConfig()
  1650. {
  1651. std::vector<std::string> const& prefixes = this->SearchPaths;
  1652. return std::any_of(
  1653. prefixes.begin(), prefixes.end(),
  1654. [this](std::string const& p) -> bool { return this->SearchPrefix(p); });
  1655. }
  1656. bool cmFindPackageCommand::FindFrameworkConfig()
  1657. {
  1658. std::vector<std::string> const& prefixes = this->SearchPaths;
  1659. return std::any_of(prefixes.begin(), prefixes.end(),
  1660. [this](std::string const& p) -> bool {
  1661. return this->SearchFrameworkPrefix(p);
  1662. });
  1663. }
  1664. bool cmFindPackageCommand::FindAppBundleConfig()
  1665. {
  1666. std::vector<std::string> const& prefixes = this->SearchPaths;
  1667. return std::any_of(prefixes.begin(), prefixes.end(),
  1668. [this](std::string const& p) -> bool {
  1669. return this->SearchAppBundlePrefix(p);
  1670. });
  1671. }
  1672. bool cmFindPackageCommand::FindEnvironmentConfig()
  1673. {
  1674. std::vector<std::string> const& prefixes =
  1675. cmSystemTools::GetEnvPathNormalized("CPS_PATH");
  1676. return std::any_of(prefixes.begin(), prefixes.end(),
  1677. [this](std::string const& p) -> bool {
  1678. return this->SearchEnvironmentPrefix(p);
  1679. });
  1680. }
  1681. cmFindPackageCommand::AppendixMap cmFindPackageCommand::FindAppendices(
  1682. std::string const& base, cmPackageInfoReader const& baseReader) const
  1683. {
  1684. AppendixMap appendices;
  1685. // Find package appendices.
  1686. cmsys::Glob glob;
  1687. glob.RecurseOff();
  1688. if (glob.FindFiles(cmStrCat(cmSystemTools::GetFilenamePath(base), "/"_s,
  1689. cmSystemTools::GetFilenameWithoutExtension(base),
  1690. "[-:]*.[Cc][Pp][Ss]"_s))) {
  1691. // Check glob results for valid appendices.
  1692. for (std::string const& extra : glob.GetFiles()) {
  1693. // Exclude configuration-specific files for now; we look at them later
  1694. // when we load their respective configuration-agnostic appendices.
  1695. if (extra.find('@') != std::string::npos) {
  1696. continue;
  1697. }
  1698. std::unique_ptr<cmPackageInfoReader> reader =
  1699. cmPackageInfoReader::Read(extra, &baseReader);
  1700. if (reader && reader->GetName() == this->Name) {
  1701. std::vector<std::string> components = reader->GetComponentNames();
  1702. Appendix appendix{ std::move(reader), std::move(components) };
  1703. appendices.emplace(extra, std::move(appendix));
  1704. }
  1705. }
  1706. }
  1707. return appendices;
  1708. }
  1709. bool cmFindPackageCommand::ReadListFile(std::string const& f,
  1710. PolicyScopeRule const psr)
  1711. {
  1712. bool const noPolicyScope = !this->PolicyScope || psr == NoPolicyScope;
  1713. using ITScope = cmMakefile::ImportedTargetScope;
  1714. ITScope scope = this->GlobalScope ? ITScope::Global : ITScope::Local;
  1715. cmMakefile::SetGlobalTargetImportScope globScope(this->Makefile, scope);
  1716. if (this->Makefile->ReadDependentFile(f, noPolicyScope)) {
  1717. return true;
  1718. }
  1719. std::string const e = cmStrCat("Error reading CMake code from \"", f, "\".");
  1720. this->SetError(e);
  1721. return false;
  1722. }
  1723. bool cmFindPackageCommand::ReadPackage()
  1724. {
  1725. // Resolve any transitive dependencies for the root file.
  1726. if (!FindPackageDependencies(this->FileFound, *this->CpsReader,
  1727. this->Required)) {
  1728. return false;
  1729. }
  1730. auto const hasComponentsRequested =
  1731. !this->RequiredComponents.empty() || !this->OptionalComponents.empty();
  1732. cmMakefile::CallRAII scope{ this->Makefile, this->FileFound, this->Status };
  1733. // Loop over appendices.
  1734. auto iter = this->CpsAppendices.begin();
  1735. while (iter != this->CpsAppendices.end()) {
  1736. RequiredStatus required = RequiredStatus::Optional;
  1737. bool important = false;
  1738. // Check if this appendix provides any requested components.
  1739. if (hasComponentsRequested) {
  1740. auto providesAny = [&iter](
  1741. std::set<std::string> const& desiredComponents) {
  1742. return std::any_of(iter->second.Components.begin(),
  1743. iter->second.Components.end(),
  1744. [&desiredComponents](std::string const& component) {
  1745. return cm::contains(desiredComponents, component);
  1746. });
  1747. };
  1748. if (providesAny(this->RequiredComponents)) {
  1749. important = true;
  1750. required = this->Required;
  1751. } else if (!providesAny(this->OptionalComponents)) {
  1752. // This appendix doesn't provide any requested components; remove it
  1753. // from the set to be imported.
  1754. iter = this->CpsAppendices.erase(iter);
  1755. continue;
  1756. }
  1757. }
  1758. // Resolve any transitive dependencies for the appendix.
  1759. if (!this->FindPackageDependencies(iter->first, iter->second, required)) {
  1760. if (important) {
  1761. // Some dependencies are missing, and we need(ed) this appendix; fail.
  1762. return false;
  1763. }
  1764. // Some dependencies are missing, but we don't need this appendix; remove
  1765. // it from the set to be imported.
  1766. iter = this->CpsAppendices.erase(iter);
  1767. } else {
  1768. ++iter;
  1769. }
  1770. }
  1771. // Import targets from root file.
  1772. if (!this->ImportPackageTargets(this->FileFound, *this->CpsReader)) {
  1773. return false;
  1774. }
  1775. // Import targets from appendices.
  1776. // NOLINTNEXTLINE(readability-use-anyofallof)
  1777. for (auto const& appendix : this->CpsAppendices) {
  1778. cmMakefile::CallRAII appendixScope{ this->Makefile, appendix.first,
  1779. this->Status };
  1780. if (!this->ImportPackageTargets(appendix.first, appendix.second)) {
  1781. return false;
  1782. }
  1783. }
  1784. return true;
  1785. }
  1786. bool cmFindPackageCommand::FindPackageDependencies(
  1787. std::string const& fileName, cmPackageInfoReader const& reader,
  1788. RequiredStatus required)
  1789. {
  1790. // Get package requirements.
  1791. for (cmPackageRequirement const& dep : reader.GetRequirements()) {
  1792. cmExecutionStatus status{ *this->Makefile };
  1793. cmMakefile::CallRAII scope{ this->Makefile, fileName, status };
  1794. // For each requirement, set up a nested instance to find it.
  1795. cmFindPackageCommand fp{ status };
  1796. fp.InheritOptions(this);
  1797. fp.Name = dep.Name;
  1798. fp.Required = required;
  1799. fp.UseFindModules = false;
  1800. fp.UseCpsFiles = true;
  1801. fp.Version = dep.Version;
  1802. fp.VersionComplete = dep.Version;
  1803. fp.VersionCount =
  1804. parseVersion(fp.Version, fp.VersionMajor, fp.VersionMinor,
  1805. fp.VersionPatch, fp.VersionTweak);
  1806. fp.Components = cmJoin(cmMakeRange(dep.Components), ";"_s);
  1807. fp.RequiredComponents =
  1808. std::set<std::string>{ dep.Components.begin(), dep.Components.end() };
  1809. // TODO set hints
  1810. // Try to find the requirement; fail if we can't.
  1811. if (!fp.FindPackage() || fp.FileFound.empty()) {
  1812. this->SetError(cmStrCat("could not find "_s, dep.Name,
  1813. ", required by "_s, this->Name, '.'));
  1814. return false;
  1815. }
  1816. }
  1817. // All requirements (if any) were found.
  1818. return true;
  1819. }
  1820. bool cmFindPackageCommand::ImportPackageTargets(std::string const& fileName,
  1821. cmPackageInfoReader& reader)
  1822. {
  1823. // Import base file.
  1824. if (!reader.ImportTargets(this->Makefile, this->Status)) {
  1825. return false;
  1826. }
  1827. // Find supplemental configuration files.
  1828. cmsys::Glob glob;
  1829. glob.RecurseOff();
  1830. if (glob.FindFiles(
  1831. cmStrCat(cmSystemTools::GetFilenamePath(fileName), '/',
  1832. cmSystemTools::GetFilenameWithoutExtension(fileName),
  1833. "@*.[Cc][Pp][Ss]"_s))) {
  1834. // Try to read supplemental data from each file found.
  1835. for (std::string const& extra : glob.GetFiles()) {
  1836. std::unique_ptr<cmPackageInfoReader> configReader =
  1837. cmPackageInfoReader::Read(extra, &reader);
  1838. if (configReader && configReader->GetName() == this->Name) {
  1839. if (!configReader->ImportTargetConfigurations(this->Makefile,
  1840. this->Status)) {
  1841. return false;
  1842. }
  1843. }
  1844. }
  1845. }
  1846. return true;
  1847. }
  1848. void cmFindPackageCommand::AppendToFoundProperty(bool const found)
  1849. {
  1850. cmList foundContents;
  1851. cmValue foundProp =
  1852. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_FOUND");
  1853. if (!foundProp.IsEmpty()) {
  1854. foundContents.assign(*foundProp);
  1855. foundContents.remove_items({ this->Name });
  1856. }
  1857. cmList notFoundContents;
  1858. cmValue notFoundProp =
  1859. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_NOT_FOUND");
  1860. if (!notFoundProp.IsEmpty()) {
  1861. notFoundContents.assign(*notFoundProp);
  1862. notFoundContents.remove_items({ this->Name });
  1863. }
  1864. if (found) {
  1865. foundContents.push_back(this->Name);
  1866. } else {
  1867. notFoundContents.push_back(this->Name);
  1868. }
  1869. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_FOUND",
  1870. foundContents.to_string());
  1871. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_NOT_FOUND",
  1872. notFoundContents.to_string());
  1873. }
  1874. void cmFindPackageCommand::AppendSuccessInformation()
  1875. {
  1876. {
  1877. std::string const transitivePropName =
  1878. cmStrCat("_CMAKE_", this->Name, "_TRANSITIVE_DEPENDENCY");
  1879. this->Makefile->GetState()->SetGlobalProperty(transitivePropName, "False");
  1880. }
  1881. std::string const found = cmStrCat(this->Name, "_FOUND");
  1882. std::string const upperFound = cmSystemTools::UpperCase(found);
  1883. bool const upperResult = this->Makefile->IsOn(upperFound);
  1884. bool const result = this->Makefile->IsOn(found);
  1885. bool const packageFound = (result || upperResult);
  1886. this->AppendToFoundProperty(packageFound);
  1887. // Record whether the find was quiet or not, so this can be used
  1888. // e.g. in FeatureSummary.cmake
  1889. std::string const quietInfoPropName =
  1890. cmStrCat("_CMAKE_", this->Name, "_QUIET");
  1891. this->Makefile->GetState()->SetGlobalProperty(
  1892. quietInfoPropName, this->Quiet ? "TRUE" : "FALSE");
  1893. // set a global property to record the required version of this package
  1894. std::string const versionInfoPropName =
  1895. cmStrCat("_CMAKE_", this->Name, "_REQUIRED_VERSION");
  1896. std::string versionInfo;
  1897. if (!this->VersionRange.empty()) {
  1898. versionInfo = this->VersionRange;
  1899. } else if (!this->Version.empty()) {
  1900. versionInfo =
  1901. cmStrCat(this->VersionExact ? "==" : ">=", ' ', this->Version);
  1902. }
  1903. this->Makefile->GetState()->SetGlobalProperty(versionInfoPropName,
  1904. versionInfo);
  1905. if (this->IsRequired()) {
  1906. std::string const requiredInfoPropName =
  1907. cmStrCat("_CMAKE_", this->Name, "_TYPE");
  1908. this->Makefile->GetState()->SetGlobalProperty(requiredInfoPropName,
  1909. "REQUIRED");
  1910. }
  1911. }
  1912. void cmFindPackageCommand::PushFindPackageRootPathStack()
  1913. {
  1914. // Allocate a PACKAGE_ROOT_PATH for the current find_package call.
  1915. this->Makefile->FindPackageRootPathStack.emplace_back();
  1916. std::vector<std::string>& rootPaths =
  1917. this->Makefile->FindPackageRootPathStack.back();
  1918. // Add root paths from <PackageName>_ROOT CMake and environment variables,
  1919. // subject to CMP0074.
  1920. std::string const rootVar = this->Name + "_ROOT";
  1921. cmValue rootDef = this->Makefile->GetDefinition(rootVar);
  1922. if (rootDef && rootDef.IsEmpty()) {
  1923. rootDef = nullptr;
  1924. }
  1925. cm::optional<std::string> rootEnv = cmSystemTools::GetEnvVar(rootVar);
  1926. if (rootEnv && rootEnv->empty()) {
  1927. rootEnv = cm::nullopt;
  1928. }
  1929. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0074)) {
  1930. case cmPolicies::WARN:
  1931. this->Makefile->MaybeWarnCMP0074(rootVar, rootDef, rootEnv);
  1932. CM_FALLTHROUGH;
  1933. case cmPolicies::OLD:
  1934. // OLD behavior is to ignore the <PackageName>_ROOT variables.
  1935. return;
  1936. case cmPolicies::NEW: {
  1937. // NEW behavior is to honor the <PackageName>_ROOT variables.
  1938. } break;
  1939. }
  1940. // Add root paths from <PACKAGENAME>_ROOT CMake and environment variables,
  1941. // if they are different than <PackageName>_ROOT, and subject to CMP0144.
  1942. std::string const rootVAR = cmSystemTools::UpperCase(rootVar);
  1943. cmValue rootDEF;
  1944. cm::optional<std::string> rootENV;
  1945. if (rootVAR != rootVar) {
  1946. rootDEF = this->Makefile->GetDefinition(rootVAR);
  1947. if (rootDEF && (rootDEF.IsEmpty() || rootDEF == rootDef)) {
  1948. rootDEF = nullptr;
  1949. }
  1950. rootENV = cmSystemTools::GetEnvVar(rootVAR);
  1951. if (rootENV && (rootENV->empty() || rootENV == rootEnv)) {
  1952. rootENV = cm::nullopt;
  1953. }
  1954. }
  1955. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0144)) {
  1956. case cmPolicies::WARN:
  1957. this->Makefile->MaybeWarnCMP0144(rootVAR, rootDEF, rootENV);
  1958. CM_FALLTHROUGH;
  1959. case cmPolicies::OLD:
  1960. // OLD behavior is to ignore the <PACKAGENAME>_ROOT variables.
  1961. rootDEF = nullptr;
  1962. rootENV = cm::nullopt;
  1963. break;
  1964. case cmPolicies::NEW: {
  1965. // NEW behavior is to honor the <PACKAGENAME>_ROOT variables.
  1966. } break;
  1967. }
  1968. if (rootDef) {
  1969. cmExpandList(*rootDef, rootPaths);
  1970. }
  1971. if (rootDEF) {
  1972. cmExpandList(*rootDEF, rootPaths);
  1973. }
  1974. if (rootEnv) {
  1975. std::vector<std::string> p =
  1976. cmSystemTools::SplitEnvPathNormalized(*rootEnv);
  1977. std::move(p.begin(), p.end(), std::back_inserter(rootPaths));
  1978. }
  1979. if (rootENV) {
  1980. std::vector<std::string> p =
  1981. cmSystemTools::SplitEnvPathNormalized(*rootENV);
  1982. std::move(p.begin(), p.end(), std::back_inserter(rootPaths));
  1983. }
  1984. }
  1985. void cmFindPackageCommand::PopFindPackageRootPathStack()
  1986. {
  1987. this->Makefile->FindPackageRootPathStack.pop_back();
  1988. }
  1989. void cmFindPackageCommand::ComputePrefixes()
  1990. {
  1991. this->FillPrefixesPackageRedirect();
  1992. if (!this->NoDefaultPath) {
  1993. if (!this->NoPackageRootPath) {
  1994. this->FillPrefixesPackageRoot();
  1995. }
  1996. if (!this->NoCMakePath) {
  1997. this->FillPrefixesCMakeVariable();
  1998. }
  1999. if (!this->NoCMakeEnvironmentPath) {
  2000. this->FillPrefixesCMakeEnvironment();
  2001. }
  2002. }
  2003. this->FillPrefixesUserHints();
  2004. if (!this->NoDefaultPath) {
  2005. if (!this->NoSystemEnvironmentPath) {
  2006. this->FillPrefixesSystemEnvironment();
  2007. }
  2008. if (!this->NoUserRegistry) {
  2009. this->FillPrefixesUserRegistry();
  2010. }
  2011. if (!this->NoCMakeSystemPath) {
  2012. this->FillPrefixesCMakeSystemVariable();
  2013. }
  2014. if (!this->NoSystemRegistry) {
  2015. this->FillPrefixesSystemRegistry();
  2016. }
  2017. }
  2018. this->FillPrefixesUserGuess();
  2019. this->ComputeFinalPaths(IgnorePaths::No, &this->DebugBuffer);
  2020. }
  2021. void cmFindPackageCommand::FillPrefixesPackageRedirect()
  2022. {
  2023. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRedirect];
  2024. auto const redirectDir =
  2025. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_REDIRECTS_DIR");
  2026. if (redirectDir && !redirectDir->empty()) {
  2027. paths.AddPath(*redirectDir);
  2028. }
  2029. if (this->DebugMode) {
  2030. std::string debugBuffer =
  2031. "The internally managed CMAKE_FIND_PACKAGE_REDIRECTS_DIR.\n";
  2032. collectPathsForDebug(debugBuffer, paths);
  2033. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2034. }
  2035. }
  2036. void cmFindPackageCommand::FillPrefixesPackageRoot()
  2037. {
  2038. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot];
  2039. // Add the PACKAGE_ROOT_PATH from each enclosing find_package call.
  2040. for (auto pkgPaths = this->Makefile->FindPackageRootPathStack.rbegin();
  2041. pkgPaths != this->Makefile->FindPackageRootPathStack.rend();
  2042. ++pkgPaths) {
  2043. for (std::string const& path : *pkgPaths) {
  2044. paths.AddPath(path);
  2045. }
  2046. }
  2047. if (this->DebugMode) {
  2048. std::string debugBuffer = "<PackageName>_ROOT CMake variable "
  2049. "[CMAKE_FIND_USE_PACKAGE_ROOT_PATH].\n";
  2050. collectPathsForDebug(debugBuffer, paths);
  2051. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2052. }
  2053. }
  2054. void cmFindPackageCommand::FillPrefixesCMakeEnvironment()
  2055. {
  2056. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeEnvironment];
  2057. std::string debugBuffer;
  2058. std::size_t debugOffset = 0;
  2059. // Check the environment variable with the same name as the cache
  2060. // entry.
  2061. paths.AddEnvPath(this->Variable);
  2062. if (this->DebugMode) {
  2063. debugBuffer = cmStrCat("Env variable ", this->Variable,
  2064. " [CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
  2065. debugOffset = collectPathsForDebug(debugBuffer, paths);
  2066. }
  2067. // And now the general CMake environment variables
  2068. paths.AddEnvPath("CMAKE_PREFIX_PATH");
  2069. if (this->DebugMode) {
  2070. debugBuffer = cmStrCat(debugBuffer,
  2071. "CMAKE_PREFIX_PATH env variable "
  2072. "[CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
  2073. debugOffset = collectPathsForDebug(debugBuffer, paths, debugOffset);
  2074. }
  2075. paths.AddEnvPath("CMAKE_FRAMEWORK_PATH");
  2076. paths.AddEnvPath("CMAKE_APPBUNDLE_PATH");
  2077. if (this->DebugMode) {
  2078. debugBuffer =
  2079. cmStrCat(debugBuffer,
  2080. "CMAKE_FRAMEWORK_PATH and CMAKE_APPBUNDLE_PATH env "
  2081. "variables [CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
  2082. collectPathsForDebug(debugBuffer, paths, debugOffset);
  2083. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2084. }
  2085. }
  2086. void cmFindPackageCommand::FillPrefixesCMakeVariable()
  2087. {
  2088. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMake];
  2089. std::string debugBuffer;
  2090. std::size_t debugOffset = 0;
  2091. paths.AddCMakePath("CMAKE_PREFIX_PATH");
  2092. if (this->DebugMode) {
  2093. debugBuffer = "CMAKE_PREFIX_PATH variable [CMAKE_FIND_USE_CMAKE_PATH].\n";
  2094. debugOffset = collectPathsForDebug(debugBuffer, paths);
  2095. }
  2096. paths.AddCMakePath("CMAKE_FRAMEWORK_PATH");
  2097. paths.AddCMakePath("CMAKE_APPBUNDLE_PATH");
  2098. if (this->DebugMode) {
  2099. debugBuffer =
  2100. cmStrCat(debugBuffer,
  2101. "CMAKE_FRAMEWORK_PATH and CMAKE_APPBUNDLE_PATH variables "
  2102. "[CMAKE_FIND_USE_CMAKE_PATH].\n");
  2103. collectPathsForDebug(debugBuffer, paths, debugOffset);
  2104. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2105. }
  2106. }
  2107. void cmFindPackageCommand::FillPrefixesSystemEnvironment()
  2108. {
  2109. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemEnvironment];
  2110. // Use the system search path to generate prefixes.
  2111. // Relative paths are interpreted with respect to the current
  2112. // working directory.
  2113. std::vector<std::string> envPATH =
  2114. cmSystemTools::GetEnvPathNormalized("PATH");
  2115. for (std::string const& i : envPATH) {
  2116. // If the path is a PREFIX/bin case then add its parent instead.
  2117. if ((cmHasLiteralSuffix(i, "/bin")) || (cmHasLiteralSuffix(i, "/sbin"))) {
  2118. paths.AddPath(cmSystemTools::GetFilenamePath(i));
  2119. } else {
  2120. paths.AddPath(i);
  2121. }
  2122. }
  2123. if (this->DebugMode) {
  2124. std::string debugBuffer = "Standard system environment variables "
  2125. "[CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH].\n";
  2126. collectPathsForDebug(debugBuffer, paths);
  2127. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2128. }
  2129. }
  2130. void cmFindPackageCommand::FillPrefixesUserRegistry()
  2131. {
  2132. #if defined(_WIN32) && !defined(__CYGWIN__)
  2133. this->LoadPackageRegistryWinUser();
  2134. #elif defined(__HAIKU__)
  2135. char dir[B_PATH_NAME_LENGTH];
  2136. if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  2137. B_OK) {
  2138. std::string fname = cmStrCat(dir, "/cmake/packages/", Name);
  2139. this->LoadPackageRegistryDir(fname,
  2140. this->LabeledPaths[PathLabel::UserRegistry]);
  2141. }
  2142. #else
  2143. std::string dir;
  2144. if (cmSystemTools::GetEnv("HOME", dir)) {
  2145. dir += "/.cmake/packages/";
  2146. dir += this->Name;
  2147. this->LoadPackageRegistryDir(dir,
  2148. this->LabeledPaths[PathLabel::UserRegistry]);
  2149. }
  2150. #endif
  2151. if (this->DebugMode) {
  2152. std::string debugBuffer =
  2153. "CMake User Package Registry [CMAKE_FIND_USE_PACKAGE_REGISTRY].\n";
  2154. collectPathsForDebug(debugBuffer,
  2155. this->LabeledPaths[PathLabel::UserRegistry]);
  2156. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2157. }
  2158. }
  2159. void cmFindPackageCommand::FillPrefixesSystemRegistry()
  2160. {
  2161. if (this->NoSystemRegistry || this->NoDefaultPath) {
  2162. return;
  2163. }
  2164. #if defined(_WIN32) && !defined(__CYGWIN__)
  2165. this->LoadPackageRegistryWinSystem();
  2166. #endif
  2167. if (this->DebugMode) {
  2168. std::string debugBuffer =
  2169. "CMake System Package Registry "
  2170. "[CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY].\n";
  2171. collectPathsForDebug(debugBuffer,
  2172. this->LabeledPaths[PathLabel::SystemRegistry]);
  2173. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2174. }
  2175. }
  2176. #if defined(_WIN32) && !defined(__CYGWIN__)
  2177. void cmFindPackageCommand::LoadPackageRegistryWinUser()
  2178. {
  2179. // HKEY_CURRENT_USER\\Software shares 32-bit and 64-bit views.
  2180. this->LoadPackageRegistryWin(true, 0,
  2181. this->LabeledPaths[PathLabel::UserRegistry]);
  2182. }
  2183. void cmFindPackageCommand::LoadPackageRegistryWinSystem()
  2184. {
  2185. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemRegistry];
  2186. // HKEY_LOCAL_MACHINE\\SOFTWARE has separate 32-bit and 64-bit views.
  2187. // Prefer the target platform view first.
  2188. if (this->Makefile->PlatformIs64Bit()) {
  2189. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  2190. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  2191. } else {
  2192. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  2193. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  2194. }
  2195. }
  2196. void cmFindPackageCommand::LoadPackageRegistryWin(bool const user,
  2197. unsigned int const view,
  2198. cmSearchPath& outPaths)
  2199. {
  2200. std::wstring key = L"Software\\Kitware\\CMake\\Packages\\";
  2201. key += cmsys::Encoding::ToWide(this->Name);
  2202. std::set<std::wstring> bad;
  2203. HKEY hKey;
  2204. if (RegOpenKeyExW(user ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, key.c_str(),
  2205. 0, KEY_QUERY_VALUE | view, &hKey) == ERROR_SUCCESS) {
  2206. DWORD valueType = REG_NONE;
  2207. wchar_t name[16383]; // RegEnumValue docs limit name to 32767 _bytes_
  2208. std::vector<wchar_t> data(512);
  2209. bool done = false;
  2210. DWORD index = 0;
  2211. while (!done) {
  2212. DWORD nameSize = static_cast<DWORD>(sizeof(name));
  2213. DWORD dataSize = static_cast<DWORD>(data.size() * sizeof(data[0]));
  2214. switch (RegEnumValueW(hKey, index, name, &nameSize, 0, &valueType,
  2215. (BYTE*)&data[0], &dataSize)) {
  2216. case ERROR_SUCCESS:
  2217. ++index;
  2218. if (valueType == REG_SZ) {
  2219. data[dataSize] = 0;
  2220. if (!this->CheckPackageRegistryEntry(
  2221. cmsys::Encoding::ToNarrow(&data[0]), outPaths)) {
  2222. // The entry is invalid.
  2223. bad.insert(name);
  2224. }
  2225. }
  2226. break;
  2227. case ERROR_MORE_DATA:
  2228. data.resize((dataSize + sizeof(data[0]) - 1) / sizeof(data[0]));
  2229. break;
  2230. case ERROR_NO_MORE_ITEMS:
  2231. default:
  2232. done = true;
  2233. break;
  2234. }
  2235. }
  2236. RegCloseKey(hKey);
  2237. }
  2238. // Remove bad values if possible.
  2239. if (user && !bad.empty() &&
  2240. RegOpenKeyExW(HKEY_CURRENT_USER, key.c_str(), 0, KEY_SET_VALUE | view,
  2241. &hKey) == ERROR_SUCCESS) {
  2242. for (std::wstring const& v : bad) {
  2243. RegDeleteValueW(hKey, v.c_str());
  2244. }
  2245. RegCloseKey(hKey);
  2246. }
  2247. }
  2248. #else
  2249. void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir,
  2250. cmSearchPath& outPaths)
  2251. {
  2252. cmsys::Directory files;
  2253. if (!files.Load(dir)) {
  2254. return;
  2255. }
  2256. std::string fname;
  2257. for (unsigned long i = 0; i < files.GetNumberOfFiles(); ++i) {
  2258. fname = cmStrCat(dir, '/', files.GetFile(i));
  2259. if (!cmSystemTools::FileIsDirectory(fname)) {
  2260. // Hold this file hostage until it behaves.
  2261. cmFindPackageCommandHoldFile holdFile(fname.c_str());
  2262. // Load the file.
  2263. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  2264. std::string fentry;
  2265. if (fin && cmSystemTools::GetLineFromStream(fin, fentry) &&
  2266. this->CheckPackageRegistryEntry(fentry, outPaths)) {
  2267. // The file references an existing package, so release it.
  2268. holdFile.Release();
  2269. }
  2270. }
  2271. }
  2272. // TODO: Wipe out the directory if it is empty.
  2273. }
  2274. #endif
  2275. bool cmFindPackageCommand::CheckPackageRegistryEntry(std::string const& fname,
  2276. cmSearchPath& outPaths)
  2277. {
  2278. // Parse the content of one package registry entry.
  2279. if (cmSystemTools::FileIsFullPath(fname)) {
  2280. // The first line in the stream is the full path to a file or
  2281. // directory containing the package.
  2282. if (cmSystemTools::FileExists(fname)) {
  2283. // The path exists. Look for the package here.
  2284. if (!cmSystemTools::FileIsDirectory(fname)) {
  2285. outPaths.AddPath(cmSystemTools::GetFilenamePath(fname));
  2286. } else {
  2287. outPaths.AddPath(fname);
  2288. }
  2289. return true;
  2290. }
  2291. // The path does not exist. Assume the stream content is
  2292. // associated with an old package that no longer exists, and
  2293. // delete it to keep the package registry clean.
  2294. return false;
  2295. }
  2296. // The first line in the stream is not the full path to a file or
  2297. // directory. Assume the stream content was created by a future
  2298. // version of CMake that uses a different format, and leave it.
  2299. return true;
  2300. }
  2301. void cmFindPackageCommand::FillPrefixesCMakeSystemVariable()
  2302. {
  2303. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeSystem];
  2304. bool const install_prefix_in_list =
  2305. !this->Makefile->IsOn("CMAKE_FIND_NO_INSTALL_PREFIX");
  2306. bool const remove_install_prefix = this->NoCMakeInstallPath;
  2307. bool const add_install_prefix = !this->NoCMakeInstallPath &&
  2308. this->Makefile->IsDefinitionSet("CMAKE_FIND_USE_INSTALL_PREFIX");
  2309. // We have 3 possible states for `CMAKE_SYSTEM_PREFIX_PATH` and
  2310. // `CMAKE_INSTALL_PREFIX`.
  2311. // Either we need to remove `CMAKE_INSTALL_PREFIX`, add
  2312. // `CMAKE_INSTALL_PREFIX`, or do nothing.
  2313. //
  2314. // When we need to remove `CMAKE_INSTALL_PREFIX` we remove the Nth occurrence
  2315. // of `CMAKE_INSTALL_PREFIX` from `CMAKE_SYSTEM_PREFIX_PATH`, where `N` is
  2316. // computed by `CMakeSystemSpecificInformation.cmake` while constructing
  2317. // `CMAKE_SYSTEM_PREFIX_PATH`. This ensures that if projects / toolchains
  2318. // have removed `CMAKE_INSTALL_PREFIX` from the list, we don't remove
  2319. // some other entry by mistake
  2320. long install_prefix_count = -1;
  2321. std::string install_path_to_remove;
  2322. if (cmValue to_skip = this->Makefile->GetDefinition(
  2323. "_CMAKE_SYSTEM_PREFIX_PATH_INSTALL_PREFIX_COUNT")) {
  2324. cmStrToLong(*to_skip, &install_prefix_count);
  2325. }
  2326. if (cmValue install_value = this->Makefile->GetDefinition(
  2327. "_CMAKE_SYSTEM_PREFIX_PATH_INSTALL_PREFIX_VALUE")) {
  2328. install_path_to_remove = *install_value;
  2329. }
  2330. if (remove_install_prefix && install_prefix_in_list &&
  2331. install_prefix_count > 0 && !install_path_to_remove.empty()) {
  2332. cmValue prefix_paths =
  2333. this->Makefile->GetDefinition("CMAKE_SYSTEM_PREFIX_PATH");
  2334. // remove entry from CMAKE_SYSTEM_PREFIX_PATH
  2335. cmList expanded{ *prefix_paths };
  2336. long count = 0;
  2337. for (auto const& path : expanded) {
  2338. bool const to_add =
  2339. !(path == install_path_to_remove && ++count == install_prefix_count);
  2340. if (to_add) {
  2341. paths.AddPath(path);
  2342. }
  2343. }
  2344. } else if (add_install_prefix && !install_prefix_in_list) {
  2345. paths.AddCMakePath("CMAKE_INSTALL_PREFIX");
  2346. paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
  2347. } else {
  2348. // Otherwise the current setup of `CMAKE_SYSTEM_PREFIX_PATH` is correct
  2349. paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
  2350. }
  2351. paths.AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
  2352. paths.AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
  2353. if (this->DebugMode) {
  2354. std::string debugBuffer = "CMake variables defined in the Platform file "
  2355. "[CMAKE_FIND_USE_CMAKE_SYSTEM_PATH].\n";
  2356. collectPathsForDebug(debugBuffer, paths);
  2357. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2358. }
  2359. }
  2360. void cmFindPackageCommand::FillPrefixesUserGuess()
  2361. {
  2362. cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
  2363. for (std::string const& p : this->UserGuessArgs) {
  2364. paths.AddUserPath(p);
  2365. }
  2366. if (this->DebugMode) {
  2367. std::string debugBuffer =
  2368. "Paths specified by the find_package PATHS option.\n";
  2369. collectPathsForDebug(debugBuffer, paths);
  2370. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2371. }
  2372. }
  2373. void cmFindPackageCommand::FillPrefixesUserHints()
  2374. {
  2375. cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
  2376. for (std::string const& p : this->UserHintsArgs) {
  2377. paths.AddUserPath(p);
  2378. }
  2379. if (this->DebugMode) {
  2380. std::string debugBuffer =
  2381. "Paths specified by the find_package HINTS option.\n";
  2382. collectPathsForDebug(debugBuffer, paths);
  2383. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2384. }
  2385. }
  2386. bool cmFindPackageCommand::SearchDirectory(std::string const& dir,
  2387. PackageDescriptionType type)
  2388. {
  2389. assert(!dir.empty() && dir.back() == '/');
  2390. // Check each path suffix on this directory.
  2391. for (std::string const& s : this->SearchPathSuffixes) {
  2392. std::string d = dir;
  2393. if (!s.empty()) {
  2394. d += s;
  2395. d += '/';
  2396. }
  2397. if (this->CheckDirectory(d, type)) {
  2398. return true;
  2399. }
  2400. }
  2401. return false;
  2402. }
  2403. bool cmFindPackageCommand::CheckDirectory(std::string const& dir,
  2404. PackageDescriptionType type)
  2405. {
  2406. assert(!dir.empty() && dir.back() == '/');
  2407. std::string const d = dir.substr(0, dir.size() - 1);
  2408. if (cm::contains(this->IgnoredPaths, d)) {
  2409. return false;
  2410. }
  2411. // Look for the file in this directory.
  2412. std::string file;
  2413. if (this->FindConfigFile(d, type, file)) {
  2414. this->FileFound = std::move(file);
  2415. return true;
  2416. }
  2417. return false;
  2418. }
  2419. bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
  2420. PackageDescriptionType type,
  2421. std::string& file)
  2422. {
  2423. for (auto const& config : this->Configs) {
  2424. if (type != pdt::Any && config.Type != type) {
  2425. continue;
  2426. }
  2427. file = cmStrCat(dir, '/', config.Name);
  2428. if (this->DebugMode) {
  2429. this->DebugBuffer = cmStrCat(this->DebugBuffer, " ", file, '\n');
  2430. }
  2431. if (cmSystemTools::FileExists(file, true) && this->CheckVersion(file)) {
  2432. // Allow resolving symlinks when the config file is found through a link
  2433. if (this->UseRealPath) {
  2434. file = cmSystemTools::GetRealPath(file);
  2435. } else {
  2436. file = cmSystemTools::ToNormalizedPathOnDisk(file);
  2437. }
  2438. return true;
  2439. }
  2440. }
  2441. return false;
  2442. }
  2443. bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
  2444. {
  2445. bool result = false; // by default, assume the version is not ok.
  2446. bool haveResult = false;
  2447. std::string version = "unknown";
  2448. // Get the file extension.
  2449. std::string::size_type pos = config_file.rfind('.');
  2450. std::string ext = cmSystemTools::LowerCase(config_file.substr(pos));
  2451. if (ext == ".cps"_s) {
  2452. std::unique_ptr<cmPackageInfoReader> reader =
  2453. cmPackageInfoReader::Read(config_file);
  2454. if (reader && reader->GetName() == this->Name) {
  2455. // Read version information.
  2456. cm::optional<std::string> cpsVersion = reader->GetVersion();
  2457. cm::optional<ParsedVersion> const& parsedVersion =
  2458. reader->ParseVersion(cpsVersion);
  2459. bool const hasVersion = cpsVersion.has_value();
  2460. // Test for version compatibility.
  2461. result = this->Version.empty();
  2462. if (hasVersion) {
  2463. version = std::move(*cpsVersion);
  2464. if (!this->Version.empty()) {
  2465. if (!parsedVersion) {
  2466. // If we don't understand the version, compare the exact versions
  2467. // using full string comparison. This is the correct behavior for
  2468. // the "custom" schema, and the best we can do otherwise.
  2469. result = (this->Version == version);
  2470. } else if (this->VersionExact) {
  2471. // If EXACT is specified, the version must be exactly the requested
  2472. // version.
  2473. result =
  2474. cmSystemTools::VersionCompareEqual(this->Version, version);
  2475. } else {
  2476. // Do we have a compat_version?
  2477. cm::optional<std::string> const& compatVersion =
  2478. reader->GetCompatVersion();
  2479. if (reader->ParseVersion(compatVersion)) {
  2480. // If yes, the initial result is whether the requested version is
  2481. // between the actual version and the compat version, inclusive.
  2482. result = cmSystemTools::VersionCompareGreaterEq(version,
  2483. this->Version) &&
  2484. cmSystemTools::VersionCompareGreaterEq(this->Version,
  2485. *compatVersion);
  2486. if (result && !this->VersionMax.empty()) {
  2487. // We must also check that the version is less than the version
  2488. // limit.
  2489. if (this->VersionRangeMax == VERSION_ENDPOINT_EXCLUDED) {
  2490. result = cmSystemTools::VersionCompareGreater(
  2491. this->VersionMax, version);
  2492. } else {
  2493. result = cmSystemTools::VersionCompareGreaterEq(
  2494. this->VersionMax, version);
  2495. }
  2496. }
  2497. } else {
  2498. // If no, compat_version is assumed to be exactly the actual
  2499. // version, so the result is whether the requested version is
  2500. // exactly the actual version, and we can ignore the version
  2501. // limit.
  2502. result =
  2503. cmSystemTools::VersionCompareEqual(this->Version, version);
  2504. }
  2505. }
  2506. }
  2507. }
  2508. if (result) {
  2509. // Locate appendices.
  2510. cmFindPackageCommand::AppendixMap appendices =
  2511. this->FindAppendices(config_file, *reader);
  2512. // Collect available components.
  2513. std::set<std::string> allComponents;
  2514. std::vector<std::string> const& rootComponents =
  2515. reader->GetComponentNames();
  2516. allComponents.insert(rootComponents.begin(), rootComponents.end());
  2517. for (auto const& appendix : appendices) {
  2518. allComponents.insert(appendix.second.Components.begin(),
  2519. appendix.second.Components.end());
  2520. }
  2521. // Verify that all required components are available.
  2522. std::vector<std::string> missingComponents;
  2523. std::set_difference(this->RequiredComponents.begin(),
  2524. this->RequiredComponents.end(),
  2525. allComponents.begin(), allComponents.end(),
  2526. std::back_inserter(missingComponents));
  2527. if (!missingComponents.empty()) {
  2528. result = false;
  2529. }
  2530. if (result && hasVersion) {
  2531. this->VersionFound = version;
  2532. if (parsedVersion) {
  2533. std::vector<unsigned> const& versionParts =
  2534. parsedVersion->ReleaseComponents;
  2535. this->VersionFoundCount =
  2536. static_cast<unsigned>(versionParts.size());
  2537. switch (std::min(this->VersionFoundCount, 4u)) {
  2538. case 4:
  2539. this->VersionFoundTweak = versionParts[3];
  2540. CM_FALLTHROUGH;
  2541. case 3:
  2542. this->VersionFoundPatch = versionParts[2];
  2543. CM_FALLTHROUGH;
  2544. case 2:
  2545. this->VersionFoundMinor = versionParts[1];
  2546. CM_FALLTHROUGH;
  2547. case 1:
  2548. this->VersionFoundMajor = versionParts[0];
  2549. CM_FALLTHROUGH;
  2550. default:
  2551. break;
  2552. }
  2553. } else {
  2554. this->VersionFoundCount = 0;
  2555. }
  2556. }
  2557. this->CpsReader = std::move(reader);
  2558. this->CpsAppendices = std::move(appendices);
  2559. }
  2560. }
  2561. } else {
  2562. // Get the filename without the .cmake extension.
  2563. std::string version_file_base = config_file.substr(0, pos);
  2564. // Look for foo-config-version.cmake
  2565. std::string version_file = cmStrCat(version_file_base, "-version.cmake");
  2566. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  2567. result = this->CheckVersionFile(version_file, version);
  2568. haveResult = true;
  2569. }
  2570. // Look for fooConfigVersion.cmake
  2571. version_file = cmStrCat(version_file_base, "Version.cmake");
  2572. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  2573. result = this->CheckVersionFile(version_file, version);
  2574. haveResult = true;
  2575. }
  2576. // If no version was requested a versionless package is acceptable.
  2577. if (!haveResult && this->Version.empty()) {
  2578. result = true;
  2579. }
  2580. }
  2581. ConfigFileInfo configFileInfo;
  2582. configFileInfo.filename = config_file;
  2583. configFileInfo.version = version;
  2584. this->ConsideredConfigs.push_back(std::move(configFileInfo));
  2585. return result;
  2586. }
  2587. bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file,
  2588. std::string& result_version)
  2589. {
  2590. // The version file will be loaded in an isolated scope.
  2591. cmMakefile::ScopePushPop const varScope(this->Makefile);
  2592. cmMakefile::PolicyPushPop const polScope(this->Makefile);
  2593. static_cast<void>(varScope);
  2594. static_cast<void>(polScope);
  2595. // Clear the output variables.
  2596. this->Makefile->RemoveDefinition("PACKAGE_VERSION");
  2597. this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
  2598. this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
  2599. this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
  2600. // Set the input variables.
  2601. this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name);
  2602. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COMPLETE",
  2603. this->VersionComplete);
  2604. auto addDefinition = [this](std::string const& variable,
  2605. cm::string_view value) {
  2606. this->Makefile->AddDefinition(variable, value);
  2607. };
  2608. this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION",
  2609. this->Version, this->VersionCount,
  2610. this->VersionMajor, this->VersionMinor,
  2611. this->VersionPatch, this->VersionTweak);
  2612. if (!this->VersionRange.empty()) {
  2613. this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION_MIN",
  2614. this->Version, this->VersionCount,
  2615. this->VersionMajor, this->VersionMinor,
  2616. this->VersionPatch, this->VersionTweak);
  2617. this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION_MAX",
  2618. this->VersionMax, this->VersionMaxCount,
  2619. this->VersionMaxMajor, this->VersionMaxMinor,
  2620. this->VersionMaxPatch, this->VersionMaxTweak);
  2621. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE",
  2622. this->VersionComplete);
  2623. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE_MIN",
  2624. this->VersionRangeMin);
  2625. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE_MAX",
  2626. this->VersionRangeMax);
  2627. }
  2628. // Load the version check file.
  2629. // Pass NoPolicyScope because we do our own policy push/pop.
  2630. bool suitable = false;
  2631. if (this->ReadListFile(version_file, NoPolicyScope)) {
  2632. // Check the output variables.
  2633. bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
  2634. bool const unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
  2635. if (!okay && !this->VersionExact) {
  2636. okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
  2637. }
  2638. // The package is suitable if the version is okay and not
  2639. // explicitly unsuitable.
  2640. suitable = !unsuitable && (okay || this->Version.empty());
  2641. if (suitable) {
  2642. // Get the version found.
  2643. this->VersionFound =
  2644. this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  2645. // Try to parse the version number and store the results that were
  2646. // successfully parsed.
  2647. unsigned int parsed_major;
  2648. unsigned int parsed_minor;
  2649. unsigned int parsed_patch;
  2650. unsigned int parsed_tweak;
  2651. this->VersionFoundCount =
  2652. parseVersion(this->VersionFound, parsed_major, parsed_minor,
  2653. parsed_patch, parsed_tweak);
  2654. switch (this->VersionFoundCount) {
  2655. case 4:
  2656. this->VersionFoundTweak = parsed_tweak;
  2657. CM_FALLTHROUGH;
  2658. case 3:
  2659. this->VersionFoundPatch = parsed_patch;
  2660. CM_FALLTHROUGH;
  2661. case 2:
  2662. this->VersionFoundMinor = parsed_minor;
  2663. CM_FALLTHROUGH;
  2664. case 1:
  2665. this->VersionFoundMajor = parsed_major;
  2666. CM_FALLTHROUGH;
  2667. default:
  2668. break;
  2669. }
  2670. }
  2671. }
  2672. result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  2673. if (result_version.empty()) {
  2674. result_version = "unknown";
  2675. }
  2676. // Succeed if the version is suitable.
  2677. return suitable;
  2678. }
  2679. void cmFindPackageCommand::StoreVersionFound()
  2680. {
  2681. // Store the whole version string.
  2682. std::string const ver = cmStrCat(this->Name, "_VERSION");
  2683. auto addDefinition = [this](std::string const& variable,
  2684. cm::string_view value) {
  2685. this->Makefile->AddDefinition(variable, value);
  2686. };
  2687. this->SetVersionVariables(addDefinition, ver, this->VersionFound,
  2688. this->VersionFoundCount, this->VersionFoundMajor,
  2689. this->VersionFoundMinor, this->VersionFoundPatch,
  2690. this->VersionFoundTweak);
  2691. if (this->VersionFound.empty()) {
  2692. this->Makefile->RemoveDefinition(ver);
  2693. }
  2694. }
  2695. bool cmFindPackageCommand::SearchPrefix(std::string const& prefix)
  2696. {
  2697. assert(!prefix.empty() && prefix.back() == '/');
  2698. // Skip this if the prefix does not exist.
  2699. if (!cmSystemTools::FileIsDirectory(prefix)) {
  2700. return false;
  2701. }
  2702. // Skip this if it's in ignored paths.
  2703. std::string prefixWithoutSlash = prefix;
  2704. if (prefixWithoutSlash != "/" && prefixWithoutSlash.back() == '/') {
  2705. prefixWithoutSlash.erase(prefixWithoutSlash.length() - 1);
  2706. }
  2707. if (this->IgnoredPaths.count(prefixWithoutSlash) ||
  2708. this->IgnoredPrefixPaths.count(prefixWithoutSlash)) {
  2709. return false;
  2710. }
  2711. auto searchFn = [this](std::string const& fullPath,
  2712. PackageDescriptionType type) -> bool {
  2713. return this->SearchDirectory(fullPath, type);
  2714. };
  2715. auto iCpsGen = cmCaseInsensitiveDirectoryListGenerator{ "cps"_s };
  2716. auto iCMakeGen = cmCaseInsensitiveDirectoryListGenerator{ "cmake"_s };
  2717. auto anyDirGen =
  2718. cmAnyDirectoryListGenerator{ this->SortOrder, this->SortDirection };
  2719. auto cpsPkgDirGen =
  2720. cmProjectDirectoryListGenerator{ &this->Names, this->SortOrder,
  2721. this->SortDirection, true };
  2722. auto cmakePkgDirGen =
  2723. cmProjectDirectoryListGenerator{ &this->Names, this->SortOrder,
  2724. this->SortDirection, false };
  2725. // PREFIX/(Foo|foo|FOO)/(cps|CPS)/
  2726. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, cpsPkgDirGen, iCpsGen)) {
  2727. return true;
  2728. }
  2729. // PREFIX/(Foo|foo|FOO)/*/(cps|CPS)/
  2730. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, cpsPkgDirGen, iCpsGen,
  2731. anyDirGen)) {
  2732. return true;
  2733. }
  2734. // PREFIX/(cps|CPS)/(Foo|foo|FOO)/
  2735. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, iCpsGen, cpsPkgDirGen)) {
  2736. return true;
  2737. }
  2738. // PREFIX/(cps|CPS)/(Foo|foo|FOO)/*/
  2739. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, iCpsGen, cpsPkgDirGen,
  2740. anyDirGen)) {
  2741. return true;
  2742. }
  2743. // PREFIX/(cps|CPS)/ (useful on windows or in build trees)
  2744. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, iCpsGen)) {
  2745. return true;
  2746. }
  2747. // PREFIX/ (useful on windows or in build trees)
  2748. if (this->SearchDirectory(prefix, pdt::CMake)) {
  2749. return true;
  2750. }
  2751. // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
  2752. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, iCMakeGen)) {
  2753. return true;
  2754. }
  2755. // PREFIX/(Foo|foo|FOO).*/
  2756. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, cmakePkgDirGen)) {
  2757. return true;
  2758. }
  2759. // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
  2760. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, cmakePkgDirGen,
  2761. iCMakeGen)) {
  2762. return true;
  2763. }
  2764. auto secondPkgDirGen =
  2765. cmProjectDirectoryListGenerator{ &this->Names, this->SortOrder,
  2766. this->SortDirection, false };
  2767. // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/(Foo|foo|FOO).*/
  2768. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, cmakePkgDirGen,
  2769. iCMakeGen, secondPkgDirGen)) {
  2770. return true;
  2771. }
  2772. // Construct list of common install locations (lib and share).
  2773. std::vector<cm::string_view> common;
  2774. std::string libArch;
  2775. if (!this->LibraryArchitecture.empty()) {
  2776. libArch = "lib/" + this->LibraryArchitecture;
  2777. common.emplace_back(libArch);
  2778. }
  2779. if (this->UseLib32Paths) {
  2780. common.emplace_back("lib32"_s);
  2781. }
  2782. if (this->UseLib64Paths) {
  2783. common.emplace_back("lib64"_s);
  2784. }
  2785. if (this->UseLibx32Paths) {
  2786. common.emplace_back("libx32"_s);
  2787. }
  2788. common.emplace_back("lib"_s);
  2789. common.emplace_back("share"_s);
  2790. auto commonGen = cmEnumPathSegmentsGenerator{ common };
  2791. auto cmakeGen = cmAppendPathSegmentGenerator{ "cmake"_s };
  2792. auto cpsGen = cmAppendPathSegmentGenerator{ "cps"_s };
  2793. // PREFIX/(lib/ARCH|lib*|share)/cps/(Foo|foo|FOO)/
  2794. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, commonGen, cpsGen,
  2795. cpsPkgDirGen)) {
  2796. return true;
  2797. }
  2798. // PREFIX/(lib/ARCH|lib*|share)/cps/(Foo|foo|FOO)/*/
  2799. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, commonGen, cpsGen,
  2800. cpsPkgDirGen, anyDirGen)) {
  2801. return true;
  2802. }
  2803. // PREFIX/(lib/ARCH|lib*|share)/cps/
  2804. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, commonGen, cpsGen)) {
  2805. return true;
  2806. }
  2807. // PREFIX/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  2808. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, commonGen, cmakeGen,
  2809. cmakePkgDirGen)) {
  2810. return true;
  2811. }
  2812. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  2813. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, commonGen,
  2814. cmakePkgDirGen)) {
  2815. return true;
  2816. }
  2817. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  2818. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, commonGen,
  2819. cmakePkgDirGen, iCMakeGen)) {
  2820. return true;
  2821. }
  2822. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  2823. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, cmakePkgDirGen,
  2824. commonGen, cmakeGen, secondPkgDirGen)) {
  2825. return true;
  2826. }
  2827. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  2828. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, cmakePkgDirGen,
  2829. commonGen, secondPkgDirGen)) {
  2830. return true;
  2831. }
  2832. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  2833. return TryGeneratedPaths(searchFn, pdt::CMake, prefix, cmakePkgDirGen,
  2834. commonGen, secondPkgDirGen, iCMakeGen);
  2835. }
  2836. bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix)
  2837. {
  2838. assert(!prefix.empty() && prefix.back() == '/');
  2839. auto searchFn = [this](std::string const& fullPath,
  2840. PackageDescriptionType type) -> bool {
  2841. return this->SearchDirectory(fullPath, type);
  2842. };
  2843. auto iCMakeGen = cmCaseInsensitiveDirectoryListGenerator{ "cmake"_s };
  2844. auto iCpsGen = cmCaseInsensitiveDirectoryListGenerator{ "cps"_s };
  2845. auto fwGen =
  2846. cmMacProjectDirectoryListGenerator{ &this->Names, ".framework"_s };
  2847. auto rGen = cmAppendPathSegmentGenerator{ "Resources"_s };
  2848. auto vGen = cmAppendPathSegmentGenerator{ "Versions"_s };
  2849. auto anyGen =
  2850. cmAnyDirectoryListGenerator{ this->SortOrder, this->SortDirection };
  2851. // <prefix>/Foo.framework/Versions/*/Resources/CPS/
  2852. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, fwGen, vGen, anyGen, rGen,
  2853. iCpsGen)) {
  2854. return true;
  2855. }
  2856. // <prefix>/Foo.framework/Resources/CPS/
  2857. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, fwGen, rGen, iCpsGen)) {
  2858. return true;
  2859. }
  2860. // <prefix>/Foo.framework/Resources/
  2861. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, fwGen, rGen)) {
  2862. return true;
  2863. }
  2864. // <prefix>/Foo.framework/Resources/CMake/
  2865. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, fwGen, rGen,
  2866. iCMakeGen)) {
  2867. return true;
  2868. }
  2869. // <prefix>/Foo.framework/Versions/*/Resources/
  2870. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, fwGen, vGen, anyGen,
  2871. rGen)) {
  2872. return true;
  2873. }
  2874. // <prefix>/Foo.framework/Versions/*/Resources/CMake/
  2875. return TryGeneratedPaths(searchFn, pdt::CMake, prefix, fwGen, vGen, anyGen,
  2876. rGen, iCMakeGen);
  2877. }
  2878. bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix)
  2879. {
  2880. assert(!prefix.empty() && prefix.back() == '/');
  2881. auto searchFn = [this](std::string const& fullPath,
  2882. PackageDescriptionType type) -> bool {
  2883. return this->SearchDirectory(fullPath, type);
  2884. };
  2885. auto appGen = cmMacProjectDirectoryListGenerator{ &this->Names, ".app"_s };
  2886. auto crGen = cmAppendPathSegmentGenerator{ "Contents/Resources"_s };
  2887. // <prefix>/Foo.app/Contents/Resources/CPS/
  2888. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, appGen, crGen,
  2889. cmCaseInsensitiveDirectoryListGenerator{ "cps"_s })) {
  2890. return true;
  2891. }
  2892. // <prefix>/Foo.app/Contents/Resources/
  2893. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, appGen, crGen)) {
  2894. return true;
  2895. }
  2896. // <prefix>/Foo.app/Contents/Resources/CMake/
  2897. return TryGeneratedPaths(
  2898. searchFn, pdt::CMake, prefix, appGen, crGen,
  2899. cmCaseInsensitiveDirectoryListGenerator{ "cmake"_s });
  2900. }
  2901. bool cmFindPackageCommand::SearchEnvironmentPrefix(std::string const& prefix)
  2902. {
  2903. assert(!prefix.empty() && prefix.back() == '/');
  2904. // Skip this if the prefix does not exist.
  2905. if (!cmSystemTools::FileIsDirectory(prefix)) {
  2906. return false;
  2907. }
  2908. auto searchFn = [this](std::string const& fullPath,
  2909. PackageDescriptionType type) -> bool {
  2910. return this->SearchDirectory(fullPath, type);
  2911. };
  2912. auto pkgDirGen =
  2913. cmProjectDirectoryListGenerator{ &this->Names, this->SortOrder,
  2914. this->SortDirection, true };
  2915. // <environment-path>/(Foo|foo|FOO)/cps/
  2916. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, pkgDirGen,
  2917. cmAppendPathSegmentGenerator{ "cps"_s })) {
  2918. return true;
  2919. }
  2920. // <environment-path>/(Foo|foo|FOO)/
  2921. return TryGeneratedPaths(searchFn, pdt::Cps, prefix, pkgDirGen);
  2922. }
  2923. bool cmFindPackageCommand::IsRequired() const
  2924. {
  2925. return this->Required == RequiredStatus::RequiredExplicit ||
  2926. this->Required == RequiredStatus::RequiredFromPackageVar ||
  2927. this->Required == RequiredStatus::RequiredFromFindVar;
  2928. }
  2929. // TODO: Debug cmsys::Glob double slash problem.
  2930. bool cmFindPackage(std::vector<std::string> const& args,
  2931. cmExecutionStatus& status)
  2932. {
  2933. return cmFindPackageCommand(status).InitialPass(args);
  2934. }