cmFindPackageCommand.cxx 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst 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. std::vector<std::string> missingTargets;
  1389. if (fileFound) {
  1390. if (this->Makefile->IsDefinitionSet(foundVar) &&
  1391. !this->Makefile->IsOn(foundVar)) {
  1392. // by removing Foo_FOUND here if it is FALSE, we don't really change
  1393. // the situation for the Config file which is about to be included,
  1394. // but we make it possible to detect later on whether the Config file
  1395. // has set Foo_FOUND to FALSE itself:
  1396. this->Makefile->RemoveDefinition(foundVar);
  1397. }
  1398. this->Makefile->RemoveDefinition(notFoundMessageVar);
  1399. // Set the version variables before loading the config file.
  1400. // It may override them.
  1401. this->StoreVersionFound();
  1402. // Parse the configuration file.
  1403. if (this->CpsReader) {
  1404. // The package has been found.
  1405. found = true;
  1406. result = this->ReadPackage();
  1407. } else if (this->ReadListFile(this->FileFound, DoPolicyScope)) {
  1408. // The package has been found.
  1409. found = true;
  1410. // Check whether the Config file has set Foo_FOUND to FALSE:
  1411. if (this->Makefile->IsDefinitionSet(foundVar) &&
  1412. !this->Makefile->IsOn(foundVar)) {
  1413. // we get here if the Config file has set Foo_FOUND actively to FALSE
  1414. found = false;
  1415. configFileSetFOUNDFalse = true;
  1416. notFoundMessage =
  1417. this->Makefile->GetSafeDefinition(notFoundMessageVar);
  1418. }
  1419. // Check whether the required targets are defined.
  1420. if (found && !this->RequiredTargets.empty()) {
  1421. for (std::string const& t : this->RequiredTargets) {
  1422. std::string qualifiedTarget = cmStrCat(this->Name, "::"_s, t);
  1423. if (!this->Makefile->FindImportedTarget(qualifiedTarget)) {
  1424. missingTargets.emplace_back(std::move(qualifiedTarget));
  1425. found = false;
  1426. }
  1427. }
  1428. }
  1429. } else {
  1430. // The configuration file is invalid.
  1431. result = false;
  1432. }
  1433. }
  1434. if (this->UseFindModules && !found &&
  1435. handlePackageModeType == HandlePackageModeType::Config &&
  1436. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  1437. // Config mode failed. Allow Module case.
  1438. result = false;
  1439. }
  1440. // package not found
  1441. if (result && !found) {
  1442. // warn if package required or
  1443. // (neither quiet nor in config mode and not explicitly optional)
  1444. if (this->IsRequired() ||
  1445. (!(this->Quiet ||
  1446. (this->UseConfigFiles && !this->UseFindModules &&
  1447. this->ConsideredConfigs.empty())) &&
  1448. this->Required != RequiredStatus::OptionalExplicit)) {
  1449. // The variable is not set.
  1450. std::ostringstream e;
  1451. std::ostringstream aw;
  1452. if (configFileSetFOUNDFalse) {
  1453. e << "Found package configuration file:\n"
  1454. " "
  1455. << this->FileFound
  1456. << "\n"
  1457. "but it set "
  1458. << foundVar << " to FALSE so package \"" << this->Name
  1459. << "\" is considered to be NOT FOUND.";
  1460. if (!notFoundMessage.empty()) {
  1461. e << " Reason given by package: \n" << notFoundMessage << "\n";
  1462. }
  1463. } else if (!missingTargets.empty()) {
  1464. e << "Found package configuration file:\n"
  1465. " "
  1466. << this->FileFound
  1467. << "\n"
  1468. "but the following required targets were not found:\n"
  1469. " "
  1470. << cmJoin(cmMakeRange(missingTargets), ", "_s);
  1471. } else if (!this->ConsideredConfigs.empty()) {
  1472. // If there are files in ConsideredConfigs, it means that
  1473. // FooConfig.cmake have been found, but they didn't have appropriate
  1474. // versions.
  1475. auto duplicate_end = cmRemoveDuplicates(this->ConsideredConfigs);
  1476. e << "Could not find a configuration file for package \"" << this->Name
  1477. << "\" that "
  1478. << (this->VersionExact ? "exactly matches" : "is compatible with")
  1479. << " requested version "
  1480. << (this->VersionRange.empty() ? "" : "range ") << '"'
  1481. << this->VersionComplete
  1482. << "\".\n"
  1483. "The following configuration files were considered but not "
  1484. "accepted:\n";
  1485. for (ConfigFileInfo const& info :
  1486. cmMakeRange(this->ConsideredConfigs.cbegin(), duplicate_end)) {
  1487. e << " " << info.filename << ", version: " << info.version << '\n';
  1488. }
  1489. } else {
  1490. std::string requestedVersionString;
  1491. if (!this->VersionComplete.empty()) {
  1492. requestedVersionString =
  1493. cmStrCat(" (requested version ", this->VersionComplete, ')');
  1494. }
  1495. if (this->UseConfigFiles) {
  1496. if (this->UseFindModules) {
  1497. e << "By not providing \"Find" << this->Name
  1498. << ".cmake\" in "
  1499. "CMAKE_MODULE_PATH this project has asked CMake to find a "
  1500. "package configuration file provided by \""
  1501. << this->Name
  1502. << "\", "
  1503. "but CMake did not find one.\n";
  1504. }
  1505. if (this->Configs.size() == 1) {
  1506. e << "Could not find a package configuration file named \""
  1507. << this->Configs[0].Name << "\" provided by package \""
  1508. << this->Name << "\"" << requestedVersionString << ".\n";
  1509. } else {
  1510. auto configs = cmMakeRange(this->Configs);
  1511. auto configNames =
  1512. configs.transform([](ConfigName const& cn) { return cn.Name; });
  1513. e << "Could not find a package configuration file provided by \""
  1514. << this->Name << "\"" << requestedVersionString
  1515. << " with any of the following names:\n"
  1516. << cmWrap(" "_s, configNames, ""_s, "\n"_s) << '\n';
  1517. }
  1518. e << "Add the installation prefix of \"" << this->Name
  1519. << "\" to CMAKE_PREFIX_PATH or set \"" << this->Variable
  1520. << "\" to a directory containing one of the above files. "
  1521. "If \""
  1522. << this->Name
  1523. << "\" provides a separate development "
  1524. "package or SDK, be sure it has been installed.";
  1525. } else // if(!this->UseFindModules && !this->UseConfigFiles)
  1526. {
  1527. e << "No \"Find" << this->Name
  1528. << ".cmake\" found in "
  1529. "CMAKE_MODULE_PATH.";
  1530. aw
  1531. << "Find" << this->Name
  1532. << ".cmake must either be part of this "
  1533. "project itself, in this case adjust CMAKE_MODULE_PATH so that "
  1534. "it points to the correct location inside its source tree.\n"
  1535. "Or it must be installed by a package which has already been "
  1536. "found via find_package(). In this case make sure that "
  1537. "package has indeed been found and adjust CMAKE_MODULE_PATH to "
  1538. "contain the location where that package has installed "
  1539. "Find"
  1540. << this->Name
  1541. << ".cmake. This must be a location "
  1542. "provided by that package. This error in general means that "
  1543. "the buildsystem of this project is relying on a Find-module "
  1544. "without ensuring that it is actually available.\n";
  1545. }
  1546. }
  1547. if (this->Required == RequiredStatus::RequiredFromFindVar) {
  1548. e << "\nThis package is considered required because the "
  1549. "CMAKE_FIND_REQUIRED variable has been enabled.\n";
  1550. } else if (this->Required == RequiredStatus::RequiredFromPackageVar) {
  1551. e << "\nThis package is considered required because the "
  1552. << cmStrCat("CMAKE_REQUIRE_FIND_PACKAGE_", this->Name)
  1553. << " variable has been enabled.\n";
  1554. }
  1555. this->Makefile->IssueMessage(
  1556. this->IsRequired() ? MessageType::FATAL_ERROR : MessageType::WARNING,
  1557. e.str());
  1558. if (this->IsRequired()) {
  1559. cmSystemTools::SetFatalErrorOccurred();
  1560. }
  1561. if (!aw.str().empty()) {
  1562. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  1563. }
  1564. }
  1565. // output result if in config mode but not in quiet mode
  1566. else if (!this->Quiet) {
  1567. this->Makefile->DisplayStatus(cmStrCat("Could NOT find ", this->Name,
  1568. " (missing: ", this->Name,
  1569. "_DIR)"),
  1570. -1);
  1571. }
  1572. }
  1573. // Set a variable marking whether the package was found.
  1574. this->Makefile->AddDefinition(foundVar, found ? "1" : "0");
  1575. // Set a variable naming the configuration file that was found.
  1576. std::string const fileVar = cmStrCat(this->Name, "_CONFIG");
  1577. if (found) {
  1578. this->Makefile->AddDefinition(fileVar, this->FileFound);
  1579. } else {
  1580. this->Makefile->RemoveDefinition(fileVar);
  1581. }
  1582. std::string const consideredConfigsVar =
  1583. cmStrCat(this->Name, "_CONSIDERED_CONFIGS");
  1584. std::string const consideredVersionsVar =
  1585. cmStrCat(this->Name, "_CONSIDERED_VERSIONS");
  1586. std::string consideredConfigFiles;
  1587. std::string consideredVersions;
  1588. char const* sep = "";
  1589. for (ConfigFileInfo const& i : this->ConsideredConfigs) {
  1590. consideredConfigFiles += sep;
  1591. consideredVersions += sep;
  1592. consideredConfigFiles += i.filename;
  1593. consideredVersions += i.version;
  1594. sep = ";";
  1595. }
  1596. this->Makefile->AddDefinition(consideredConfigsVar, consideredConfigFiles);
  1597. this->Makefile->AddDefinition(consideredVersionsVar, consideredVersions);
  1598. return result;
  1599. }
  1600. bool cmFindPackageCommand::FindConfig()
  1601. {
  1602. // Compute the set of search prefixes.
  1603. this->ComputePrefixes();
  1604. // Look for the project's configuration file.
  1605. bool found = false;
  1606. if (this->DebugMode) {
  1607. this->DebugBuffer = cmStrCat(this->DebugBuffer,
  1608. "find_package considered the following "
  1609. "locations for ",
  1610. this->Name, "'s Config module:\n");
  1611. }
  1612. if (!found && this->UseCpsFiles) {
  1613. found = this->FindEnvironmentConfig();
  1614. }
  1615. // Search for frameworks.
  1616. if (!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly)) {
  1617. found = this->FindFrameworkConfig();
  1618. }
  1619. // Search for apps.
  1620. if (!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly)) {
  1621. found = this->FindAppBundleConfig();
  1622. }
  1623. // Search prefixes.
  1624. if (!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly)) {
  1625. found = this->FindPrefixedConfig();
  1626. }
  1627. // Search for frameworks.
  1628. if (!found && this->SearchFrameworkLast) {
  1629. found = this->FindFrameworkConfig();
  1630. }
  1631. // Search for apps.
  1632. if (!found && this->SearchAppBundleLast) {
  1633. found = this->FindAppBundleConfig();
  1634. }
  1635. if (this->DebugMode) {
  1636. if (found) {
  1637. this->DebugBuffer = cmStrCat(
  1638. this->DebugBuffer, "The file was found at\n ", this->FileFound, '\n');
  1639. } else {
  1640. this->DebugBuffer =
  1641. cmStrCat(this->DebugBuffer, "The file was not found.\n");
  1642. }
  1643. }
  1644. // Store the entry in the cache so it can be set by the user.
  1645. std::string init;
  1646. if (found) {
  1647. init = cmSystemTools::GetFilenamePath(this->FileFound);
  1648. } else {
  1649. init = this->Variable + "-NOTFOUND";
  1650. }
  1651. // We force the value since we do not get here if it was already set.
  1652. this->SetConfigDirCacheVariable(init);
  1653. return found;
  1654. }
  1655. void cmFindPackageCommand::SetConfigDirCacheVariable(std::string const& value)
  1656. {
  1657. std::string const help =
  1658. cmStrCat("The directory containing a CMake configuration file for ",
  1659. this->Name, '.');
  1660. this->Makefile->AddCacheDefinition(this->Variable, value, help,
  1661. cmStateEnums::PATH, true);
  1662. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0126) ==
  1663. cmPolicies::NEW &&
  1664. this->Makefile->IsNormalDefinitionSet(this->Variable)) {
  1665. this->Makefile->AddDefinition(this->Variable, value);
  1666. }
  1667. }
  1668. bool cmFindPackageCommand::FindPrefixedConfig()
  1669. {
  1670. std::vector<std::string> const& prefixes = this->SearchPaths;
  1671. return std::any_of(
  1672. prefixes.begin(), prefixes.end(),
  1673. [this](std::string const& p) -> bool { return this->SearchPrefix(p); });
  1674. }
  1675. bool cmFindPackageCommand::FindFrameworkConfig()
  1676. {
  1677. std::vector<std::string> const& prefixes = this->SearchPaths;
  1678. return std::any_of(prefixes.begin(), prefixes.end(),
  1679. [this](std::string const& p) -> bool {
  1680. return this->SearchFrameworkPrefix(p);
  1681. });
  1682. }
  1683. bool cmFindPackageCommand::FindAppBundleConfig()
  1684. {
  1685. std::vector<std::string> const& prefixes = this->SearchPaths;
  1686. return std::any_of(prefixes.begin(), prefixes.end(),
  1687. [this](std::string const& p) -> bool {
  1688. return this->SearchAppBundlePrefix(p);
  1689. });
  1690. }
  1691. bool cmFindPackageCommand::FindEnvironmentConfig()
  1692. {
  1693. std::vector<std::string> const& prefixes =
  1694. cmSystemTools::GetEnvPathNormalized("CPS_PATH");
  1695. return std::any_of(prefixes.begin(), prefixes.end(),
  1696. [this](std::string const& p) -> bool {
  1697. return this->SearchEnvironmentPrefix(p);
  1698. });
  1699. }
  1700. cmFindPackageCommand::AppendixMap cmFindPackageCommand::FindAppendices(
  1701. std::string const& base, cmPackageInfoReader const& baseReader) const
  1702. {
  1703. AppendixMap appendices;
  1704. // Find package appendices.
  1705. cmsys::Glob glob;
  1706. glob.RecurseOff();
  1707. if (glob.FindFiles(cmStrCat(cmSystemTools::GetFilenamePath(base), "/"_s,
  1708. cmSystemTools::GetFilenameWithoutExtension(base),
  1709. "[-:]*.[Cc][Pp][Ss]"_s))) {
  1710. // Check glob results for valid appendices.
  1711. for (std::string const& extra : glob.GetFiles()) {
  1712. // Exclude configuration-specific files for now; we look at them later
  1713. // when we load their respective configuration-agnostic appendices.
  1714. if (extra.find('@') != std::string::npos) {
  1715. continue;
  1716. }
  1717. std::unique_ptr<cmPackageInfoReader> reader =
  1718. cmPackageInfoReader::Read(extra, &baseReader);
  1719. if (reader && reader->GetName() == this->Name) {
  1720. std::vector<std::string> components = reader->GetComponentNames();
  1721. Appendix appendix{ std::move(reader), std::move(components) };
  1722. appendices.emplace(extra, std::move(appendix));
  1723. }
  1724. }
  1725. }
  1726. return appendices;
  1727. }
  1728. bool cmFindPackageCommand::ReadListFile(std::string const& f,
  1729. PolicyScopeRule const psr)
  1730. {
  1731. bool const noPolicyScope = !this->PolicyScope || psr == NoPolicyScope;
  1732. using ITScope = cmMakefile::ImportedTargetScope;
  1733. ITScope scope = this->GlobalScope ? ITScope::Global : ITScope::Local;
  1734. cmMakefile::SetGlobalTargetImportScope globScope(this->Makefile, scope);
  1735. if (this->Makefile->ReadDependentFile(f, noPolicyScope)) {
  1736. return true;
  1737. }
  1738. std::string const e = cmStrCat("Error reading CMake code from \"", f, "\".");
  1739. this->SetError(e);
  1740. return false;
  1741. }
  1742. bool cmFindPackageCommand::ReadPackage()
  1743. {
  1744. // Resolve any transitive dependencies for the root file.
  1745. if (!FindPackageDependencies(this->FileFound, *this->CpsReader,
  1746. this->Required)) {
  1747. return false;
  1748. }
  1749. bool const hasComponentsRequested =
  1750. !this->RequiredComponents.empty() || !this->OptionalComponents.empty();
  1751. cmMakefile::CallRAII scope{ this->Makefile, this->FileFound, this->Status };
  1752. // Loop over appendices.
  1753. auto iter = this->CpsAppendices.begin();
  1754. while (iter != this->CpsAppendices.end()) {
  1755. RequiredStatus required = RequiredStatus::Optional;
  1756. bool important = false;
  1757. // Check if this appendix provides any requested components.
  1758. if (hasComponentsRequested) {
  1759. auto providesAny = [&iter](
  1760. std::set<std::string> const& desiredComponents) {
  1761. return std::any_of(iter->second.Components.begin(),
  1762. iter->second.Components.end(),
  1763. [&desiredComponents](std::string const& component) {
  1764. return cm::contains(desiredComponents, component);
  1765. });
  1766. };
  1767. if (providesAny(this->RequiredComponents)) {
  1768. important = true;
  1769. required = this->Required;
  1770. } else if (!providesAny(this->OptionalComponents)) {
  1771. // This appendix doesn't provide any requested components; remove it
  1772. // from the set to be imported.
  1773. iter = this->CpsAppendices.erase(iter);
  1774. continue;
  1775. }
  1776. }
  1777. // Resolve any transitive dependencies for the appendix.
  1778. if (!this->FindPackageDependencies(iter->first, iter->second, required)) {
  1779. if (important) {
  1780. // Some dependencies are missing, and we need(ed) this appendix; fail.
  1781. return false;
  1782. }
  1783. // Some dependencies are missing, but we don't need this appendix; remove
  1784. // it from the set to be imported.
  1785. iter = this->CpsAppendices.erase(iter);
  1786. } else {
  1787. ++iter;
  1788. }
  1789. }
  1790. // Import targets from root file.
  1791. if (!this->ImportPackageTargets(this->FileFound, *this->CpsReader)) {
  1792. return false;
  1793. }
  1794. // Import targets from appendices.
  1795. // NOLINTNEXTLINE(readability-use-anyofallof)
  1796. for (auto const& appendix : this->CpsAppendices) {
  1797. cmMakefile::CallRAII appendixScope{ this->Makefile, appendix.first,
  1798. this->Status };
  1799. if (!this->ImportPackageTargets(appendix.first, appendix.second)) {
  1800. return false;
  1801. }
  1802. }
  1803. return true;
  1804. }
  1805. bool cmFindPackageCommand::FindPackageDependencies(
  1806. std::string const& fileName, cmPackageInfoReader const& reader,
  1807. RequiredStatus required)
  1808. {
  1809. // Get package requirements.
  1810. for (cmPackageRequirement const& dep : reader.GetRequirements()) {
  1811. cmExecutionStatus status{ *this->Makefile };
  1812. cmMakefile::CallRAII scope{ this->Makefile, fileName, status };
  1813. // For each requirement, set up a nested instance to find it.
  1814. cmFindPackageCommand fp{ status };
  1815. fp.InheritOptions(this);
  1816. fp.Name = dep.Name;
  1817. fp.Required = required;
  1818. fp.UseFindModules = false;
  1819. fp.UseCpsFiles = true;
  1820. fp.Version = dep.Version;
  1821. fp.VersionComplete = dep.Version;
  1822. fp.VersionCount =
  1823. parseVersion(fp.Version, fp.VersionMajor, fp.VersionMinor,
  1824. fp.VersionPatch, fp.VersionTweak);
  1825. fp.Components = cmJoin(cmMakeRange(dep.Components), ";"_s);
  1826. fp.OptionalComponents =
  1827. std::set<std::string>{ dep.Components.begin(), dep.Components.end() };
  1828. fp.RequiredTargets = fp.OptionalComponents;
  1829. // TODO set hints
  1830. // Try to find the requirement; fail if we can't.
  1831. if (!fp.FindPackage() || fp.FileFound.empty()) {
  1832. this->SetError(cmStrCat("could not find "_s, dep.Name,
  1833. ", required by "_s, this->Name, '.'));
  1834. return false;
  1835. }
  1836. }
  1837. // All requirements (if any) were found.
  1838. return true;
  1839. }
  1840. bool cmFindPackageCommand::ImportPackageTargets(std::string const& fileName,
  1841. cmPackageInfoReader& reader)
  1842. {
  1843. // Import base file.
  1844. if (!reader.ImportTargets(this->Makefile, this->Status)) {
  1845. return false;
  1846. }
  1847. // Find supplemental configuration files.
  1848. cmsys::Glob glob;
  1849. glob.RecurseOff();
  1850. if (glob.FindFiles(
  1851. cmStrCat(cmSystemTools::GetFilenamePath(fileName), '/',
  1852. cmSystemTools::GetFilenameWithoutExtension(fileName),
  1853. "@*.[Cc][Pp][Ss]"_s))) {
  1854. // Try to read supplemental data from each file found.
  1855. for (std::string const& extra : glob.GetFiles()) {
  1856. std::unique_ptr<cmPackageInfoReader> configReader =
  1857. cmPackageInfoReader::Read(extra, &reader);
  1858. if (configReader && configReader->GetName() == this->Name) {
  1859. if (!configReader->ImportTargetConfigurations(this->Makefile,
  1860. this->Status)) {
  1861. return false;
  1862. }
  1863. }
  1864. }
  1865. }
  1866. return true;
  1867. }
  1868. void cmFindPackageCommand::AppendToFoundProperty(bool const found)
  1869. {
  1870. cmList foundContents;
  1871. cmValue foundProp =
  1872. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_FOUND");
  1873. if (!foundProp.IsEmpty()) {
  1874. foundContents.assign(*foundProp);
  1875. foundContents.remove_items({ this->Name });
  1876. }
  1877. cmList notFoundContents;
  1878. cmValue notFoundProp =
  1879. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_NOT_FOUND");
  1880. if (!notFoundProp.IsEmpty()) {
  1881. notFoundContents.assign(*notFoundProp);
  1882. notFoundContents.remove_items({ this->Name });
  1883. }
  1884. if (found) {
  1885. foundContents.push_back(this->Name);
  1886. } else {
  1887. notFoundContents.push_back(this->Name);
  1888. }
  1889. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_FOUND",
  1890. foundContents.to_string());
  1891. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_NOT_FOUND",
  1892. notFoundContents.to_string());
  1893. }
  1894. void cmFindPackageCommand::AppendSuccessInformation()
  1895. {
  1896. {
  1897. std::string const transitivePropName =
  1898. cmStrCat("_CMAKE_", this->Name, "_TRANSITIVE_DEPENDENCY");
  1899. this->Makefile->GetState()->SetGlobalProperty(transitivePropName, "False");
  1900. }
  1901. std::string const found = cmStrCat(this->Name, "_FOUND");
  1902. std::string const upperFound = cmSystemTools::UpperCase(found);
  1903. bool const upperResult = this->Makefile->IsOn(upperFound);
  1904. bool const result = this->Makefile->IsOn(found);
  1905. bool const packageFound = (result || upperResult);
  1906. this->AppendToFoundProperty(packageFound);
  1907. // Record whether the find was quiet or not, so this can be used
  1908. // e.g. in FeatureSummary.cmake
  1909. std::string const quietInfoPropName =
  1910. cmStrCat("_CMAKE_", this->Name, "_QUIET");
  1911. this->Makefile->GetState()->SetGlobalProperty(
  1912. quietInfoPropName, this->Quiet ? "TRUE" : "FALSE");
  1913. // set a global property to record the required version of this package
  1914. std::string const versionInfoPropName =
  1915. cmStrCat("_CMAKE_", this->Name, "_REQUIRED_VERSION");
  1916. std::string versionInfo;
  1917. if (!this->VersionRange.empty()) {
  1918. versionInfo = this->VersionRange;
  1919. } else if (!this->Version.empty()) {
  1920. versionInfo =
  1921. cmStrCat(this->VersionExact ? "==" : ">=", ' ', this->Version);
  1922. }
  1923. this->Makefile->GetState()->SetGlobalProperty(versionInfoPropName,
  1924. versionInfo);
  1925. if (this->IsRequired()) {
  1926. std::string const requiredInfoPropName =
  1927. cmStrCat("_CMAKE_", this->Name, "_TYPE");
  1928. this->Makefile->GetState()->SetGlobalProperty(requiredInfoPropName,
  1929. "REQUIRED");
  1930. }
  1931. }
  1932. void cmFindPackageCommand::PushFindPackageRootPathStack()
  1933. {
  1934. // Allocate a PACKAGE_ROOT_PATH for the current find_package call.
  1935. this->Makefile->FindPackageRootPathStack.emplace_back();
  1936. std::vector<std::string>& rootPaths =
  1937. this->Makefile->FindPackageRootPathStack.back();
  1938. // Add root paths from <PackageName>_ROOT CMake and environment variables,
  1939. // subject to CMP0074.
  1940. std::string const rootVar = this->Name + "_ROOT";
  1941. cmValue rootDef = this->Makefile->GetDefinition(rootVar);
  1942. if (rootDef && rootDef.IsEmpty()) {
  1943. rootDef = nullptr;
  1944. }
  1945. cm::optional<std::string> rootEnv = cmSystemTools::GetEnvVar(rootVar);
  1946. if (rootEnv && rootEnv->empty()) {
  1947. rootEnv = cm::nullopt;
  1948. }
  1949. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0074)) {
  1950. case cmPolicies::WARN:
  1951. this->Makefile->MaybeWarnCMP0074(rootVar, rootDef, rootEnv);
  1952. CM_FALLTHROUGH;
  1953. case cmPolicies::OLD:
  1954. // OLD behavior is to ignore the <PackageName>_ROOT variables.
  1955. return;
  1956. case cmPolicies::NEW: {
  1957. // NEW behavior is to honor the <PackageName>_ROOT variables.
  1958. } break;
  1959. }
  1960. // Add root paths from <PACKAGENAME>_ROOT CMake and environment variables,
  1961. // if they are different than <PackageName>_ROOT, and subject to CMP0144.
  1962. std::string const rootVAR = cmSystemTools::UpperCase(rootVar);
  1963. cmValue rootDEF;
  1964. cm::optional<std::string> rootENV;
  1965. if (rootVAR != rootVar) {
  1966. rootDEF = this->Makefile->GetDefinition(rootVAR);
  1967. if (rootDEF && (rootDEF.IsEmpty() || rootDEF == rootDef)) {
  1968. rootDEF = nullptr;
  1969. }
  1970. rootENV = cmSystemTools::GetEnvVar(rootVAR);
  1971. if (rootENV && (rootENV->empty() || rootENV == rootEnv)) {
  1972. rootENV = cm::nullopt;
  1973. }
  1974. }
  1975. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0144)) {
  1976. case cmPolicies::WARN:
  1977. this->Makefile->MaybeWarnCMP0144(rootVAR, rootDEF, rootENV);
  1978. CM_FALLTHROUGH;
  1979. case cmPolicies::OLD:
  1980. // OLD behavior is to ignore the <PACKAGENAME>_ROOT variables.
  1981. rootDEF = nullptr;
  1982. rootENV = cm::nullopt;
  1983. break;
  1984. case cmPolicies::NEW: {
  1985. // NEW behavior is to honor the <PACKAGENAME>_ROOT variables.
  1986. } break;
  1987. }
  1988. if (rootDef) {
  1989. cmExpandList(*rootDef, rootPaths);
  1990. }
  1991. if (rootDEF) {
  1992. cmExpandList(*rootDEF, rootPaths);
  1993. }
  1994. if (rootEnv) {
  1995. std::vector<std::string> p =
  1996. cmSystemTools::SplitEnvPathNormalized(*rootEnv);
  1997. std::move(p.begin(), p.end(), std::back_inserter(rootPaths));
  1998. }
  1999. if (rootENV) {
  2000. std::vector<std::string> p =
  2001. cmSystemTools::SplitEnvPathNormalized(*rootENV);
  2002. std::move(p.begin(), p.end(), std::back_inserter(rootPaths));
  2003. }
  2004. }
  2005. void cmFindPackageCommand::PopFindPackageRootPathStack()
  2006. {
  2007. this->Makefile->FindPackageRootPathStack.pop_back();
  2008. }
  2009. void cmFindPackageCommand::ComputePrefixes()
  2010. {
  2011. this->FillPrefixesPackageRedirect();
  2012. if (!this->NoDefaultPath) {
  2013. if (!this->NoPackageRootPath) {
  2014. this->FillPrefixesPackageRoot();
  2015. }
  2016. if (!this->NoCMakePath) {
  2017. this->FillPrefixesCMakeVariable();
  2018. }
  2019. if (!this->NoCMakeEnvironmentPath) {
  2020. this->FillPrefixesCMakeEnvironment();
  2021. }
  2022. }
  2023. this->FillPrefixesUserHints();
  2024. if (!this->NoDefaultPath) {
  2025. if (!this->NoSystemEnvironmentPath) {
  2026. this->FillPrefixesSystemEnvironment();
  2027. }
  2028. if (!this->NoUserRegistry) {
  2029. this->FillPrefixesUserRegistry();
  2030. }
  2031. if (!this->NoCMakeSystemPath) {
  2032. this->FillPrefixesCMakeSystemVariable();
  2033. }
  2034. if (!this->NoSystemRegistry) {
  2035. this->FillPrefixesSystemRegistry();
  2036. }
  2037. }
  2038. this->FillPrefixesUserGuess();
  2039. this->ComputeFinalPaths(IgnorePaths::No, &this->DebugBuffer);
  2040. }
  2041. void cmFindPackageCommand::FillPrefixesPackageRedirect()
  2042. {
  2043. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRedirect];
  2044. auto const redirectDir =
  2045. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_REDIRECTS_DIR");
  2046. if (redirectDir && !redirectDir->empty()) {
  2047. paths.AddPath(*redirectDir);
  2048. }
  2049. if (this->DebugMode) {
  2050. std::string debugBuffer =
  2051. "The internally managed CMAKE_FIND_PACKAGE_REDIRECTS_DIR.\n";
  2052. collectPathsForDebug(debugBuffer, paths);
  2053. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2054. }
  2055. }
  2056. void cmFindPackageCommand::FillPrefixesPackageRoot()
  2057. {
  2058. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot];
  2059. // Add the PACKAGE_ROOT_PATH from each enclosing find_package call.
  2060. for (auto pkgPaths = this->Makefile->FindPackageRootPathStack.rbegin();
  2061. pkgPaths != this->Makefile->FindPackageRootPathStack.rend();
  2062. ++pkgPaths) {
  2063. for (std::string const& path : *pkgPaths) {
  2064. paths.AddPath(path);
  2065. }
  2066. }
  2067. if (this->DebugMode) {
  2068. std::string debugBuffer = "<PackageName>_ROOT CMake variable "
  2069. "[CMAKE_FIND_USE_PACKAGE_ROOT_PATH].\n";
  2070. collectPathsForDebug(debugBuffer, paths);
  2071. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2072. }
  2073. }
  2074. void cmFindPackageCommand::FillPrefixesCMakeEnvironment()
  2075. {
  2076. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeEnvironment];
  2077. std::string debugBuffer;
  2078. std::size_t debugOffset = 0;
  2079. // Check the environment variable with the same name as the cache
  2080. // entry.
  2081. paths.AddEnvPath(this->Variable);
  2082. if (this->DebugMode) {
  2083. debugBuffer = cmStrCat("Env variable ", this->Variable,
  2084. " [CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
  2085. debugOffset = collectPathsForDebug(debugBuffer, paths);
  2086. }
  2087. // And now the general CMake environment variables
  2088. paths.AddEnvPath("CMAKE_PREFIX_PATH");
  2089. if (this->DebugMode) {
  2090. debugBuffer = cmStrCat(debugBuffer,
  2091. "CMAKE_PREFIX_PATH env variable "
  2092. "[CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
  2093. debugOffset = collectPathsForDebug(debugBuffer, paths, debugOffset);
  2094. }
  2095. paths.AddEnvPath("CMAKE_FRAMEWORK_PATH");
  2096. paths.AddEnvPath("CMAKE_APPBUNDLE_PATH");
  2097. if (this->DebugMode) {
  2098. debugBuffer =
  2099. cmStrCat(debugBuffer,
  2100. "CMAKE_FRAMEWORK_PATH and CMAKE_APPBUNDLE_PATH env "
  2101. "variables [CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
  2102. collectPathsForDebug(debugBuffer, paths, debugOffset);
  2103. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2104. }
  2105. }
  2106. void cmFindPackageCommand::FillPrefixesCMakeVariable()
  2107. {
  2108. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMake];
  2109. std::string debugBuffer;
  2110. std::size_t debugOffset = 0;
  2111. paths.AddCMakePath("CMAKE_PREFIX_PATH");
  2112. if (this->DebugMode) {
  2113. debugBuffer = "CMAKE_PREFIX_PATH variable [CMAKE_FIND_USE_CMAKE_PATH].\n";
  2114. debugOffset = collectPathsForDebug(debugBuffer, paths);
  2115. }
  2116. paths.AddCMakePath("CMAKE_FRAMEWORK_PATH");
  2117. paths.AddCMakePath("CMAKE_APPBUNDLE_PATH");
  2118. if (this->DebugMode) {
  2119. debugBuffer =
  2120. cmStrCat(debugBuffer,
  2121. "CMAKE_FRAMEWORK_PATH and CMAKE_APPBUNDLE_PATH variables "
  2122. "[CMAKE_FIND_USE_CMAKE_PATH].\n");
  2123. collectPathsForDebug(debugBuffer, paths, debugOffset);
  2124. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2125. }
  2126. }
  2127. void cmFindPackageCommand::FillPrefixesSystemEnvironment()
  2128. {
  2129. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemEnvironment];
  2130. // Use the system search path to generate prefixes.
  2131. // Relative paths are interpreted with respect to the current
  2132. // working directory.
  2133. std::vector<std::string> envPATH =
  2134. cmSystemTools::GetEnvPathNormalized("PATH");
  2135. for (std::string const& i : envPATH) {
  2136. // If the path is a PREFIX/bin case then add its parent instead.
  2137. if ((cmHasLiteralSuffix(i, "/bin")) || (cmHasLiteralSuffix(i, "/sbin"))) {
  2138. paths.AddPath(cmSystemTools::GetFilenamePath(i));
  2139. } else {
  2140. paths.AddPath(i);
  2141. }
  2142. }
  2143. if (this->DebugMode) {
  2144. std::string debugBuffer = "Standard system environment variables "
  2145. "[CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH].\n";
  2146. collectPathsForDebug(debugBuffer, paths);
  2147. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2148. }
  2149. }
  2150. void cmFindPackageCommand::FillPrefixesUserRegistry()
  2151. {
  2152. #if defined(_WIN32) && !defined(__CYGWIN__)
  2153. this->LoadPackageRegistryWinUser();
  2154. #elif defined(__HAIKU__)
  2155. char dir[B_PATH_NAME_LENGTH];
  2156. if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  2157. B_OK) {
  2158. std::string fname = cmStrCat(dir, "/cmake/packages/", Name);
  2159. this->LoadPackageRegistryDir(fname,
  2160. this->LabeledPaths[PathLabel::UserRegistry]);
  2161. }
  2162. #else
  2163. std::string dir;
  2164. if (cmSystemTools::GetEnv("HOME", dir)) {
  2165. dir += "/.cmake/packages/";
  2166. dir += this->Name;
  2167. this->LoadPackageRegistryDir(dir,
  2168. this->LabeledPaths[PathLabel::UserRegistry]);
  2169. }
  2170. #endif
  2171. if (this->DebugMode) {
  2172. std::string debugBuffer =
  2173. "CMake User Package Registry [CMAKE_FIND_USE_PACKAGE_REGISTRY].\n";
  2174. collectPathsForDebug(debugBuffer,
  2175. this->LabeledPaths[PathLabel::UserRegistry]);
  2176. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2177. }
  2178. }
  2179. void cmFindPackageCommand::FillPrefixesSystemRegistry()
  2180. {
  2181. if (this->NoSystemRegistry || this->NoDefaultPath) {
  2182. return;
  2183. }
  2184. #if defined(_WIN32) && !defined(__CYGWIN__)
  2185. this->LoadPackageRegistryWinSystem();
  2186. #endif
  2187. if (this->DebugMode) {
  2188. std::string debugBuffer =
  2189. "CMake System Package Registry "
  2190. "[CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY].\n";
  2191. collectPathsForDebug(debugBuffer,
  2192. this->LabeledPaths[PathLabel::SystemRegistry]);
  2193. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2194. }
  2195. }
  2196. #if defined(_WIN32) && !defined(__CYGWIN__)
  2197. void cmFindPackageCommand::LoadPackageRegistryWinUser()
  2198. {
  2199. // HKEY_CURRENT_USER\\Software shares 32-bit and 64-bit views.
  2200. this->LoadPackageRegistryWin(true, 0,
  2201. this->LabeledPaths[PathLabel::UserRegistry]);
  2202. }
  2203. void cmFindPackageCommand::LoadPackageRegistryWinSystem()
  2204. {
  2205. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemRegistry];
  2206. // HKEY_LOCAL_MACHINE\\SOFTWARE has separate 32-bit and 64-bit views.
  2207. // Prefer the target platform view first.
  2208. if (this->Makefile->PlatformIs64Bit()) {
  2209. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  2210. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  2211. } else {
  2212. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  2213. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  2214. }
  2215. }
  2216. void cmFindPackageCommand::LoadPackageRegistryWin(bool const user,
  2217. unsigned int const view,
  2218. cmSearchPath& outPaths)
  2219. {
  2220. std::wstring key = L"Software\\Kitware\\CMake\\Packages\\";
  2221. key += cmsys::Encoding::ToWide(this->Name);
  2222. std::set<std::wstring> bad;
  2223. HKEY hKey;
  2224. if (RegOpenKeyExW(user ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, key.c_str(),
  2225. 0, KEY_QUERY_VALUE | view, &hKey) == ERROR_SUCCESS) {
  2226. DWORD valueType = REG_NONE;
  2227. wchar_t name[16383]; // RegEnumValue docs limit name to 32767 _bytes_
  2228. std::vector<wchar_t> data(512);
  2229. bool done = false;
  2230. DWORD index = 0;
  2231. while (!done) {
  2232. DWORD nameSize = static_cast<DWORD>(sizeof(name));
  2233. DWORD dataSize = static_cast<DWORD>(data.size() * sizeof(data[0]));
  2234. switch (RegEnumValueW(hKey, index, name, &nameSize, 0, &valueType,
  2235. (BYTE*)&data[0], &dataSize)) {
  2236. case ERROR_SUCCESS:
  2237. ++index;
  2238. if (valueType == REG_SZ) {
  2239. data[dataSize] = 0;
  2240. if (!this->CheckPackageRegistryEntry(
  2241. cmsys::Encoding::ToNarrow(&data[0]), outPaths)) {
  2242. // The entry is invalid.
  2243. bad.insert(name);
  2244. }
  2245. }
  2246. break;
  2247. case ERROR_MORE_DATA:
  2248. data.resize((dataSize + sizeof(data[0]) - 1) / sizeof(data[0]));
  2249. break;
  2250. case ERROR_NO_MORE_ITEMS:
  2251. default:
  2252. done = true;
  2253. break;
  2254. }
  2255. }
  2256. RegCloseKey(hKey);
  2257. }
  2258. // Remove bad values if possible.
  2259. if (user && !bad.empty() &&
  2260. RegOpenKeyExW(HKEY_CURRENT_USER, key.c_str(), 0, KEY_SET_VALUE | view,
  2261. &hKey) == ERROR_SUCCESS) {
  2262. for (std::wstring const& v : bad) {
  2263. RegDeleteValueW(hKey, v.c_str());
  2264. }
  2265. RegCloseKey(hKey);
  2266. }
  2267. }
  2268. #else
  2269. void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir,
  2270. cmSearchPath& outPaths)
  2271. {
  2272. cmsys::Directory files;
  2273. if (!files.Load(dir)) {
  2274. return;
  2275. }
  2276. std::string fname;
  2277. for (unsigned long i = 0; i < files.GetNumberOfFiles(); ++i) {
  2278. fname = cmStrCat(dir, '/', files.GetFile(i));
  2279. if (!cmSystemTools::FileIsDirectory(fname)) {
  2280. // Hold this file hostage until it behaves.
  2281. cmFindPackageCommandHoldFile holdFile(fname.c_str());
  2282. // Load the file.
  2283. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  2284. std::string fentry;
  2285. if (fin && cmSystemTools::GetLineFromStream(fin, fentry) &&
  2286. this->CheckPackageRegistryEntry(fentry, outPaths)) {
  2287. // The file references an existing package, so release it.
  2288. holdFile.Release();
  2289. }
  2290. }
  2291. }
  2292. // TODO: Wipe out the directory if it is empty.
  2293. }
  2294. #endif
  2295. bool cmFindPackageCommand::CheckPackageRegistryEntry(std::string const& fname,
  2296. cmSearchPath& outPaths)
  2297. {
  2298. // Parse the content of one package registry entry.
  2299. if (cmSystemTools::FileIsFullPath(fname)) {
  2300. // The first line in the stream is the full path to a file or
  2301. // directory containing the package.
  2302. if (cmSystemTools::FileExists(fname)) {
  2303. // The path exists. Look for the package here.
  2304. if (!cmSystemTools::FileIsDirectory(fname)) {
  2305. outPaths.AddPath(cmSystemTools::GetFilenamePath(fname));
  2306. } else {
  2307. outPaths.AddPath(fname);
  2308. }
  2309. return true;
  2310. }
  2311. // The path does not exist. Assume the stream content is
  2312. // associated with an old package that no longer exists, and
  2313. // delete it to keep the package registry clean.
  2314. return false;
  2315. }
  2316. // The first line in the stream is not the full path to a file or
  2317. // directory. Assume the stream content was created by a future
  2318. // version of CMake that uses a different format, and leave it.
  2319. return true;
  2320. }
  2321. void cmFindPackageCommand::FillPrefixesCMakeSystemVariable()
  2322. {
  2323. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeSystem];
  2324. bool const install_prefix_in_list =
  2325. !this->Makefile->IsOn("CMAKE_FIND_NO_INSTALL_PREFIX");
  2326. bool const remove_install_prefix = this->NoCMakeInstallPath;
  2327. bool const add_install_prefix = !this->NoCMakeInstallPath &&
  2328. this->Makefile->IsDefinitionSet("CMAKE_FIND_USE_INSTALL_PREFIX");
  2329. // We have 3 possible states for `CMAKE_SYSTEM_PREFIX_PATH` and
  2330. // `CMAKE_INSTALL_PREFIX`.
  2331. // Either we need to remove `CMAKE_INSTALL_PREFIX`, add
  2332. // `CMAKE_INSTALL_PREFIX`, or do nothing.
  2333. //
  2334. // When we need to remove `CMAKE_INSTALL_PREFIX` we remove the Nth occurrence
  2335. // of `CMAKE_INSTALL_PREFIX` from `CMAKE_SYSTEM_PREFIX_PATH`, where `N` is
  2336. // computed by `CMakeSystemSpecificInformation.cmake` while constructing
  2337. // `CMAKE_SYSTEM_PREFIX_PATH`. This ensures that if projects / toolchains
  2338. // have removed `CMAKE_INSTALL_PREFIX` from the list, we don't remove
  2339. // some other entry by mistake
  2340. long install_prefix_count = -1;
  2341. std::string install_path_to_remove;
  2342. if (cmValue to_skip = this->Makefile->GetDefinition(
  2343. "_CMAKE_SYSTEM_PREFIX_PATH_INSTALL_PREFIX_COUNT")) {
  2344. cmStrToLong(*to_skip, &install_prefix_count);
  2345. }
  2346. if (cmValue install_value = this->Makefile->GetDefinition(
  2347. "_CMAKE_SYSTEM_PREFIX_PATH_INSTALL_PREFIX_VALUE")) {
  2348. install_path_to_remove = *install_value;
  2349. }
  2350. if (remove_install_prefix && install_prefix_in_list &&
  2351. install_prefix_count > 0 && !install_path_to_remove.empty()) {
  2352. cmValue prefix_paths =
  2353. this->Makefile->GetDefinition("CMAKE_SYSTEM_PREFIX_PATH");
  2354. // remove entry from CMAKE_SYSTEM_PREFIX_PATH
  2355. cmList expanded{ *prefix_paths };
  2356. long count = 0;
  2357. for (auto const& path : expanded) {
  2358. bool const to_add =
  2359. !(path == install_path_to_remove && ++count == install_prefix_count);
  2360. if (to_add) {
  2361. paths.AddPath(path);
  2362. }
  2363. }
  2364. } else if (add_install_prefix && !install_prefix_in_list) {
  2365. paths.AddCMakePath("CMAKE_INSTALL_PREFIX");
  2366. paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
  2367. } else {
  2368. // Otherwise the current setup of `CMAKE_SYSTEM_PREFIX_PATH` is correct
  2369. paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
  2370. }
  2371. paths.AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
  2372. paths.AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
  2373. if (this->DebugMode) {
  2374. std::string debugBuffer = "CMake variables defined in the Platform file "
  2375. "[CMAKE_FIND_USE_CMAKE_SYSTEM_PATH].\n";
  2376. collectPathsForDebug(debugBuffer, paths);
  2377. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2378. }
  2379. }
  2380. void cmFindPackageCommand::FillPrefixesUserGuess()
  2381. {
  2382. cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
  2383. for (std::string const& p : this->UserGuessArgs) {
  2384. paths.AddUserPath(p);
  2385. }
  2386. if (this->DebugMode) {
  2387. std::string debugBuffer =
  2388. "Paths specified by the find_package PATHS option.\n";
  2389. collectPathsForDebug(debugBuffer, paths);
  2390. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2391. }
  2392. }
  2393. void cmFindPackageCommand::FillPrefixesUserHints()
  2394. {
  2395. cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
  2396. for (std::string const& p : this->UserHintsArgs) {
  2397. paths.AddUserPath(p);
  2398. }
  2399. if (this->DebugMode) {
  2400. std::string debugBuffer =
  2401. "Paths specified by the find_package HINTS option.\n";
  2402. collectPathsForDebug(debugBuffer, paths);
  2403. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2404. }
  2405. }
  2406. bool cmFindPackageCommand::SearchDirectory(std::string const& dir,
  2407. PackageDescriptionType type)
  2408. {
  2409. assert(!dir.empty() && dir.back() == '/');
  2410. // Check each path suffix on this directory.
  2411. for (std::string const& s : this->SearchPathSuffixes) {
  2412. std::string d = dir;
  2413. if (!s.empty()) {
  2414. d += s;
  2415. d += '/';
  2416. }
  2417. if (this->CheckDirectory(d, type)) {
  2418. return true;
  2419. }
  2420. }
  2421. return false;
  2422. }
  2423. bool cmFindPackageCommand::CheckDirectory(std::string const& dir,
  2424. PackageDescriptionType type)
  2425. {
  2426. assert(!dir.empty() && dir.back() == '/');
  2427. std::string const d = dir.substr(0, dir.size() - 1);
  2428. if (cm::contains(this->IgnoredPaths, d)) {
  2429. return false;
  2430. }
  2431. // Look for the file in this directory.
  2432. std::string file;
  2433. if (this->FindConfigFile(d, type, file)) {
  2434. this->FileFound = std::move(file);
  2435. return true;
  2436. }
  2437. return false;
  2438. }
  2439. bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
  2440. PackageDescriptionType type,
  2441. std::string& file)
  2442. {
  2443. for (auto const& config : this->Configs) {
  2444. if (type != pdt::Any && config.Type != type) {
  2445. continue;
  2446. }
  2447. file = cmStrCat(dir, '/', config.Name);
  2448. if (this->DebugMode) {
  2449. this->DebugBuffer = cmStrCat(this->DebugBuffer, " ", file, '\n');
  2450. }
  2451. if (cmSystemTools::FileExists(file, true) && this->CheckVersion(file)) {
  2452. // Allow resolving symlinks when the config file is found through a link
  2453. if (this->UseRealPath) {
  2454. file = cmSystemTools::GetRealPath(file);
  2455. } else {
  2456. file = cmSystemTools::ToNormalizedPathOnDisk(file);
  2457. }
  2458. return true;
  2459. }
  2460. }
  2461. return false;
  2462. }
  2463. bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
  2464. {
  2465. bool result = false; // by default, assume the version is not ok.
  2466. bool haveResult = false;
  2467. std::string version = "unknown";
  2468. // Get the file extension.
  2469. std::string::size_type pos = config_file.rfind('.');
  2470. std::string ext = cmSystemTools::LowerCase(config_file.substr(pos));
  2471. if (ext == ".cps"_s) {
  2472. std::unique_ptr<cmPackageInfoReader> reader =
  2473. cmPackageInfoReader::Read(config_file);
  2474. if (reader && reader->GetName() == this->Name) {
  2475. // Read version information.
  2476. cm::optional<std::string> cpsVersion = reader->GetVersion();
  2477. cm::optional<ParsedVersion> const& parsedVersion =
  2478. reader->ParseVersion(cpsVersion);
  2479. bool const hasVersion = cpsVersion.has_value();
  2480. // Test for version compatibility.
  2481. result = this->Version.empty();
  2482. if (hasVersion) {
  2483. version = std::move(*cpsVersion);
  2484. if (!this->Version.empty()) {
  2485. if (!parsedVersion) {
  2486. // If we don't understand the version, compare the exact versions
  2487. // using full string comparison. This is the correct behavior for
  2488. // the "custom" schema, and the best we can do otherwise.
  2489. result = (this->Version == version);
  2490. } else if (this->VersionExact) {
  2491. // If EXACT is specified, the version must be exactly the requested
  2492. // version.
  2493. result =
  2494. cmSystemTools::VersionCompareEqual(this->Version, version);
  2495. } else {
  2496. // Do we have a compat_version?
  2497. cm::optional<std::string> const& compatVersion =
  2498. reader->GetCompatVersion();
  2499. if (reader->ParseVersion(compatVersion)) {
  2500. // If yes, the initial result is whether the requested version is
  2501. // between the actual version and the compat version, inclusive.
  2502. result = cmSystemTools::VersionCompareGreaterEq(version,
  2503. this->Version) &&
  2504. cmSystemTools::VersionCompareGreaterEq(this->Version,
  2505. *compatVersion);
  2506. if (result && !this->VersionMax.empty()) {
  2507. // We must also check that the version is less than the version
  2508. // limit.
  2509. if (this->VersionRangeMax == VERSION_ENDPOINT_EXCLUDED) {
  2510. result = cmSystemTools::VersionCompareGreater(
  2511. this->VersionMax, version);
  2512. } else {
  2513. result = cmSystemTools::VersionCompareGreaterEq(
  2514. this->VersionMax, version);
  2515. }
  2516. }
  2517. } else {
  2518. // If no, compat_version is assumed to be exactly the actual
  2519. // version, so the result is whether the requested version is
  2520. // exactly the actual version, and we can ignore the version
  2521. // limit.
  2522. result =
  2523. cmSystemTools::VersionCompareEqual(this->Version, version);
  2524. }
  2525. }
  2526. }
  2527. }
  2528. if (result) {
  2529. // Locate appendices.
  2530. cmFindPackageCommand::AppendixMap appendices =
  2531. this->FindAppendices(config_file, *reader);
  2532. // Collect available components.
  2533. std::set<std::string> allComponents;
  2534. std::vector<std::string> const& rootComponents =
  2535. reader->GetComponentNames();
  2536. allComponents.insert(rootComponents.begin(), rootComponents.end());
  2537. for (auto const& appendix : appendices) {
  2538. allComponents.insert(appendix.second.Components.begin(),
  2539. appendix.second.Components.end());
  2540. }
  2541. // Verify that all required components are available.
  2542. std::set<std::string> requiredComponents = this->RequiredComponents;
  2543. requiredComponents.insert(this->RequiredTargets.begin(),
  2544. this->RequiredTargets.end());
  2545. std::vector<std::string> missingComponents;
  2546. std::set_difference(requiredComponents.begin(),
  2547. requiredComponents.end(), allComponents.begin(),
  2548. allComponents.end(),
  2549. std::back_inserter(missingComponents));
  2550. if (!missingComponents.empty()) {
  2551. result = false;
  2552. }
  2553. if (result && hasVersion) {
  2554. this->VersionFound = version;
  2555. if (parsedVersion) {
  2556. std::vector<unsigned> const& versionParts =
  2557. parsedVersion->ReleaseComponents;
  2558. this->VersionFoundCount =
  2559. static_cast<unsigned>(versionParts.size());
  2560. switch (std::min(this->VersionFoundCount, 4u)) {
  2561. case 4:
  2562. this->VersionFoundTweak = versionParts[3];
  2563. CM_FALLTHROUGH;
  2564. case 3:
  2565. this->VersionFoundPatch = versionParts[2];
  2566. CM_FALLTHROUGH;
  2567. case 2:
  2568. this->VersionFoundMinor = versionParts[1];
  2569. CM_FALLTHROUGH;
  2570. case 1:
  2571. this->VersionFoundMajor = versionParts[0];
  2572. CM_FALLTHROUGH;
  2573. default:
  2574. break;
  2575. }
  2576. } else {
  2577. this->VersionFoundCount = 0;
  2578. }
  2579. }
  2580. this->CpsReader = std::move(reader);
  2581. this->CpsAppendices = std::move(appendices);
  2582. this->RequiredComponents = std::move(requiredComponents);
  2583. }
  2584. }
  2585. } else {
  2586. // Get the filename without the .cmake extension.
  2587. std::string version_file_base = config_file.substr(0, pos);
  2588. // Look for foo-config-version.cmake
  2589. std::string version_file = cmStrCat(version_file_base, "-version.cmake");
  2590. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  2591. result = this->CheckVersionFile(version_file, version);
  2592. haveResult = true;
  2593. }
  2594. // Look for fooConfigVersion.cmake
  2595. version_file = cmStrCat(version_file_base, "Version.cmake");
  2596. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  2597. result = this->CheckVersionFile(version_file, version);
  2598. haveResult = true;
  2599. }
  2600. // If no version was requested a versionless package is acceptable.
  2601. if (!haveResult && this->Version.empty()) {
  2602. result = true;
  2603. }
  2604. }
  2605. ConfigFileInfo configFileInfo;
  2606. configFileInfo.filename = config_file;
  2607. configFileInfo.version = version;
  2608. this->ConsideredConfigs.push_back(std::move(configFileInfo));
  2609. return result;
  2610. }
  2611. bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file,
  2612. std::string& result_version)
  2613. {
  2614. // The version file will be loaded in an isolated scope.
  2615. cmMakefile::ScopePushPop const varScope(this->Makefile);
  2616. cmMakefile::PolicyPushPop const polScope(this->Makefile);
  2617. static_cast<void>(varScope);
  2618. static_cast<void>(polScope);
  2619. // Clear the output variables.
  2620. this->Makefile->RemoveDefinition("PACKAGE_VERSION");
  2621. this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
  2622. this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
  2623. this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
  2624. // Set the input variables.
  2625. this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name);
  2626. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COMPLETE",
  2627. this->VersionComplete);
  2628. auto addDefinition = [this](std::string const& variable,
  2629. cm::string_view value) {
  2630. this->Makefile->AddDefinition(variable, value);
  2631. };
  2632. this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION",
  2633. this->Version, this->VersionCount,
  2634. this->VersionMajor, this->VersionMinor,
  2635. this->VersionPatch, this->VersionTweak);
  2636. if (!this->VersionRange.empty()) {
  2637. this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION_MIN",
  2638. this->Version, this->VersionCount,
  2639. this->VersionMajor, this->VersionMinor,
  2640. this->VersionPatch, this->VersionTweak);
  2641. this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION_MAX",
  2642. this->VersionMax, this->VersionMaxCount,
  2643. this->VersionMaxMajor, this->VersionMaxMinor,
  2644. this->VersionMaxPatch, this->VersionMaxTweak);
  2645. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE",
  2646. this->VersionComplete);
  2647. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE_MIN",
  2648. this->VersionRangeMin);
  2649. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE_MAX",
  2650. this->VersionRangeMax);
  2651. }
  2652. // Load the version check file.
  2653. // Pass NoPolicyScope because we do our own policy push/pop.
  2654. bool suitable = false;
  2655. if (this->ReadListFile(version_file, NoPolicyScope)) {
  2656. // Check the output variables.
  2657. bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
  2658. bool const unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
  2659. if (!okay && !this->VersionExact) {
  2660. okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
  2661. }
  2662. // The package is suitable if the version is okay and not
  2663. // explicitly unsuitable.
  2664. suitable = !unsuitable && (okay || this->Version.empty());
  2665. if (suitable) {
  2666. // Get the version found.
  2667. this->VersionFound =
  2668. this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  2669. // Try to parse the version number and store the results that were
  2670. // successfully parsed.
  2671. unsigned int parsed_major;
  2672. unsigned int parsed_minor;
  2673. unsigned int parsed_patch;
  2674. unsigned int parsed_tweak;
  2675. this->VersionFoundCount =
  2676. parseVersion(this->VersionFound, parsed_major, parsed_minor,
  2677. parsed_patch, parsed_tweak);
  2678. switch (this->VersionFoundCount) {
  2679. case 4:
  2680. this->VersionFoundTweak = parsed_tweak;
  2681. CM_FALLTHROUGH;
  2682. case 3:
  2683. this->VersionFoundPatch = parsed_patch;
  2684. CM_FALLTHROUGH;
  2685. case 2:
  2686. this->VersionFoundMinor = parsed_minor;
  2687. CM_FALLTHROUGH;
  2688. case 1:
  2689. this->VersionFoundMajor = parsed_major;
  2690. CM_FALLTHROUGH;
  2691. default:
  2692. break;
  2693. }
  2694. }
  2695. }
  2696. result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  2697. if (result_version.empty()) {
  2698. result_version = "unknown";
  2699. }
  2700. // Succeed if the version is suitable.
  2701. return suitable;
  2702. }
  2703. void cmFindPackageCommand::StoreVersionFound()
  2704. {
  2705. // Store the whole version string.
  2706. std::string const ver = cmStrCat(this->Name, "_VERSION");
  2707. auto addDefinition = [this](std::string const& variable,
  2708. cm::string_view value) {
  2709. this->Makefile->AddDefinition(variable, value);
  2710. };
  2711. this->SetVersionVariables(addDefinition, ver, this->VersionFound,
  2712. this->VersionFoundCount, this->VersionFoundMajor,
  2713. this->VersionFoundMinor, this->VersionFoundPatch,
  2714. this->VersionFoundTweak);
  2715. if (this->VersionFound.empty()) {
  2716. this->Makefile->RemoveDefinition(ver);
  2717. }
  2718. }
  2719. bool cmFindPackageCommand::SearchPrefix(std::string const& prefix)
  2720. {
  2721. assert(!prefix.empty() && prefix.back() == '/');
  2722. // Skip this if the prefix does not exist.
  2723. if (!cmSystemTools::FileIsDirectory(prefix)) {
  2724. return false;
  2725. }
  2726. // Skip this if it's in ignored paths.
  2727. std::string prefixWithoutSlash = prefix;
  2728. if (prefixWithoutSlash != "/" && prefixWithoutSlash.back() == '/') {
  2729. prefixWithoutSlash.erase(prefixWithoutSlash.length() - 1);
  2730. }
  2731. if (this->IgnoredPaths.count(prefixWithoutSlash) ||
  2732. this->IgnoredPrefixPaths.count(prefixWithoutSlash)) {
  2733. return false;
  2734. }
  2735. auto searchFn = [this](std::string const& fullPath,
  2736. PackageDescriptionType type) -> bool {
  2737. return this->SearchDirectory(fullPath, type);
  2738. };
  2739. auto iCpsGen = cmCaseInsensitiveDirectoryListGenerator{ "cps"_s };
  2740. auto iCMakeGen = cmCaseInsensitiveDirectoryListGenerator{ "cmake"_s };
  2741. auto anyDirGen =
  2742. cmAnyDirectoryListGenerator{ this->SortOrder, this->SortDirection };
  2743. auto cpsPkgDirGen =
  2744. cmProjectDirectoryListGenerator{ &this->Names, this->SortOrder,
  2745. this->SortDirection, true };
  2746. auto cmakePkgDirGen =
  2747. cmProjectDirectoryListGenerator{ &this->Names, this->SortOrder,
  2748. this->SortDirection, false };
  2749. // PREFIX/(Foo|foo|FOO)/(cps|CPS)/
  2750. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, cpsPkgDirGen, iCpsGen)) {
  2751. return true;
  2752. }
  2753. // PREFIX/(Foo|foo|FOO)/*/(cps|CPS)/
  2754. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, cpsPkgDirGen, iCpsGen,
  2755. anyDirGen)) {
  2756. return true;
  2757. }
  2758. // PREFIX/(cps|CPS)/(Foo|foo|FOO)/
  2759. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, iCpsGen, cpsPkgDirGen)) {
  2760. return true;
  2761. }
  2762. // PREFIX/(cps|CPS)/(Foo|foo|FOO)/*/
  2763. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, iCpsGen, cpsPkgDirGen,
  2764. anyDirGen)) {
  2765. return true;
  2766. }
  2767. // PREFIX/(cps|CPS)/ (useful on windows or in build trees)
  2768. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, iCpsGen)) {
  2769. return true;
  2770. }
  2771. // PREFIX/ (useful on windows or in build trees)
  2772. if (this->SearchDirectory(prefix, pdt::CMake)) {
  2773. return true;
  2774. }
  2775. // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
  2776. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, iCMakeGen)) {
  2777. return true;
  2778. }
  2779. // PREFIX/(Foo|foo|FOO).*/
  2780. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, cmakePkgDirGen)) {
  2781. return true;
  2782. }
  2783. // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
  2784. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, cmakePkgDirGen,
  2785. iCMakeGen)) {
  2786. return true;
  2787. }
  2788. auto secondPkgDirGen =
  2789. cmProjectDirectoryListGenerator{ &this->Names, this->SortOrder,
  2790. this->SortDirection, false };
  2791. // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/(Foo|foo|FOO).*/
  2792. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, cmakePkgDirGen,
  2793. iCMakeGen, secondPkgDirGen)) {
  2794. return true;
  2795. }
  2796. // Construct list of common install locations (lib and share).
  2797. std::vector<cm::string_view> common;
  2798. std::string libArch;
  2799. if (!this->LibraryArchitecture.empty()) {
  2800. libArch = "lib/" + this->LibraryArchitecture;
  2801. common.emplace_back(libArch);
  2802. }
  2803. if (this->UseLib32Paths) {
  2804. common.emplace_back("lib32"_s);
  2805. }
  2806. if (this->UseLib64Paths) {
  2807. common.emplace_back("lib64"_s);
  2808. }
  2809. if (this->UseLibx32Paths) {
  2810. common.emplace_back("libx32"_s);
  2811. }
  2812. common.emplace_back("lib"_s);
  2813. common.emplace_back("share"_s);
  2814. auto commonGen = cmEnumPathSegmentsGenerator{ common };
  2815. auto cmakeGen = cmAppendPathSegmentGenerator{ "cmake"_s };
  2816. auto cpsGen = cmAppendPathSegmentGenerator{ "cps"_s };
  2817. // PREFIX/(lib/ARCH|lib*|share)/cps/(Foo|foo|FOO)/
  2818. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, commonGen, cpsGen,
  2819. cpsPkgDirGen)) {
  2820. return true;
  2821. }
  2822. // PREFIX/(lib/ARCH|lib*|share)/cps/(Foo|foo|FOO)/*/
  2823. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, commonGen, cpsGen,
  2824. cpsPkgDirGen, anyDirGen)) {
  2825. return true;
  2826. }
  2827. // PREFIX/(lib/ARCH|lib*|share)/cps/
  2828. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, commonGen, cpsGen)) {
  2829. return true;
  2830. }
  2831. // PREFIX/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  2832. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, commonGen, cmakeGen,
  2833. cmakePkgDirGen)) {
  2834. return true;
  2835. }
  2836. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  2837. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, commonGen,
  2838. cmakePkgDirGen)) {
  2839. return true;
  2840. }
  2841. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  2842. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, commonGen,
  2843. cmakePkgDirGen, iCMakeGen)) {
  2844. return true;
  2845. }
  2846. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  2847. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, cmakePkgDirGen,
  2848. commonGen, cmakeGen, secondPkgDirGen)) {
  2849. return true;
  2850. }
  2851. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  2852. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, cmakePkgDirGen,
  2853. commonGen, secondPkgDirGen)) {
  2854. return true;
  2855. }
  2856. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  2857. return TryGeneratedPaths(searchFn, pdt::CMake, prefix, cmakePkgDirGen,
  2858. commonGen, secondPkgDirGen, iCMakeGen);
  2859. }
  2860. bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix)
  2861. {
  2862. assert(!prefix.empty() && prefix.back() == '/');
  2863. auto searchFn = [this](std::string const& fullPath,
  2864. PackageDescriptionType type) -> bool {
  2865. return this->SearchDirectory(fullPath, type);
  2866. };
  2867. auto iCMakeGen = cmCaseInsensitiveDirectoryListGenerator{ "cmake"_s };
  2868. auto iCpsGen = cmCaseInsensitiveDirectoryListGenerator{ "cps"_s };
  2869. auto fwGen =
  2870. cmMacProjectDirectoryListGenerator{ &this->Names, ".framework"_s };
  2871. auto rGen = cmAppendPathSegmentGenerator{ "Resources"_s };
  2872. auto vGen = cmAppendPathSegmentGenerator{ "Versions"_s };
  2873. auto anyGen =
  2874. cmAnyDirectoryListGenerator{ this->SortOrder, this->SortDirection };
  2875. // <prefix>/Foo.framework/Versions/*/Resources/CPS/
  2876. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, fwGen, vGen, anyGen, rGen,
  2877. iCpsGen)) {
  2878. return true;
  2879. }
  2880. // <prefix>/Foo.framework/Resources/CPS/
  2881. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, fwGen, rGen, iCpsGen)) {
  2882. return true;
  2883. }
  2884. // <prefix>/Foo.framework/Resources/
  2885. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, fwGen, rGen)) {
  2886. return true;
  2887. }
  2888. // <prefix>/Foo.framework/Resources/CMake/
  2889. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, fwGen, rGen,
  2890. iCMakeGen)) {
  2891. return true;
  2892. }
  2893. // <prefix>/Foo.framework/Versions/*/Resources/
  2894. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, fwGen, vGen, anyGen,
  2895. rGen)) {
  2896. return true;
  2897. }
  2898. // <prefix>/Foo.framework/Versions/*/Resources/CMake/
  2899. return TryGeneratedPaths(searchFn, pdt::CMake, prefix, fwGen, vGen, anyGen,
  2900. rGen, iCMakeGen);
  2901. }
  2902. bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix)
  2903. {
  2904. assert(!prefix.empty() && prefix.back() == '/');
  2905. auto searchFn = [this](std::string const& fullPath,
  2906. PackageDescriptionType type) -> bool {
  2907. return this->SearchDirectory(fullPath, type);
  2908. };
  2909. auto appGen = cmMacProjectDirectoryListGenerator{ &this->Names, ".app"_s };
  2910. auto crGen = cmAppendPathSegmentGenerator{ "Contents/Resources"_s };
  2911. // <prefix>/Foo.app/Contents/Resources/CPS/
  2912. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, appGen, crGen,
  2913. cmCaseInsensitiveDirectoryListGenerator{ "cps"_s })) {
  2914. return true;
  2915. }
  2916. // <prefix>/Foo.app/Contents/Resources/
  2917. if (TryGeneratedPaths(searchFn, pdt::CMake, prefix, appGen, crGen)) {
  2918. return true;
  2919. }
  2920. // <prefix>/Foo.app/Contents/Resources/CMake/
  2921. return TryGeneratedPaths(
  2922. searchFn, pdt::CMake, prefix, appGen, crGen,
  2923. cmCaseInsensitiveDirectoryListGenerator{ "cmake"_s });
  2924. }
  2925. bool cmFindPackageCommand::SearchEnvironmentPrefix(std::string const& prefix)
  2926. {
  2927. assert(!prefix.empty() && prefix.back() == '/');
  2928. // Skip this if the prefix does not exist.
  2929. if (!cmSystemTools::FileIsDirectory(prefix)) {
  2930. return false;
  2931. }
  2932. auto searchFn = [this](std::string const& fullPath,
  2933. PackageDescriptionType type) -> bool {
  2934. return this->SearchDirectory(fullPath, type);
  2935. };
  2936. auto pkgDirGen =
  2937. cmProjectDirectoryListGenerator{ &this->Names, this->SortOrder,
  2938. this->SortDirection, true };
  2939. // <environment-path>/(Foo|foo|FOO)/cps/
  2940. if (TryGeneratedPaths(searchFn, pdt::Cps, prefix, pkgDirGen,
  2941. cmAppendPathSegmentGenerator{ "cps"_s })) {
  2942. return true;
  2943. }
  2944. // <environment-path>/(Foo|foo|FOO)/
  2945. return TryGeneratedPaths(searchFn, pdt::Cps, prefix, pkgDirGen);
  2946. }
  2947. bool cmFindPackageCommand::IsRequired() const
  2948. {
  2949. return this->Required == RequiredStatus::RequiredExplicit ||
  2950. this->Required == RequiredStatus::RequiredFromPackageVar ||
  2951. this->Required == RequiredStatus::RequiredFromFindVar;
  2952. }
  2953. // TODO: Debug cmsys::Glob double slash problem.
  2954. bool cmFindPackage(std::vector<std::string> const& args,
  2955. cmExecutionStatus& status)
  2956. {
  2957. return cmFindPackageCommand(status).InitialPass(args);
  2958. }