1 /*============================================================================
2 CMake - Cross Platform Makefile Generator
3 Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
5 Distributed under the OSI-approved BSD License (the "License");
6 see accompanying file Copyright.txt for details.
8 This software is distributed WITHOUT ANY WARRANTY; without even the
9 implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the License for more information.
11 ============================================================================*/
12 #include "cmFindPackageCommand.h"
14 #include <cmsys/Directory.hxx>
15 #include <cmsys/RegularExpression.hxx>
17 #ifdef CMAKE_BUILD_WITH_CMAKE
18 #include "cmVariableWatch.h"
21 #if defined(__HAIKU__)
22 #include <StorageKit.h>
25 void cmFindPackageNeedBackwardsCompatibility(const std::string& variable,
26 int access_type, void*, const char* newValue,
30 #ifdef CMAKE_BUILD_WITH_CMAKE
31 if(access_type == cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS)
33 std::string message = "An attempt was made to access a variable: ";
36 " that has not been defined. This variable is created by the "
37 "FIND_PACKAGE command. CMake version 1.6 always converted the "
38 "variable name to upper-case, but this behavior is no longer the "
39 "case. To fix this you might need to set the cache value of "
40 "CMAKE_BACKWARDS_COMPATIBILITY to 1.6 or less. If you are writing a "
41 "CMake listfile, you should change the variable reference to use "
42 "the case of the argument to FIND_PACKAGE.";
43 cmSystemTools::Error(message.c_str());
51 //----------------------------------------------------------------------------
52 cmFindPackageCommand::cmFindPackageCommand()
54 this->CMakePathName = "PACKAGE";
56 this->Required = false;
57 this->NoUserRegistry = false;
58 this->NoSystemRegistry = false;
59 this->NoBuilds = false;
60 this->UseConfigFiles = true;
61 this->UseFindModules = true;
62 this->DebugMode = false;
63 this->UseLib64Paths = false;
64 this->PolicyScope = true;
65 this->VersionMajor = 0;
66 this->VersionMinor = 0;
67 this->VersionPatch = 0;
68 this->VersionTweak = 0;
69 this->VersionCount = 0;
70 this->VersionExact = false;
71 this->VersionFoundMajor = 0;
72 this->VersionFoundMinor = 0;
73 this->VersionFoundPatch = 0;
74 this->VersionFoundTweak = 0;
75 this->VersionFoundCount = 0;
76 this->RequiredCMakeVersion = 0;
79 //----------------------------------------------------------------------------
80 void cmFindPackageCommand::GenerateDocumentation()
82 this->cmFindCommon::GenerateDocumentation();
83 cmSystemTools::ReplaceString(this->GenericDocumentationRootPath,
84 "CMAKE_FIND_ROOT_PATH_MODE_XXX",
85 "CMAKE_FIND_ROOT_PATH_MODE_PACKAGE");
86 cmSystemTools::ReplaceString(this->GenericDocumentationPathsOrder,
87 "FIND_ARGS_XXX", "<package>");
88 cmSystemTools::ReplaceString(this->GenericDocumentationPathsOrder,
89 "FIND_XXX", "find_package");
90 this->CommandDocumentation =
91 " find_package(<package> [version] [EXACT] [QUIET] [MODULE]\n"
92 " [REQUIRED] [[COMPONENTS] [components...]]\n"
93 " [OPTIONAL_COMPONENTS components...]\n"
94 " [NO_POLICY_SCOPE])\n"
95 "Finds and loads settings from an external project. "
96 "<package>_FOUND will be set to indicate whether the package was found. "
97 "When the package is found package-specific information is provided "
98 "through variables and imported targets documented by the package "
100 "The QUIET option disables messages if the package cannot be found. "
101 "The MODULE option disables the second signature documented below. "
102 "The REQUIRED option stops processing with an error message if the "
103 "package cannot be found."
105 "A package-specific list of required components may be listed after the "
106 "COMPONENTS option (or after the REQUIRED option if present). "
107 "Additional optional components may be listed after OPTIONAL_COMPONENTS. "
108 "Available components and their influence on whether a package is "
109 "considered to be found are defined by the target package."
111 "The [version] argument requests a version with which the package found "
112 "should be compatible (format is major[.minor[.patch[.tweak]]]). "
113 "The EXACT option requests that the version be matched exactly. "
114 "If no [version] and/or component list is given to a recursive "
115 "invocation inside a find-module, the corresponding arguments "
116 "are forwarded automatically from the outer call (including the "
117 "EXACT flag for [version]). "
118 "Version support is currently provided only on a package-by-package "
119 "basis (details below).\n"
120 "User code should generally look for packages using the above simple "
121 "signature. The remainder of this command documentation specifies the "
122 "full command signature and details of the search process. Project "
123 "maintainers wishing to provide a package to be found by this command "
124 "are encouraged to read on.\n"
125 "The command has two modes by which it searches for packages: "
126 "\"Module\" mode and \"Config\" mode. "
127 "Module mode is available when the command is invoked with the above "
128 "reduced signature. "
129 "CMake searches for a file called \"Find<package>.cmake\" in "
130 "the CMAKE_MODULE_PATH followed by the CMake installation. "
131 "If the file is found, it is read and processed by CMake. "
132 "It is responsible for finding the package, checking the version, "
133 "and producing any needed messages. "
134 "Many find-modules provide limited or no support for versioning; "
135 "check the module documentation. "
136 "If no module is found and the MODULE option is not given the command "
137 "proceeds to Config mode.\n"
138 "The complete Config mode command signature is:\n"
139 " find_package(<package> [version] [EXACT] [QUIET]\n"
140 " [REQUIRED] [[COMPONENTS] [components...]]\n"
141 " [CONFIG|NO_MODULE]\n"
142 " [NO_POLICY_SCOPE]\n"
143 " [NAMES name1 [name2 ...]]\n"
144 " [CONFIGS config1 [config2 ...]]\n"
145 " [HINTS path1 [path2 ... ]]\n"
146 " [PATHS path1 [path2 ... ]]\n"
147 " [PATH_SUFFIXES suffix1 [suffix2 ...]]\n"
148 " [NO_DEFAULT_PATH]\n"
149 " [NO_CMAKE_ENVIRONMENT_PATH]\n"
151 " [NO_SYSTEM_ENVIRONMENT_PATH]\n"
152 " [NO_CMAKE_PACKAGE_REGISTRY]\n"
153 " [NO_CMAKE_BUILDS_PATH]\n"
154 " [NO_CMAKE_SYSTEM_PATH]\n"
155 " [NO_CMAKE_SYSTEM_PACKAGE_REGISTRY]\n"
156 " [CMAKE_FIND_ROOT_PATH_BOTH |\n"
157 " ONLY_CMAKE_FIND_ROOT_PATH |\n"
158 " NO_CMAKE_FIND_ROOT_PATH])\n"
159 "The CONFIG option may be used to skip Module mode explicitly and "
160 "switch to Config mode. It is synonymous to using NO_MODULE. "
161 "Config mode is also implied by use of options not specified in the "
162 "reduced signature. "
164 "Config mode attempts to locate a configuration file provided by the "
165 "package to be found. A cache entry called <package>_DIR is created to "
166 "hold the directory containing the file. "
167 "By default the command searches for a package with the name <package>. "
168 "If the NAMES option is given the names following it are used instead "
170 "The command searches for a file called \"<name>Config.cmake\" or "
171 "\"<lower-case-name>-config.cmake\" for each name specified. "
172 "A replacement set of possible configuration file names may be given "
173 "using the CONFIGS option. "
174 "The search procedure is specified below. Once found, the configuration "
175 "file is read and processed by CMake. Since the file is provided by the "
176 "package it already knows the location of package contents. "
177 "The full path to the configuration file is stored in the cmake "
178 "variable <package>_CONFIG."
180 "All configuration files which have been considered by CMake while "
181 "searching for an installation of the package with an appropriate "
182 "version are stored in the cmake variable <package>_CONSIDERED_CONFIGS, "
183 "the associated versions in <package>_CONSIDERED_VERSIONS. "
185 "If the package configuration file cannot be found CMake "
186 "will generate an error describing the problem unless the QUIET "
187 "argument is specified. If REQUIRED is specified and the package "
188 "is not found a fatal error is generated and the configure step stops "
189 "executing. If <package>_DIR has been set to a directory not containing "
190 "a configuration file CMake will ignore it and search from scratch."
192 "When the [version] argument is given Config mode will only find a "
193 "version of the package that claims compatibility with the requested "
194 "version (format is major[.minor[.patch[.tweak]]]). "
195 "If the EXACT option is given only a version of the package claiming "
196 "an exact match of the requested version may be found. "
197 "CMake does not establish any convention for the meaning of version "
199 "Package version numbers are checked by \"version\" files provided by "
200 "the packages themselves. "
201 "For a candidate package configuration file \"<config-file>.cmake\" the "
202 "corresponding version file is located next to it and named either "
203 "\"<config-file>-version.cmake\" or \"<config-file>Version.cmake\". "
204 "If no such version file is available then the configuration file "
205 "is assumed to not be compatible with any requested version. "
206 "A basic version file containing generic version matching code can be "
207 "created using the macro write_basic_package_version_file(), see its "
208 "documentation for more details. "
209 "When a version file is found it is loaded to check the requested "
211 "The version file is loaded in a nested scope in which the following "
212 "variables have been defined:\n"
213 " PACKAGE_FIND_NAME = the <package> name\n"
214 " PACKAGE_FIND_VERSION = full requested version string\n"
215 " PACKAGE_FIND_VERSION_MAJOR = major version if requested, else 0\n"
216 " PACKAGE_FIND_VERSION_MINOR = minor version if requested, else 0\n"
217 " PACKAGE_FIND_VERSION_PATCH = patch version if requested, else 0\n"
218 " PACKAGE_FIND_VERSION_TWEAK = tweak version if requested, else 0\n"
219 " PACKAGE_FIND_VERSION_COUNT = number of version components, 0 to 4\n"
220 "The version file checks whether it satisfies the requested version "
221 "and sets these variables:\n"
222 " PACKAGE_VERSION = full provided version string\n"
223 " PACKAGE_VERSION_EXACT = true if version is exact match\n"
224 " PACKAGE_VERSION_COMPATIBLE = true if version is compatible\n"
225 " PACKAGE_VERSION_UNSUITABLE = true if unsuitable as any version\n"
226 "These variables are checked by the find_package command to determine "
227 "whether the configuration file provides an acceptable version. "
228 "They are not available after the find_package call returns. "
229 "If the version is acceptable the following variables are set:\n"
230 " <package>_VERSION = full provided version string\n"
231 " <package>_VERSION_MAJOR = major version if provided, else 0\n"
232 " <package>_VERSION_MINOR = minor version if provided, else 0\n"
233 " <package>_VERSION_PATCH = patch version if provided, else 0\n"
234 " <package>_VERSION_TWEAK = tweak version if provided, else 0\n"
235 " <package>_VERSION_COUNT = number of version components, 0 to 4\n"
236 "and the corresponding package configuration file is loaded. "
237 "When multiple package configuration files are available whose version "
238 "files claim compatibility with the version requested it is unspecified "
239 "which one is chosen. "
240 "No attempt is made to choose a highest or closest version number."
242 "Config mode provides an elaborate interface and search procedure. "
243 "Much of the interface is provided for completeness and for use "
244 "internally by find-modules loaded by Module mode. "
245 "Most user code should simply call\n"
246 " find_package(<package> [major[.minor]] [EXACT] [REQUIRED|QUIET])\n"
247 "in order to find a package. Package maintainers providing CMake "
248 "package configuration files are encouraged to name and install "
249 "them such that the procedure outlined below will find them "
250 "without requiring use of additional options."
252 "CMake constructs a set of possible installation prefixes for the "
253 "package. Under each prefix several directories are searched for a "
254 "configuration file. The tables below show the directories searched. "
255 "Each entry is meant for installation trees following Windows (W), "
256 "UNIX (U), or Apple (A) conventions.\n"
258 " <prefix>/(cmake|CMake)/ (W)\n"
259 " <prefix>/<name>*/ (W)\n"
260 " <prefix>/<name>*/(cmake|CMake)/ (W)\n"
261 " <prefix>/(lib/<arch>|lib|share)/cmake/<name>*/ (U)\n"
262 " <prefix>/(lib/<arch>|lib|share)/<name>*/ (U)\n"
263 " <prefix>/(lib/<arch>|lib|share)/<name>*/(cmake|CMake)/ (U)\n"
264 "On systems supporting OS X Frameworks and Application Bundles "
265 "the following directories are searched for frameworks or bundles "
266 "containing a configuration file:\n"
267 " <prefix>/<name>.framework/Resources/ (A)\n"
268 " <prefix>/<name>.framework/Resources/CMake/ (A)\n"
269 " <prefix>/<name>.framework/Versions/*/Resources/ (A)\n"
270 " <prefix>/<name>.framework/Versions/*/Resources/CMake/ (A)\n"
271 " <prefix>/<name>.app/Contents/Resources/ (A)\n"
272 " <prefix>/<name>.app/Contents/Resources/CMake/ (A)\n"
273 "In all cases the <name> is treated as case-insensitive and corresponds "
274 "to any of the names specified (<package> or names given by NAMES). "
275 "Paths with lib/<arch> are enabled if CMAKE_LIBRARY_ARCHITECTURE is set. "
276 "If PATH_SUFFIXES is specified the suffixes are appended to each "
277 "(W) or (U) directory entry one-by-one.\n"
278 "This set of directories is intended to work in cooperation with "
279 "projects that provide configuration files in their installation trees. "
280 "Directories above marked with (W) are intended for installations on "
281 "Windows where the prefix may point at the top of an application's "
282 "installation directory. Those marked with (U) are intended for "
283 "installations on UNIX platforms where the prefix is shared by "
284 "multiple packages. This is merely a convention, so all (W) and (U) "
285 "directories are still searched on all platforms. "
286 "Directories marked with (A) are intended for installations on "
287 "Apple platforms. The cmake variables CMAKE_FIND_FRAMEWORK and "
288 "CMAKE_FIND_APPBUNDLE determine the order of preference "
289 "as specified below.\n"
290 "The set of installation prefixes is constructed using the following "
291 "steps. If NO_DEFAULT_PATH is specified all NO_* options are enabled.\n"
292 "1. Search paths specified in cmake-specific cache variables. "
293 "These are intended to be used on the command line with a -DVAR=value. "
294 "This can be skipped if NO_CMAKE_PATH is passed.\n"
295 " CMAKE_PREFIX_PATH\n"
296 " CMAKE_FRAMEWORK_PATH\n"
297 " CMAKE_APPBUNDLE_PATH\n"
298 "2. Search paths specified in cmake-specific environment variables. "
299 "These are intended to be set in the user's shell configuration. "
300 "This can be skipped if NO_CMAKE_ENVIRONMENT_PATH is passed.\n"
302 " CMAKE_PREFIX_PATH\n"
303 " CMAKE_FRAMEWORK_PATH\n"
304 " CMAKE_APPBUNDLE_PATH\n"
305 "3. Search paths specified by the HINTS option. "
306 "These should be paths computed by system introspection, such as a "
307 "hint provided by the location of another item already found. "
308 "Hard-coded guesses should be specified with the PATHS option.\n"
309 "4. Search the standard system environment variables. "
310 "This can be skipped if NO_SYSTEM_ENVIRONMENT_PATH is passed. "
311 "Path entries ending in \"/bin\" or \"/sbin\" are automatically "
312 "converted to their parent directories.\n"
314 "5. Search project build trees recently configured in a CMake GUI. "
315 "This can be skipped if NO_CMAKE_BUILDS_PATH is passed. "
316 "It is intended for the case when a user is building multiple "
317 "dependent projects one after another.\n"
318 "6. Search paths stored in the CMake user package registry. "
319 "This can be skipped if NO_CMAKE_PACKAGE_REGISTRY is passed. "
320 "On Windows a <package> may appear under registry key\n"
321 " HKEY_CURRENT_USER\\Software\\Kitware\\CMake\\Packages\\<package>\n"
322 "as a REG_SZ value, with arbitrary name, that specifies the directory "
323 "containing the package configuration file. "
324 "On UNIX platforms a <package> may appear under the directory\n"
325 " ~/.cmake/packages/<package>\n"
326 "as a file, with arbitrary name, whose content specifies the directory "
327 "containing the package configuration file. "
328 "See the export(PACKAGE) command to create user package registry entries "
329 "for project build trees."
331 "7. Search cmake variables defined in the Platform files "
332 "for the current system. This can be skipped if NO_CMAKE_SYSTEM_PATH "
334 " CMAKE_SYSTEM_PREFIX_PATH\n"
335 " CMAKE_SYSTEM_FRAMEWORK_PATH\n"
336 " CMAKE_SYSTEM_APPBUNDLE_PATH\n"
337 "8. Search paths stored in the CMake system package registry. "
338 "This can be skipped if NO_CMAKE_SYSTEM_PACKAGE_REGISTRY is passed. "
339 "On Windows a <package> may appear under registry key\n"
340 " HKEY_LOCAL_MACHINE\\Software\\Kitware\\CMake\\Packages\\<package>\n"
341 "as a REG_SZ value, with arbitrary name, that specifies the directory "
342 "containing the package configuration file. "
343 "There is no system package registry on non-Windows platforms."
345 "9. Search paths specified by the PATHS option. "
346 "These are typically hard-coded guesses.\n"
348 this->CommandDocumentation += this->GenericDocumentationMacPolicy;
349 this->CommandDocumentation += this->GenericDocumentationRootPath;
350 this->CommandDocumentation += this->GenericDocumentationPathsOrder;
351 this->CommandDocumentation +=
353 "Every non-REQUIRED find_package() call can be disabled by setting the "
354 "variable CMAKE_DISABLE_FIND_PACKAGE_<package> to TRUE. See the "
355 "documentation for the CMAKE_DISABLE_FIND_PACKAGE_<package> variable for "
356 "more information.\n"
357 "When loading a find module or package configuration file find_package "
358 "defines variables to provide information about the call arguments "
359 "(and restores their original state before returning):\n"
360 " <package>_FIND_REQUIRED = true if REQUIRED option was given\n"
361 " <package>_FIND_QUIETLY = true if QUIET option was given\n"
362 " <package>_FIND_VERSION = full requested version string\n"
363 " <package>_FIND_VERSION_MAJOR = major version if requested, else 0\n"
364 " <package>_FIND_VERSION_MINOR = minor version if requested, else 0\n"
365 " <package>_FIND_VERSION_PATCH = patch version if requested, else 0\n"
366 " <package>_FIND_VERSION_TWEAK = tweak version if requested, else 0\n"
367 " <package>_FIND_VERSION_COUNT = number of version components, 0 to 4\n"
368 " <package>_FIND_VERSION_EXACT = true if EXACT option was given\n"
369 " <package>_FIND_COMPONENTS = list of requested components\n"
370 " <package>_FIND_REQUIRED_<c> = true if component <c> is required\n"
371 " false if component <c> is optional\n"
372 "In Module mode the loaded find module is responsible to honor the "
373 "request detailed by these variables; see the find module for details. "
374 "In Config mode find_package handles REQUIRED, QUIET, and version "
375 "options automatically but leaves it to the package configuration file "
376 "to handle components in a way that makes sense for the package. "
377 "The package configuration file may set <package>_FOUND to false "
378 "to tell find_package that component requirements are not satisfied."
380 "See the cmake_policy() command documentation for discussion of the "
381 "NO_POLICY_SCOPE option."
385 //----------------------------------------------------------------------------
386 const char* cmFindPackageCommand::GetFullDocumentation() const
388 if(this->CommandDocumentation.empty())
390 const_cast<cmFindPackageCommand *>(this)->GenerateDocumentation();
392 return this->CommandDocumentation.c_str();
395 //----------------------------------------------------------------------------
396 bool cmFindPackageCommand
397 ::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
401 this->SetError("called with incorrect number of arguments");
405 // Lookup required version of CMake.
407 this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION"))
409 unsigned int v[3] = {0,0,0};
410 sscanf(rv, "%u.%u.%u", &v[0], &v[1], &v[2]);
411 this->RequiredCMakeVersion = CMake_VERSION_ENCODE(v[0],v[1],v[2]);
414 // Check for debug mode.
415 this->DebugMode = this->Makefile->IsOn("CMAKE_FIND_DEBUG_MODE");
417 // Lookup target architecture, if any.
418 if(const char* arch =
419 this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE"))
421 this->LibraryArchitecture = arch;
424 // Lookup whether lib64 paths should be used.
425 if(this->Makefile->PlatformIs64Bit() &&
426 this->Makefile->GetCMakeInstance()
427 ->GetPropertyAsBool("FIND_LIBRARY_USE_LIB64_PATHS"))
429 this->UseLib64Paths = true;
432 // Find the current root path mode.
433 this->SelectDefaultRootPathMode();
435 // Find the current bundle/framework search policy.
436 this->SelectDefaultMacMode();
439 this->Name = args[0];
440 std::string components;
441 const char* components_sep = "";
442 std::set<std::string> requiredComponents;
443 std::set<std::string> optionalComponents;
445 // Check ancient compatibility.
446 this->Compatibility_1_6 =
447 this->Makefile->GetLocalGenerator()
448 ->NeedBackwardsCompatibility(1, 6);
450 // Always search directly in a generated path.
451 this->SearchPathSuffixes.push_back("");
453 // Parse the arguments.
454 enum Doing { DoingNone, DoingComponents, DoingOptionalComponents, DoingNames,
455 DoingPaths, DoingPathSuffixes, DoingConfigs, DoingHints };
456 Doing doing = DoingNone;
457 cmsys::RegularExpression version("^[0-9.]+$");
458 bool haveVersion = false;
459 std::set<unsigned int> configArgs;
460 std::set<unsigned int> moduleArgs;
461 for(unsigned int i=1; i < args.size(); ++i)
463 if(args[i] == "QUIET")
468 else if(args[i] == "EXACT")
470 this->VersionExact = true;
471 this->Compatibility_1_6 = false;
474 else if(args[i] == "MODULE")
476 moduleArgs.insert(i);
479 else if(args[i] == "CONFIG")
481 configArgs.insert(i);
484 else if(args[i] == "NO_MODULE")
486 configArgs.insert(i);
489 else if(args[i] == "REQUIRED")
491 this->Required = true;
492 doing = DoingComponents;
494 else if(args[i] == "COMPONENTS")
496 this->Compatibility_1_6 = false;
497 doing = DoingComponents;
499 else if(args[i] == "OPTIONAL_COMPONENTS")
501 this->Compatibility_1_6 = false;
502 doing = DoingOptionalComponents;
504 else if(args[i] == "NAMES")
506 configArgs.insert(i);
507 this->Compatibility_1_6 = false;
510 else if(args[i] == "PATHS")
512 configArgs.insert(i);
513 this->Compatibility_1_6 = false;
516 else if(args[i] == "HINTS")
518 configArgs.insert(i);
519 this->Compatibility_1_6 = false;
522 else if(args[i] == "PATH_SUFFIXES")
524 configArgs.insert(i);
525 this->Compatibility_1_6 = false;
526 doing = DoingPathSuffixes;
528 else if(args[i] == "CONFIGS")
530 configArgs.insert(i);
531 this->Compatibility_1_6 = false;
532 doing = DoingConfigs;
534 else if(args[i] == "NO_POLICY_SCOPE")
536 this->PolicyScope = false;
537 this->Compatibility_1_6 = false;
540 else if(args[i] == "NO_CMAKE_PACKAGE_REGISTRY")
542 this->NoUserRegistry = true;
543 configArgs.insert(i);
544 this->Compatibility_1_6 = false;
547 else if(args[i] == "NO_CMAKE_SYSTEM_PACKAGE_REGISTRY")
549 this->NoSystemRegistry = true;
550 configArgs.insert(i);
551 this->Compatibility_1_6 = false;
554 else if(args[i] == "NO_CMAKE_BUILDS_PATH")
556 this->NoBuilds = true;
557 configArgs.insert(i);
558 this->Compatibility_1_6 = false;
561 else if(this->CheckCommonArgument(args[i]))
563 configArgs.insert(i);
564 this->Compatibility_1_6 = false;
567 else if((doing == DoingComponents) || (doing == DoingOptionalComponents))
569 // Set a variable telling the find script whether this component
571 const char* isRequired = "1";
572 if (doing == DoingOptionalComponents)
575 optionalComponents.insert(args[i]);
579 requiredComponents.insert(args[i]);
582 std::string req_var = this->Name + "_FIND_REQUIRED_" + args[i];
583 this->AddFindDefinition(req_var.c_str(), isRequired);
585 // Append to the list of required components.
586 components += components_sep;
587 components += args[i];
588 components_sep = ";";
590 else if(doing == DoingNames)
592 this->Names.push_back(args[i]);
594 else if(doing == DoingPaths)
596 this->AddUserPath(args[i], this->UserPaths);
598 else if(doing == DoingHints)
600 this->AddUserPath(args[i], this->UserHints);
602 else if(doing == DoingPathSuffixes)
604 this->AddPathSuffix(args[i]);
606 else if(doing == DoingConfigs)
608 if(args[i].find_first_of(":/\\") != args[i].npos ||
609 cmSystemTools::GetFilenameLastExtension(args[i]) != ".cmake")
612 e << "given CONFIGS option followed by invalid file name \""
613 << args[i] << "\". The names given must be file names without "
614 << "a path and with a \".cmake\" extension.";
615 this->SetError(e.str().c_str());
618 this->Configs.push_back(args[i]);
620 else if(!haveVersion && version.find(args[i].c_str()))
623 this->Version = args[i];
628 e << "called with invalid argument \"" << args[i].c_str() << "\"";
629 this->SetError(e.str().c_str());
634 std::vector<std::string> doubledComponents;
635 std::set_intersection(requiredComponents.begin(), requiredComponents.end(),
636 optionalComponents.begin(), optionalComponents.end(),
637 std::back_inserter(doubledComponents));
638 if(!doubledComponents.empty())
641 e << "called with components that are both required and optional:\n";
642 for(unsigned int i=0; i<doubledComponents.size(); ++i)
644 e << " " << doubledComponents[i] << "\n";
646 this->SetError(e.str().c_str());
650 // Maybe choose one mode exclusively.
651 this->UseFindModules = configArgs.empty();
652 this->UseConfigFiles = moduleArgs.empty();
653 if(!this->UseFindModules && !this->UseConfigFiles)
656 e << "given options exclusive to Module mode:\n";
657 for(std::set<unsigned int>::const_iterator si = moduleArgs.begin();
658 si != moduleArgs.end(); ++si)
660 e << " " << args[*si] << "\n";
662 e << "and options exclusive to Config mode:\n";
663 for(std::set<unsigned int>::const_iterator si = configArgs.begin();
664 si != configArgs.end(); ++si)
666 e << " " << args[*si] << "\n";
668 e << "The options are incompatible.";
669 this->SetError(e.str().c_str());
673 // Ignore EXACT with no version.
674 if(this->Version.empty() && this->VersionExact)
676 this->VersionExact = false;
677 this->Makefile->IssueMessage(
678 cmake::AUTHOR_WARNING, "Ignoring EXACT since no version is requested.");
681 if(this->Version.empty() || components.empty())
683 // Check whether we are recursing inside "Find<name>.cmake" within
684 // another find_package(<name>) call.
685 std::string mod = this->Name;
686 mod += "_FIND_MODULE";
687 if(this->Makefile->IsOn(mod.c_str()))
689 if(this->Version.empty())
691 // Get version information from the outer call if necessary.
692 // Requested version string.
693 std::string ver = this->Name;
694 ver += "_FIND_VERSION";
695 this->Version = this->Makefile->GetSafeDefinition(ver.c_str());
697 // Whether an exact version is required.
698 std::string exact = this->Name;
699 exact += "_FIND_VERSION_EXACT";
700 this->VersionExact = this->Makefile->IsOn(exact.c_str());
702 if(components.empty())
704 std::string components_var = this->Name + "_FIND_COMPONENTS";
705 components = this->Makefile->GetSafeDefinition(components_var.c_str());
710 if(!this->Version.empty())
712 // Try to parse the version number and store the results that were
713 // successfully parsed.
714 unsigned int parsed_major;
715 unsigned int parsed_minor;
716 unsigned int parsed_patch;
717 unsigned int parsed_tweak;
718 this->VersionCount = sscanf(this->Version.c_str(), "%u.%u.%u.%u",
719 &parsed_major, &parsed_minor,
720 &parsed_patch, &parsed_tweak);
721 switch(this->VersionCount)
723 case 4: this->VersionTweak = parsed_tweak; // no break!
724 case 3: this->VersionPatch = parsed_patch; // no break!
725 case 2: this->VersionMinor = parsed_minor; // no break!
726 case 1: this->VersionMajor = parsed_major; // no break!
731 std::string disableFindPackageVar = "CMAKE_DISABLE_FIND_PACKAGE_";
732 disableFindPackageVar += this->Name;
733 if(this->Makefile->IsOn(disableFindPackageVar.c_str()))
738 e << "for module " << this->Name << " called with REQUIRED, but "
739 << disableFindPackageVar
740 << " is enabled. A REQUIRED package cannot be disabled.";
741 this->SetError(e.str().c_str());
749 this->SetModuleVariables(components);
751 // See if there is a Find<package>.cmake module.
752 if(this->UseFindModules)
754 bool foundModule = false;
755 if(!this->FindModule(foundModule))
757 this->AppendSuccessInformation();
762 this->AppendSuccessInformation();
767 if(this->UseFindModules && this->UseConfigFiles &&
768 this->Makefile->IsOn("CMAKE_FIND_PACKAGE_WARN_NO_MODULE"))
771 if(this->RequiredCMakeVersion >= CMake_VERSION_ENCODE(2,8,8))
773 aw << "find_package called without either MODULE or CONFIG option and "
774 "no Find" << this->Name << ".cmake module is in CMAKE_MODULE_PATH. "
775 "Add MODULE to exclusively request Module mode and fail if "
776 "Find" << this->Name << ".cmake is missing. "
777 "Add CONFIG to exclusively request Config mode and search for a "
778 "package configuration file provided by " << this->Name <<
779 " (" << this->Name << "Config.cmake or " <<
780 cmSystemTools::LowerCase(this->Name) << "-config.cmake). ";
784 aw << "find_package called without NO_MODULE option and no "
785 "Find" << this->Name << ".cmake module is in CMAKE_MODULE_PATH. "
786 "Add NO_MODULE to exclusively request Config mode and search for a "
787 "package configuration file provided by " << this->Name <<
788 " (" << this->Name << "Config.cmake or " <<
789 cmSystemTools::LowerCase(this->Name) << "-config.cmake). "
790 "Otherwise make Find" << this->Name << ".cmake available in "
791 "CMAKE_MODULE_PATH.";
794 "(Variable CMAKE_FIND_PACKAGE_WARN_NO_MODULE enabled this warning.)";
795 this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, aw.str());
798 // No find module. Assume the project has a CMake config file. Use
799 // a <package>_DIR cache variable to locate it.
800 this->Variable = this->Name;
801 this->Variable += "_DIR";
803 // Add the default name.
804 if(this->Names.empty())
806 this->Names.push_back(this->Name);
809 // Add the default configs.
810 if(this->Configs.empty())
812 for(std::vector<std::string>::const_iterator ni = this->Names.begin();
813 ni != this->Names.end(); ++ni)
815 std::string config = *ni;
816 config += "Config.cmake";
817 this->Configs.push_back(config);
819 config = cmSystemTools::LowerCase(*ni);
820 config += "-config.cmake";
821 this->Configs.push_back(config);
825 // get igonored paths from vars and reroot them.
826 std::vector<std::string> ignored;
827 this->GetIgnoredPaths(ignored);
828 this->RerootPaths(ignored);
830 // Construct a set of ignored paths
831 this->IgnoredPaths.clear();
832 this->IgnoredPaths.insert(ignored.begin(), ignored.end());
834 // Find and load the package.
835 bool result = this->HandlePackageMode();
836 this->AppendSuccessInformation();
841 //----------------------------------------------------------------------------
842 void cmFindPackageCommand::SetModuleVariables(const std::string& components)
844 this->AddFindDefinition("CMAKE_FIND_PACKAGE_NAME", this->Name.c_str());
846 // Store the list of components.
847 std::string components_var = this->Name + "_FIND_COMPONENTS";
848 this->AddFindDefinition(components_var.c_str(), components.c_str());
852 // Tell the module that is about to be read that it should find
854 std::string quietly = this->Name;
855 quietly += "_FIND_QUIETLY";
856 this->AddFindDefinition(quietly.c_str(), "1");
861 // Tell the module that is about to be read that it should report
862 // a fatal error if the package is not found.
863 std::string req = this->Name;
864 req += "_FIND_REQUIRED";
865 this->AddFindDefinition(req.c_str(), "1");
868 if(!this->Version.empty())
870 // Tell the module that is about to be read what version of the
871 // package has been requested.
872 std::string ver = this->Name;
873 ver += "_FIND_VERSION";
874 this->AddFindDefinition(ver.c_str(), this->Version.c_str());
876 sprintf(buf, "%u", this->VersionMajor);
877 this->AddFindDefinition((ver+"_MAJOR").c_str(), buf);
878 sprintf(buf, "%u", this->VersionMinor);
879 this->AddFindDefinition((ver+"_MINOR").c_str(), buf);
880 sprintf(buf, "%u", this->VersionPatch);
881 this->AddFindDefinition((ver+"_PATCH").c_str(), buf);
882 sprintf(buf, "%u", this->VersionTweak);
883 this->AddFindDefinition((ver+"_TWEAK").c_str(), buf);
884 sprintf(buf, "%u", this->VersionCount);
885 this->AddFindDefinition((ver+"_COUNT").c_str(), buf);
887 // Tell the module whether an exact version has been requested.
888 std::string exact = this->Name;
889 exact += "_FIND_VERSION_EXACT";
890 this->AddFindDefinition(exact.c_str(), this->VersionExact? "1":"0");
894 //----------------------------------------------------------------------------
895 void cmFindPackageCommand::AddFindDefinition(const char* var, const char* val)
897 if(const char* old = this->Makefile->GetDefinition(var))
899 this->OriginalDefs[var].exists = true;
900 this->OriginalDefs[var].value = old;
904 this->OriginalDefs[var].exists = false;
906 this->Makefile->AddDefinition(var, val);
909 //----------------------------------------------------------------------------
910 void cmFindPackageCommand::RestoreFindDefinitions()
912 for(std::map<cmStdString, OriginalDef>::iterator
913 i = this->OriginalDefs.begin(); i != this->OriginalDefs.end(); ++i)
915 OriginalDef const& od = i->second;
918 this->Makefile->AddDefinition(i->first.c_str(), od.value.c_str());
922 this->Makefile->RemoveDefinition(i->first.c_str());
927 //----------------------------------------------------------------------------
928 bool cmFindPackageCommand::FindModule(bool& found)
930 std::string module = "Find";
931 module += this->Name;
933 std::string mfile = this->Makefile->GetModulesFile(module.c_str());
936 // Load the module we found, and set "<name>_FIND_MODULE" to true
939 std::string var = this->Name;
940 var += "_FIND_MODULE";
941 this->Makefile->AddDefinition(var.c_str(), "1");
942 bool result = this->ReadListFile(mfile.c_str(), DoPolicyScope);
943 this->Makefile->RemoveDefinition(var.c_str());
949 //----------------------------------------------------------------------------
950 bool cmFindPackageCommand::HandlePackageMode()
952 this->ConsideredConfigs.clear();
954 // Support old capitalization behavior.
955 std::string upperDir = cmSystemTools::UpperCase(this->Name);
956 std::string upperFound = cmSystemTools::UpperCase(this->Name);
958 upperFound += "_FOUND";
959 if(upperDir == this->Variable)
961 this->Compatibility_1_6 = false;
964 // Try to find the config file.
965 const char* def = this->Makefile->GetDefinition(this->Variable.c_str());
966 if(this->Compatibility_1_6 && cmSystemTools::IsOff(def))
968 // Use the setting of the old name of the variable to provide the
970 const char* oldDef = this->Makefile->GetDefinition(upperDir.c_str());
971 if(!cmSystemTools::IsOff(oldDef))
973 this->Makefile->AddDefinition(this->Variable.c_str(), oldDef);
974 def = this->Makefile->GetDefinition(this->Variable.c_str());
978 // Try to load the config file if the directory is known
979 bool fileFound = false;
980 if (this->UseConfigFiles)
982 if(!cmSystemTools::IsOff(def))
984 // Get the directory from the variable value.
985 std::string dir = def;
986 cmSystemTools::ConvertToUnixSlashes(dir);
988 // Treat relative paths with respect to the current source dir.
989 if(!cmSystemTools::FileIsFullPath(dir.c_str()))
992 dir = this->Makefile->GetCurrentDirectory() + dir;
994 // The file location was cached. Look for the correct file.
996 if (this->FindConfigFile(dir, file))
998 this->FileFound = file;
1001 def = this->Makefile->GetDefinition(this->Variable.c_str());
1004 // Search for the config file if it is not already found.
1005 if(cmSystemTools::IsOff(def) || !fileFound)
1007 fileFound = this->FindConfig();
1008 def = this->Makefile->GetDefinition(this->Variable.c_str());
1012 if(fileFound && this->FileFound.empty())
1014 this->Makefile->IssueMessage(
1015 cmake::INTERNAL_ERROR, "fileFound is true but FileFound is empty!");
1020 std::string foundVar = this->Name;
1021 foundVar += "_FOUND";
1022 std::string notFoundMessageVar = this->Name;
1023 notFoundMessageVar += "_NOT_FOUND_MESSAGE";
1024 std::string notFoundMessage;
1026 // If the directory for the config file was found, try to read the file.
1029 bool configFileSetFOUNDFalse = false;
1033 if ((this->Makefile->IsDefinitionSet(foundVar.c_str()))
1034 && (this->Makefile->IsOn(foundVar.c_str()) == false))
1036 // by removing Foo_FOUND here if it is FALSE, we don't really change
1037 // the situation for the Config file which is about to be included,
1038 // but we make it possible to detect later on whether the Config file
1039 // has set Foo_FOUND to FALSE itself:
1040 this->Makefile->RemoveDefinition(foundVar.c_str());
1042 this->Makefile->RemoveDefinition(notFoundMessageVar.c_str());
1044 // Set the version variables before loading the config file.
1045 // It may override them.
1046 this->StoreVersionFound();
1048 // Parse the configuration file.
1049 if(this->ReadListFile(this->FileFound.c_str(), DoPolicyScope))
1051 // The package has been found.
1054 // Check whether the Config file has set Foo_FOUND to FALSE:
1055 if ((this->Makefile->IsDefinitionSet(foundVar.c_str()))
1056 && (this->Makefile->IsOn(foundVar.c_str()) == false))
1058 // we get here if the Config file has set Foo_FOUND actively to FALSE
1060 configFileSetFOUNDFalse = true;
1061 notFoundMessage = this->Makefile->GetSafeDefinition(
1062 notFoundMessageVar.c_str());
1067 // The configuration file is invalid.
1072 if (result && !found && (!this->Quiet || this->Required))
1074 // The variable is not set.
1077 if (configFileSetFOUNDFalse)
1079 e << "Found package configuration file:\n"
1080 " " << this->FileFound << "\n"
1081 "but it set " << foundVar << " to FALSE so package \"" <<
1082 this->Name << "\" is considered to be NOT FOUND.";
1083 if (!notFoundMessage.empty())
1085 e << " Reason given by package: \n" << notFoundMessage << "\n";
1088 // If there are files in ConsideredConfigs, it means that FooConfig.cmake
1089 // have been found, but they didn't have appropriate versions.
1090 else if (this->ConsideredConfigs.size() > 0)
1092 e << "Could not find a configuration file for package \""
1093 << this->Name << "\" that "
1094 << (this->VersionExact? "exactly matches" : "is compatible with")
1095 << " requested version \"" << this->Version << "\".\n"
1096 << "The following configuration files were considered but not "
1098 for(std::vector<ConfigFileInfo>::size_type i=0;
1099 i<this->ConsideredConfigs.size(); i++)
1101 e << " " << this->ConsideredConfigs[i].filename
1102 << ", version: " << this->ConsideredConfigs[i].version << "\n";
1107 std::string requestedVersionString;
1108 if(!this->Version.empty())
1110 requestedVersionString = " (requested version ";
1111 requestedVersionString += this->Version;
1112 requestedVersionString += ")";
1115 if (this->UseConfigFiles)
1117 if(this->UseFindModules)
1119 e << "By not providing \"Find" << this->Name << ".cmake\" in "
1120 "CMAKE_MODULE_PATH this project has asked CMake to find a "
1121 "package configuration file provided by \""<<this->Name<< "\", "
1122 "but CMake did not find one.\n";
1125 if(this->Configs.size() == 1)
1127 e << "Could not find a package configuration file named \""
1128 << this->Configs[0] << "\" provided by package \""
1129 << this->Name << "\"" << requestedVersionString <<".\n";
1133 e << "Could not find a package configuration file provided by \""
1134 << this->Name << "\"" << requestedVersionString
1135 << " with any of the following names:\n";
1136 for(std::vector<std::string>::const_iterator ci =
1137 this->Configs.begin();
1138 ci != this->Configs.end(); ++ci)
1140 e << " " << *ci << "\n";
1144 e << "Add the installation prefix of \"" << this->Name << "\" to "
1145 "CMAKE_PREFIX_PATH or set \"" << this->Variable << "\" to a "
1146 "directory containing one of the above files. "
1147 "If \"" << this->Name << "\" provides a separate development "
1148 "package or SDK, be sure it has been installed.";
1150 else // if(!this->UseFindModules && !this->UseConfigFiles)
1152 e << "No \"Find" << this->Name << ".cmake\" found in "
1153 << "CMAKE_MODULE_PATH.";
1155 aw<< "Find"<< this->Name <<".cmake must either be part of this "
1156 "project itself, in this case adjust CMAKE_MODULE_PATH so that "
1157 "it points to the correct location inside its source tree.\n"
1158 "Or it must be installed by a package which has already been "
1159 "found via find_package(). In this case make sure that "
1160 "package has indeed been found and adjust CMAKE_MODULE_PATH to "
1161 "contain the location where that package has installed "
1162 "Find" << this->Name << ".cmake. This must be a location "
1163 "provided by that package. This error in general means that "
1164 "the buildsystem of this project is relying on a Find-module "
1165 "without ensuring that it is actually available.\n";
1170 this->Makefile->IssueMessage(
1171 this->Required? cmake::FATAL_ERROR : cmake::WARNING, e.str());
1174 cmSystemTools::SetFatalErrorOccured();
1177 if (!aw.str().empty())
1179 this->Makefile->IssueMessage(cmake::AUTHOR_WARNING,aw.str());
1183 // Set a variable marking whether the package was found.
1184 this->Makefile->AddDefinition(foundVar.c_str(), found? "1":"0");
1186 // Set a variable naming the configuration file that was found.
1187 std::string fileVar = this->Name;
1188 fileVar += "_CONFIG";
1191 this->Makefile->AddDefinition(fileVar.c_str(), this->FileFound.c_str());
1195 this->Makefile->RemoveDefinition(fileVar.c_str());
1198 // Handle some ancient compatibility stuff.
1199 if(this->Compatibility_1_6)
1201 // Listfiles will be looking for the capitalized version of the
1202 // name. Provide it.
1203 this->Makefile->AddDefinition
1205 this->Makefile->GetDefinition(this->Variable.c_str()));
1206 this->Makefile->AddDefinition
1207 (upperFound.c_str(),
1208 this->Makefile->GetDefinition(foundVar.c_str()));
1211 #ifdef CMAKE_BUILD_WITH_CMAKE
1212 if(!(upperDir == this->Variable))
1214 if(this->Compatibility_1_6)
1216 // Listfiles may use the capitalized version of the name.
1217 // Remove any previously added watch.
1218 this->Makefile->GetVariableWatch()->RemoveWatch(
1220 cmFindPackageNeedBackwardsCompatibility
1225 // Listfiles should not be using the capitalized version of the
1226 // name. Add a watch to warn the user.
1227 this->Makefile->GetVariableWatch()->AddWatch(
1229 cmFindPackageNeedBackwardsCompatibility
1235 std::string consideredConfigsVar = this->Name;
1236 consideredConfigsVar += "_CONSIDERED_CONFIGS";
1237 std::string consideredVersionsVar = this->Name;
1238 consideredVersionsVar += "_CONSIDERED_VERSIONS";
1240 std::string consideredConfigFiles;
1241 std::string consideredVersions;
1243 const char* sep = "";
1244 for(std::vector<ConfigFileInfo>::size_type i=0;
1245 i<this->ConsideredConfigs.size(); i++)
1247 consideredConfigFiles += sep;
1248 consideredVersions += sep;
1249 consideredConfigFiles += this->ConsideredConfigs[i].filename;
1250 consideredVersions += this->ConsideredConfigs[i].version;
1254 this->Makefile->AddDefinition(consideredConfigsVar.c_str(),
1255 consideredConfigFiles.c_str());
1257 this->Makefile->AddDefinition(consideredVersionsVar.c_str(),
1258 consideredVersions.c_str());
1263 //----------------------------------------------------------------------------
1264 bool cmFindPackageCommand::FindConfig()
1266 // Compute the set of search prefixes.
1267 this->ComputePrefixes();
1269 // Look for the project's configuration file.
1272 // Search for frameworks.
1273 if(!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly))
1275 found = this->FindFrameworkConfig();
1279 if(!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly))
1281 found = this->FindAppBundleConfig();
1285 if(!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly))
1287 found = this->FindPrefixedConfig();
1290 // Search for frameworks.
1291 if(!found && this->SearchFrameworkLast)
1293 found = this->FindFrameworkConfig();
1297 if(!found && this->SearchAppBundleLast)
1299 found = this->FindAppBundleConfig();
1302 // Store the entry in the cache so it can be set by the user.
1306 init = cmSystemTools::GetFilenamePath(this->FileFound);
1310 init = this->Variable + "-NOTFOUND";
1313 "The directory containing a CMake configuration file for ";
1316 // We force the value since we do not get here if it was already set.
1317 this->Makefile->AddCacheDefinition(this->Variable.c_str(),
1318 init.c_str(), help.c_str(),
1319 cmCacheManager::PATH, true);
1323 //----------------------------------------------------------------------------
1324 bool cmFindPackageCommand::FindPrefixedConfig()
1326 std::vector<std::string>& prefixes = this->SearchPaths;
1327 for(std::vector<std::string>::const_iterator pi = prefixes.begin();
1328 pi != prefixes.end(); ++pi)
1330 if(this->SearchPrefix(*pi))
1338 //----------------------------------------------------------------------------
1339 bool cmFindPackageCommand::FindFrameworkConfig()
1341 std::vector<std::string>& prefixes = this->SearchPaths;
1342 for(std::vector<std::string>::const_iterator i = prefixes.begin();
1343 i != prefixes.end(); ++i)
1345 if(this->SearchFrameworkPrefix(*i))
1353 //----------------------------------------------------------------------------
1354 bool cmFindPackageCommand::FindAppBundleConfig()
1356 std::vector<std::string>& prefixes = this->SearchPaths;
1357 for(std::vector<std::string>::const_iterator i = prefixes.begin();
1358 i != prefixes.end(); ++i)
1360 if(this->SearchAppBundlePrefix(*i))
1368 //----------------------------------------------------------------------------
1369 bool cmFindPackageCommand::ReadListFile(const char* f, PolicyScopeRule psr)
1371 if(this->Makefile->ReadListFile(this->Makefile->GetCurrentListFile(), f, 0,
1372 !this->PolicyScope || psr == NoPolicyScope))
1376 std::string e = "Error reading CMake code from \"";
1379 this->SetError(e.c_str());
1383 //----------------------------------------------------------------------------
1384 void cmFindPackageCommand::AppendToFoundProperty(bool found)
1386 std::vector<std::string> foundContents;
1387 const char *foundProp =
1388 this->Makefile->GetCMakeInstance()->GetProperty("PACKAGES_FOUND");
1389 if (foundProp && *foundProp)
1391 std::string tmp = foundProp;
1393 cmSystemTools::ExpandListArgument(tmp, foundContents, false);
1394 std::vector<std::string>::iterator nameIt = std::find(
1395 foundContents.begin(), foundContents.end(), this->Name);
1396 if(nameIt != foundContents.end())
1398 foundContents.erase(nameIt);
1402 std::vector<std::string> notFoundContents;
1403 const char *notFoundProp =
1404 this->Makefile->GetCMakeInstance()->GetProperty("PACKAGES_NOT_FOUND");
1405 if (notFoundProp && *notFoundProp)
1407 std::string tmp = notFoundProp;
1409 cmSystemTools::ExpandListArgument(tmp, notFoundContents, false);
1410 std::vector<std::string>::iterator nameIt = std::find(
1411 notFoundContents.begin(), notFoundContents.end(), this->Name);
1412 if(nameIt != notFoundContents.end())
1414 notFoundContents.erase(nameIt);
1420 foundContents.push_back(this->Name);
1424 notFoundContents.push_back(this->Name);
1429 const char* sep ="";
1430 for(size_t i=0; i<foundContents.size(); i++)
1433 tmp += foundContents[i];
1437 this->Makefile->GetCMakeInstance()->SetProperty("PACKAGES_FOUND",
1442 for(size_t i=0; i<notFoundContents.size(); i++)
1445 tmp += notFoundContents[i];
1448 this->Makefile->GetCMakeInstance()->SetProperty("PACKAGES_NOT_FOUND",
1452 //----------------------------------------------------------------------------
1453 void cmFindPackageCommand::AppendSuccessInformation()
1455 std::string found = this->Name;
1457 std::string upperFound = cmSystemTools::UpperCase(found);
1459 const char* upperResult = this->Makefile->GetDefinition(upperFound.c_str());
1460 const char* result = this->Makefile->GetDefinition(found.c_str());
1461 bool packageFound = ((cmSystemTools::IsOn(result))
1462 || (cmSystemTools::IsOn(upperResult)));
1464 this->AppendToFoundProperty(packageFound);
1466 // Record whether the find was quiet or not, so this can be used
1467 // e.g. in FeatureSummary.cmake
1468 std::string quietInfoPropName = "_CMAKE_";
1469 quietInfoPropName += this->Name;
1470 quietInfoPropName += "_QUIET";
1471 this->Makefile->GetCMakeInstance()->SetProperty(quietInfoPropName.c_str(),
1472 this->Quiet ? "TRUE" : "FALSE");
1474 // set a global property to record the required version of this package
1475 std::string versionInfoPropName = "_CMAKE_";
1476 versionInfoPropName += this->Name;
1477 versionInfoPropName += "_REQUIRED_VERSION";
1478 std::string versionInfo;
1479 if(!this->Version.empty())
1481 versionInfo = this->VersionExact ? "==" : ">=";
1483 versionInfo += this->Version;
1485 this->Makefile->GetCMakeInstance()->SetProperty(versionInfoPropName.c_str(),
1486 versionInfo.c_str());
1489 std::string requiredInfoPropName = "_CMAKE_";
1490 requiredInfoPropName += this->Name;
1491 requiredInfoPropName += "_TYPE";
1492 this->Makefile->GetCMakeInstance()->SetProperty(
1493 requiredInfoPropName.c_str(), "REQUIRED");
1497 // Restore original state of "_FIND_" variables we set.
1498 this->RestoreFindDefinitions();
1501 //----------------------------------------------------------------------------
1502 void cmFindPackageCommand::ComputePrefixes()
1504 this->AddPrefixesCMakeVariable();
1505 this->AddPrefixesCMakeEnvironment();
1506 this->AddPrefixesUserHints();
1507 this->AddPrefixesSystemEnvironment();
1508 this->AddPrefixesUserRegistry();
1509 this->AddPrefixesBuilds();
1510 this->AddPrefixesCMakeSystemVariable();
1511 this->AddPrefixesSystemRegistry();
1512 this->AddPrefixesUserGuess();
1513 this->ComputeFinalPaths();
1516 //----------------------------------------------------------------------------
1517 void cmFindPackageCommand::AddPrefixesCMakeEnvironment()
1519 if(!this->NoCMakeEnvironmentPath && !this->NoDefaultPath)
1521 // Check the environment variable with the same name as the cache
1524 if(cmSystemTools::GetEnv(this->Variable.c_str(), env) && env.length() > 0)
1526 cmSystemTools::ConvertToUnixSlashes(env);
1527 this->AddPathInternal(env, EnvPath);
1530 this->AddEnvPath("CMAKE_PREFIX_PATH");
1531 this->AddEnvPath("CMAKE_FRAMEWORK_PATH");
1532 this->AddEnvPath("CMAKE_APPBUNDLE_PATH");
1536 //----------------------------------------------------------------------------
1537 void cmFindPackageCommand::AddPrefixesCMakeVariable()
1539 if(!this->NoCMakePath && !this->NoDefaultPath)
1541 this->AddCMakePath("CMAKE_PREFIX_PATH");
1542 this->AddCMakePath("CMAKE_FRAMEWORK_PATH");
1543 this->AddCMakePath("CMAKE_APPBUNDLE_PATH");
1547 //----------------------------------------------------------------------------
1548 void cmFindPackageCommand::AddPrefixesSystemEnvironment()
1550 if(!this->NoSystemEnvironmentPath && !this->NoDefaultPath)
1552 // Use the system search path to generate prefixes.
1553 // Relative paths are interpreted with respect to the current
1554 // working directory.
1555 std::vector<std::string> tmp;
1556 cmSystemTools::GetPath(tmp);
1557 for(std::vector<std::string>::iterator i = tmp.begin();
1558 i != tmp.end(); ++i)
1560 std::string const& d = *i;
1562 // If the path is a PREFIX/bin case then add its parent instead.
1563 if((d.size() >= 4 && strcmp(d.c_str()+d.size()-4, "/bin") == 0) ||
1564 (d.size() >= 5 && strcmp(d.c_str()+d.size()-5, "/sbin") == 0))
1566 this->AddPathInternal(cmSystemTools::GetFilenamePath(d), EnvPath);
1570 this->AddPathInternal(d, EnvPath);
1576 //----------------------------------------------------------------------------
1577 void cmFindPackageCommand::AddPrefixesUserRegistry()
1579 if(this->NoUserRegistry || this->NoDefaultPath)
1584 #if defined(_WIN32) && !defined(__CYGWIN__)
1585 this->LoadPackageRegistryWinUser();
1586 #elif defined(__HAIKU__)
1588 if (find_directory(B_USER_SETTINGS_DIRECTORY, &dir) == B_OK)
1590 dir.Append("cmake/packages");
1591 dir.Append(this->Name.c_str());
1592 this->LoadPackageRegistryDir(dir.Path());
1595 if(const char* home = cmSystemTools::GetEnv("HOME"))
1597 std::string dir = home;
1598 dir += "/.cmake/packages/";
1600 this->LoadPackageRegistryDir(dir);
1605 //----------------------------------------------------------------------------
1606 void cmFindPackageCommand::AddPrefixesSystemRegistry()
1608 if(this->NoSystemRegistry || this->NoDefaultPath)
1613 #if defined(_WIN32) && !defined(__CYGWIN__)
1614 this->LoadPackageRegistryWinSystem();
1618 #if defined(_WIN32) && !defined(__CYGWIN__)
1619 # include <windows.h>
1620 # undef GetCurrentDirectory
1621 // http://msdn.microsoft.com/en-us/library/aa384253%28v=vs.85%29.aspx
1622 # if !defined(KEY_WOW64_32KEY)
1623 # define KEY_WOW64_32KEY 0x0200
1625 # if !defined(KEY_WOW64_64KEY)
1626 # define KEY_WOW64_64KEY 0x0100
1628 //----------------------------------------------------------------------------
1629 void cmFindPackageCommand::LoadPackageRegistryWinUser()
1631 // HKEY_CURRENT_USER\\Software shares 32-bit and 64-bit views.
1632 this->LoadPackageRegistryWin(true, 0);
1635 //----------------------------------------------------------------------------
1636 void cmFindPackageCommand::LoadPackageRegistryWinSystem()
1638 // HKEY_LOCAL_MACHINE\\SOFTWARE has separate 32-bit and 64-bit views.
1639 // Prefer the target platform view first.
1640 if(this->Makefile->PlatformIs64Bit())
1642 this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY);
1643 this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY);
1647 this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY);
1648 this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY);
1652 //----------------------------------------------------------------------------
1653 void cmFindPackageCommand::LoadPackageRegistryWin(bool user,
1656 std::string key = "Software\\Kitware\\CMake\\Packages\\";
1658 std::set<cmStdString> bad;
1660 if(RegOpenKeyEx(user? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, key.c_str(),
1661 0, KEY_QUERY_VALUE|view, &hKey) == ERROR_SUCCESS)
1663 DWORD valueType = REG_NONE;
1665 std::vector<char> data(512);
1670 DWORD nameSize = static_cast<DWORD>(sizeof(name));
1671 DWORD dataSize = static_cast<DWORD>(data.size()-1);
1672 switch(RegEnumValue(hKey, index, name, &nameSize,
1673 0, &valueType, (BYTE*)&data[0], &dataSize))
1677 if(valueType == REG_SZ)
1680 cmsys_ios::stringstream ss(&data[0]);
1681 if(!this->CheckPackageRegistryEntry(ss))
1683 // The entry is invalid.
1688 case ERROR_MORE_DATA:
1689 data.resize(dataSize+1);
1691 case ERROR_NO_MORE_ITEMS: default: done = true; break;
1697 // Remove bad values if possible.
1698 if(user && !bad.empty() &&
1699 RegOpenKeyEx(HKEY_CURRENT_USER, key.c_str(),
1700 0, KEY_SET_VALUE|view, &hKey) == ERROR_SUCCESS)
1702 for(std::set<cmStdString>::const_iterator vi = bad.begin();
1703 vi != bad.end(); ++vi)
1705 RegDeleteValue(hKey, vi->c_str());
1711 //----------------------------------------------------------------------------
1712 class cmFindPackageCommandHoldFile
1716 cmFindPackageCommandHoldFile(const char* f): File(f) {}
1717 ~cmFindPackageCommandHoldFile()
1718 { if(this->File) { cmSystemTools::RemoveFile(this->File); } }
1719 void Release() { this->File = 0; }
1722 //----------------------------------------------------------------------------
1723 void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir)
1725 cmsys::Directory files;
1726 if(!files.Load(dir.c_str()))
1732 for(unsigned long i=0; i < files.GetNumberOfFiles(); ++i)
1736 fname += files.GetFile(i);
1738 if(!cmSystemTools::FileIsDirectory(fname.c_str()))
1740 // Hold this file hostage until it behaves.
1741 cmFindPackageCommandHoldFile holdFile(fname.c_str());
1744 std::ifstream fin(fname.c_str(), std::ios::in | cmsys_ios_binary);
1745 if(fin && this->CheckPackageRegistryEntry(fin))
1747 // The file references an existing package, so release it.
1753 // TODO: Wipe out the directory if it is empty.
1757 //----------------------------------------------------------------------------
1758 bool cmFindPackageCommand::CheckPackageRegistryEntry(std::istream& is)
1760 // Parse the content of one package registry entry.
1762 if(cmSystemTools::GetLineFromStream(is, fname) &&
1763 cmSystemTools::FileIsFullPath(fname.c_str()))
1765 // The first line in the stream is the full path to a file or
1766 // directory containing the package.
1767 if(cmSystemTools::FileExists(fname.c_str()))
1769 // The path exists. Look for the package here.
1770 if(!cmSystemTools::FileIsDirectory(fname.c_str()))
1772 fname = cmSystemTools::GetFilenamePath(fname);
1774 this->AddPathInternal(fname, FullPath);
1779 // The path does not exist. Assume the stream content is
1780 // associated with an old package that no longer exists, and
1781 // delete it to keep the package registry clean.
1787 // The first line in the stream is not the full path to a file or
1788 // directory. Assume the stream content was created by a future
1789 // version of CMake that uses a different format, and leave it.
1794 //----------------------------------------------------------------------------
1795 void cmFindPackageCommand::AddPrefixesBuilds()
1797 if(!this->NoBuilds && !this->NoDefaultPath)
1799 // It is likely that CMake will have recently built the project.
1800 for(int i=0; i <= 10; ++i)
1804 "[HKEY_CURRENT_USER\\Software\\Kitware\\CMakeSetup\\"
1805 "Settings\\StartPath;WhereBuild" << i << "]";
1806 std::string f = r.str();
1807 cmSystemTools::ExpandRegistryValues(f);
1808 cmSystemTools::ConvertToUnixSlashes(f);
1809 if(cmSystemTools::FileIsFullPath(f.c_str()) &&
1810 cmSystemTools::FileIsDirectory(f.c_str()))
1812 this->AddPathInternal(f, FullPath);
1818 //----------------------------------------------------------------------------
1819 void cmFindPackageCommand::AddPrefixesCMakeSystemVariable()
1821 if(!this->NoCMakeSystemPath && !this->NoDefaultPath)
1823 this->AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
1824 this->AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
1825 this->AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
1829 //----------------------------------------------------------------------------
1830 void cmFindPackageCommand::AddPrefixesUserGuess()
1832 // Add guesses specified by the caller.
1833 this->AddPathsInternal(this->UserPaths, CMakePath);
1836 //----------------------------------------------------------------------------
1837 void cmFindPackageCommand::AddPrefixesUserHints()
1839 // Add hints specified by the caller.
1840 this->AddPathsInternal(this->UserHints, CMakePath);
1843 //----------------------------------------------------------------------------
1844 bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
1846 assert(!dir.empty() && dir[dir.size()-1] == '/');
1848 // Check each path suffix on this directory.
1849 for(std::vector<std::string>::const_iterator
1850 si = this->SearchPathSuffixes.begin();
1851 si != this->SearchPathSuffixes.end(); ++si)
1853 std::string d = dir;
1859 if(this->CheckDirectory(d))
1867 //----------------------------------------------------------------------------
1868 bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
1870 assert(!dir.empty() && dir[dir.size()-1] == '/');
1872 // Look for the file in this directory.
1873 std::string d = dir.substr(0, dir.size()-1);
1874 if(this->FindConfigFile(d, this->FileFound))
1876 // Remove duplicate slashes.
1877 cmSystemTools::ConvertToUnixSlashes(this->FileFound);
1883 //----------------------------------------------------------------------------
1884 bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
1887 if (this->IgnoredPaths.count(dir))
1892 for(std::vector<std::string>::const_iterator ci = this->Configs.begin();
1893 ci != this->Configs.end(); ++ci)
1900 fprintf(stderr, "Checking file [%s]\n", file.c_str());
1902 if(cmSystemTools::FileExists(file.c_str(), true) &&
1903 this->CheckVersion(file))
1911 //----------------------------------------------------------------------------
1912 bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
1914 bool result = false; // by default, assume the version is not ok.
1915 bool haveResult = false;
1916 std::string version = "unknown";
1918 // Get the filename without the .cmake extension.
1919 std::string::size_type pos = config_file.rfind('.');
1920 std::string version_file_base = config_file.substr(0, pos);
1922 // Look for foo-config-version.cmake
1923 std::string version_file = version_file_base;
1924 version_file += "-version.cmake";
1925 if ((haveResult == false)
1926 && (cmSystemTools::FileExists(version_file.c_str(), true)))
1928 result = this->CheckVersionFile(version_file, version);
1932 // Look for fooConfigVersion.cmake
1933 version_file = version_file_base;
1934 version_file += "Version.cmake";
1935 if ((haveResult == false)
1936 && (cmSystemTools::FileExists(version_file.c_str(), true)))
1938 result = this->CheckVersionFile(version_file, version);
1943 // If no version was requested a versionless package is acceptable.
1944 if ((haveResult == false) && (this->Version.empty()))
1950 ConfigFileInfo configFileInfo;
1951 configFileInfo.filename = config_file;
1952 configFileInfo.version = version;
1953 this->ConsideredConfigs.push_back(configFileInfo);
1958 //----------------------------------------------------------------------------
1959 bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file,
1960 std::string& result_version)
1962 // The version file will be loaded in an isolated scope.
1963 cmMakefile::ScopePushPop varScope(this->Makefile);
1964 cmMakefile::PolicyPushPop polScope(this->Makefile);
1965 static_cast<void>(varScope);
1966 static_cast<void>(polScope);
1968 // Clear the output variables.
1969 this->Makefile->RemoveDefinition("PACKAGE_VERSION");
1970 this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
1971 this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
1972 this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
1974 // Set the input variables.
1975 this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name.c_str());
1976 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION",
1977 this->Version.c_str());
1979 sprintf(buf, "%u", this->VersionMajor);
1980 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MAJOR", buf);
1981 sprintf(buf, "%u", this->VersionMinor);
1982 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MINOR", buf);
1983 sprintf(buf, "%u", this->VersionPatch);
1984 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_PATCH", buf);
1985 sprintf(buf, "%u", this->VersionTweak);
1986 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_TWEAK", buf);
1987 sprintf(buf, "%u", this->VersionCount);
1988 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COUNT", buf);
1990 // Load the version check file. Pass NoPolicyScope because we do
1991 // our own policy push/pop independent of CMP0011.
1992 bool suitable = false;
1993 if(this->ReadListFile(version_file.c_str(), NoPolicyScope))
1995 // Check the output variables.
1996 bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
1997 bool unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
1998 if(!okay && !this->VersionExact)
2000 okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
2003 // The package is suitable if the version is okay and not
2004 // explicitly unsuitable.
2005 suitable = !unsuitable && (okay || this->Version.empty());
2008 // Get the version found.
2009 this->VersionFound =
2010 this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
2012 // Try to parse the version number and store the results that were
2013 // successfully parsed.
2014 unsigned int parsed_major;
2015 unsigned int parsed_minor;
2016 unsigned int parsed_patch;
2017 unsigned int parsed_tweak;
2018 this->VersionFoundCount =
2019 sscanf(this->VersionFound.c_str(), "%u.%u.%u.%u",
2020 &parsed_major, &parsed_minor,
2021 &parsed_patch, &parsed_tweak);
2022 switch(this->VersionFoundCount)
2024 case 4: this->VersionFoundTweak = parsed_tweak; // no break!
2025 case 3: this->VersionFoundPatch = parsed_patch; // no break!
2026 case 2: this->VersionFoundMinor = parsed_minor; // no break!
2027 case 1: this->VersionFoundMajor = parsed_major; // no break!
2033 result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
2034 if (result_version.empty())
2036 result_version = "unknown";
2039 // Succeed if the version is suitable.
2043 //----------------------------------------------------------------------------
2044 void cmFindPackageCommand::StoreVersionFound()
2046 // Store the whole version string.
2047 std::string ver = this->Name;
2049 if(this->VersionFound.empty())
2051 this->Makefile->RemoveDefinition(ver.c_str());
2055 this->Makefile->AddDefinition(ver.c_str(), this->VersionFound.c_str());
2058 // Store the version components.
2060 sprintf(buf, "%u", this->VersionFoundMajor);
2061 this->Makefile->AddDefinition((ver+"_MAJOR").c_str(), buf);
2062 sprintf(buf, "%u", this->VersionFoundMinor);
2063 this->Makefile->AddDefinition((ver+"_MINOR").c_str(), buf);
2064 sprintf(buf, "%u", this->VersionFoundPatch);
2065 this->Makefile->AddDefinition((ver+"_PATCH").c_str(), buf);
2066 sprintf(buf, "%u", this->VersionFoundTweak);
2067 this->Makefile->AddDefinition((ver+"_TWEAK").c_str(), buf);
2068 sprintf(buf, "%u", this->VersionFoundCount);
2069 this->Makefile->AddDefinition((ver+"_COUNT").c_str(), buf);
2072 //----------------------------------------------------------------------------
2073 #include <cmsys/Glob.hxx>
2074 #include <cmsys/String.h>
2075 #include <cmsys/auto_ptr.hxx>
2078 class cmFileListGeneratorBase
2081 virtual ~cmFileListGeneratorBase() {}
2083 bool Consider(std::string const& fullPath, cmFileList& listing);
2085 bool Search(cmFileList&);
2086 virtual bool Search(std::string const& parent, cmFileList&) = 0;
2087 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const = 0;
2088 friend class cmFileList;
2089 cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next);
2090 cmsys::auto_ptr<cmFileListGeneratorBase> Next;
2096 cmFileList(): First(), Last(0) {}
2097 virtual ~cmFileList() {}
2098 cmFileList& operator/(cmFileListGeneratorBase const& rhs)
2102 this->Last = this->Last->SetNext(rhs);
2106 this->First = rhs.Clone();
2107 this->Last = this->First.get();
2113 if(this->First.get())
2115 return this->First->Search(*this);
2120 virtual bool Visit(std::string const& fullPath) = 0;
2121 friend class cmFileListGeneratorBase;
2122 cmsys::auto_ptr<cmFileListGeneratorBase> First;
2123 cmFileListGeneratorBase* Last;
2126 class cmFindPackageFileList: public cmFileList
2129 cmFindPackageFileList(cmFindPackageCommand* fpc,
2130 bool use_suffixes = true):
2131 cmFileList(), FPC(fpc), UseSuffixes(use_suffixes) {}
2133 bool Visit(std::string const& fullPath)
2135 if(this->UseSuffixes)
2137 return this->FPC->SearchDirectory(fullPath);
2141 return this->FPC->CheckDirectory(fullPath);
2144 cmFindPackageCommand* FPC;
2148 bool cmFileListGeneratorBase::Search(cmFileList& listing)
2150 return this->Search("", listing);
2153 cmFileListGeneratorBase*
2154 cmFileListGeneratorBase::SetNext(cmFileListGeneratorBase const& next)
2156 this->Next = next.Clone();
2157 return this->Next.get();
2160 bool cmFileListGeneratorBase::Consider(std::string const& fullPath,
2161 cmFileList& listing)
2163 if(this->Next.get())
2165 return this->Next->Search(fullPath + "/", listing);
2169 return listing.Visit(fullPath + "/");
2173 class cmFileListGeneratorFixed: public cmFileListGeneratorBase
2176 cmFileListGeneratorFixed(std::string const& str):
2177 cmFileListGeneratorBase(), String(str) {}
2178 cmFileListGeneratorFixed(cmFileListGeneratorFixed const& r):
2179 cmFileListGeneratorBase(), String(r.String) {}
2182 virtual bool Search(std::string const& parent, cmFileList& lister)
2184 std::string fullPath = parent + this->String;
2185 return this->Consider(fullPath, lister);
2187 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
2189 cmsys::auto_ptr<cmFileListGeneratorBase>
2190 g(new cmFileListGeneratorFixed(*this));
2195 class cmFileListGeneratorEnumerate: public cmFileListGeneratorBase
2198 cmFileListGeneratorEnumerate(std::vector<std::string> const& v):
2199 cmFileListGeneratorBase(), Vector(v) {}
2200 cmFileListGeneratorEnumerate(cmFileListGeneratorEnumerate const& r):
2201 cmFileListGeneratorBase(), Vector(r.Vector) {}
2203 std::vector<std::string> const& Vector;
2204 virtual bool Search(std::string const& parent, cmFileList& lister)
2206 for(std::vector<std::string>::const_iterator i = this->Vector.begin();
2207 i != this->Vector.end(); ++i)
2209 if(this->Consider(parent + *i, lister))
2216 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
2218 cmsys::auto_ptr<cmFileListGeneratorBase>
2219 g(new cmFileListGeneratorEnumerate(*this));
2224 class cmFileListGeneratorProject: public cmFileListGeneratorBase
2227 cmFileListGeneratorProject(std::vector<std::string> const& names):
2228 cmFileListGeneratorBase(), Names(names) {}
2229 cmFileListGeneratorProject(cmFileListGeneratorProject const& r):
2230 cmFileListGeneratorBase(), Names(r.Names) {}
2232 std::vector<std::string> const& Names;
2233 virtual bool Search(std::string const& parent, cmFileList& lister)
2235 // Construct a list of matches.
2236 std::vector<std::string> matches;
2238 d.Load(parent.c_str());
2239 for(unsigned long i=0; i < d.GetNumberOfFiles(); ++i)
2241 const char* fname = d.GetFile(i);
2242 if(strcmp(fname, ".") == 0 ||
2243 strcmp(fname, "..") == 0)
2247 for(std::vector<std::string>::const_iterator ni = this->Names.begin();
2248 ni != this->Names.end(); ++ni)
2250 if(cmsysString_strncasecmp(fname, ni->c_str(),
2253 matches.push_back(fname);
2258 for(std::vector<std::string>::const_iterator i = matches.begin();
2259 i != matches.end(); ++i)
2261 if(this->Consider(parent + *i, lister))
2268 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
2270 cmsys::auto_ptr<cmFileListGeneratorBase>
2271 g(new cmFileListGeneratorProject(*this));
2276 class cmFileListGeneratorMacProject: public cmFileListGeneratorBase
2279 cmFileListGeneratorMacProject(std::vector<std::string> const& names,
2281 cmFileListGeneratorBase(), Names(names), Extension(ext) {}
2282 cmFileListGeneratorMacProject(cmFileListGeneratorMacProject const& r):
2283 cmFileListGeneratorBase(), Names(r.Names), Extension(r.Extension) {}
2285 std::vector<std::string> const& Names;
2286 std::string Extension;
2287 virtual bool Search(std::string const& parent, cmFileList& lister)
2289 // Construct a list of matches.
2290 std::vector<std::string> matches;
2292 d.Load(parent.c_str());
2293 for(unsigned long i=0; i < d.GetNumberOfFiles(); ++i)
2295 const char* fname = d.GetFile(i);
2296 if(strcmp(fname, ".") == 0 ||
2297 strcmp(fname, "..") == 0)
2301 for(std::vector<std::string>::const_iterator ni = this->Names.begin();
2302 ni != this->Names.end(); ++ni)
2304 std::string name = *ni;
2305 name += this->Extension;
2306 if(cmsysString_strcasecmp(fname, name.c_str()) == 0)
2308 matches.push_back(fname);
2313 for(std::vector<std::string>::const_iterator i = matches.begin();
2314 i != matches.end(); ++i)
2316 if(this->Consider(parent + *i, lister))
2323 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
2325 cmsys::auto_ptr<cmFileListGeneratorBase>
2326 g(new cmFileListGeneratorMacProject(*this));
2331 class cmFileListGeneratorCaseInsensitive: public cmFileListGeneratorBase
2334 cmFileListGeneratorCaseInsensitive(std::string const& str):
2335 cmFileListGeneratorBase(), String(str) {}
2336 cmFileListGeneratorCaseInsensitive(
2337 cmFileListGeneratorCaseInsensitive const& r):
2338 cmFileListGeneratorBase(), String(r.String) {}
2341 virtual bool Search(std::string const& parent, cmFileList& lister)
2343 // Look for matching files.
2344 std::vector<std::string> matches;
2346 d.Load(parent.c_str());
2347 for(unsigned long i=0; i < d.GetNumberOfFiles(); ++i)
2349 const char* fname = d.GetFile(i);
2350 if(strcmp(fname, ".") == 0 ||
2351 strcmp(fname, "..") == 0)
2355 if(cmsysString_strcasecmp(fname, this->String.c_str()) == 0)
2357 if(this->Consider(parent + fname, lister))
2365 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
2367 cmsys::auto_ptr<cmFileListGeneratorBase>
2368 g(new cmFileListGeneratorCaseInsensitive(*this));
2373 class cmFileListGeneratorGlob: public cmFileListGeneratorBase
2376 cmFileListGeneratorGlob(std::string const& str):
2377 cmFileListGeneratorBase(), Pattern(str) {}
2378 cmFileListGeneratorGlob(cmFileListGeneratorGlob const& r):
2379 cmFileListGeneratorBase(), Pattern(r.Pattern) {}
2381 std::string Pattern;
2382 virtual bool Search(std::string const& parent, cmFileList& lister)
2384 // Glob the set of matching files.
2385 std::string expr = parent;
2386 expr += this->Pattern;
2388 if(!g.FindFiles(expr))
2392 std::vector<std::string> const& files = g.GetFiles();
2394 // Look for directories among the matches.
2395 for(std::vector<std::string>::const_iterator fi = files.begin();
2396 fi != files.end(); ++fi)
2398 if(cmSystemTools::FileIsDirectory(fi->c_str()))
2400 if(this->Consider(*fi, lister))
2408 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
2410 cmsys::auto_ptr<cmFileListGeneratorBase>
2411 g(new cmFileListGeneratorGlob(*this));
2416 //----------------------------------------------------------------------------
2417 bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
2419 assert(!prefix_in.empty() && prefix_in[prefix_in.size()-1] == '/');
2422 fprintf(stderr, "Checking prefix [%s]\n", prefix_in.c_str());
2425 // Skip this if the prefix does not exist.
2426 if(!cmSystemTools::FileIsDirectory(prefix_in.c_str()))
2431 // PREFIX/ (useful on windows or in build trees)
2432 if(this->SearchDirectory(prefix_in))
2437 // Strip the trailing slash because the path generator is about to
2439 std::string prefix = prefix_in.substr(0, prefix_in.size()-1);
2441 // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
2443 cmFindPackageFileList lister(this);
2445 / cmFileListGeneratorFixed(prefix)
2446 / cmFileListGeneratorCaseInsensitive("cmake");
2453 // PREFIX/(Foo|foo|FOO).*/
2455 cmFindPackageFileList lister(this);
2457 / cmFileListGeneratorFixed(prefix)
2458 / cmFileListGeneratorProject(this->Names);
2465 // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
2467 cmFindPackageFileList lister(this);
2469 / cmFileListGeneratorFixed(prefix)
2470 / cmFileListGeneratorProject(this->Names)
2471 / cmFileListGeneratorCaseInsensitive("cmake");
2478 // Construct list of common install locations (lib and share).
2479 std::vector<std::string> common;
2480 if(!this->LibraryArchitecture.empty())
2482 common.push_back("lib/"+this->LibraryArchitecture);
2484 if(this->UseLib64Paths)
2486 common.push_back("lib64");
2488 common.push_back("lib");
2489 common.push_back("share");
2491 // PREFIX/(lib/ARCH|lib|share)/cmake/(Foo|foo|FOO).*/
2493 cmFindPackageFileList lister(this);
2495 / cmFileListGeneratorFixed(prefix)
2496 / cmFileListGeneratorEnumerate(common)
2497 / cmFileListGeneratorFixed("cmake")
2498 / cmFileListGeneratorProject(this->Names);
2505 // PREFIX/(lib/ARCH|lib|share)/(Foo|foo|FOO).*/
2507 cmFindPackageFileList lister(this);
2509 / cmFileListGeneratorFixed(prefix)
2510 / cmFileListGeneratorEnumerate(common)
2511 / cmFileListGeneratorProject(this->Names);
2518 // PREFIX/(lib/ARCH|lib|share)/(Foo|foo|FOO).*/(cmake|CMake)/
2520 cmFindPackageFileList lister(this);
2522 / cmFileListGeneratorFixed(prefix)
2523 / cmFileListGeneratorEnumerate(common)
2524 / cmFileListGeneratorProject(this->Names)
2525 / cmFileListGeneratorCaseInsensitive("cmake");
2535 //----------------------------------------------------------------------------
2536 bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
2538 assert(!prefix_in.empty() && prefix_in[prefix_in.size()-1] == '/');
2541 fprintf(stderr, "Checking framework prefix [%s]\n", prefix_in.c_str());
2544 // Strip the trailing slash because the path generator is about to
2546 std::string prefix = prefix_in.substr(0, prefix_in.size()-1);
2548 // <prefix>/Foo.framework/Resources/
2550 cmFindPackageFileList lister(this);
2552 / cmFileListGeneratorFixed(prefix)
2553 / cmFileListGeneratorMacProject(this->Names, ".framework")
2554 / cmFileListGeneratorFixed("Resources");
2560 // <prefix>/Foo.framework/Resources/CMake/
2562 cmFindPackageFileList lister(this);
2564 / cmFileListGeneratorFixed(prefix)
2565 / cmFileListGeneratorMacProject(this->Names, ".framework")
2566 / cmFileListGeneratorFixed("Resources")
2567 / cmFileListGeneratorCaseInsensitive("cmake");
2574 // <prefix>/Foo.framework/Versions/*/Resources/
2576 cmFindPackageFileList lister(this);
2578 / cmFileListGeneratorFixed(prefix)
2579 / cmFileListGeneratorMacProject(this->Names, ".framework")
2580 / cmFileListGeneratorFixed("Versions")
2581 / cmFileListGeneratorGlob("*/Resources");
2588 // <prefix>/Foo.framework/Versions/*/Resources/CMake/
2590 cmFindPackageFileList lister(this);
2592 / cmFileListGeneratorFixed(prefix)
2593 / cmFileListGeneratorMacProject(this->Names, ".framework")
2594 / cmFileListGeneratorFixed("Versions")
2595 / cmFileListGeneratorGlob("*/Resources")
2596 / cmFileListGeneratorCaseInsensitive("cmake");
2606 //----------------------------------------------------------------------------
2607 bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
2609 assert(!prefix_in.empty() && prefix_in[prefix_in.size()-1] == '/');
2612 fprintf(stderr, "Checking bundle prefix [%s]\n", prefix_in.c_str());
2615 // Strip the trailing slash because the path generator is about to
2617 std::string prefix = prefix_in.substr(0, prefix_in.size()-1);
2619 // <prefix>/Foo.app/Contents/Resources
2621 cmFindPackageFileList lister(this);
2623 / cmFileListGeneratorFixed(prefix)
2624 / cmFileListGeneratorMacProject(this->Names, ".app")
2625 / cmFileListGeneratorFixed("Contents/Resources");
2632 // <prefix>/Foo.app/Contents/Resources/CMake
2634 cmFindPackageFileList lister(this);
2636 / cmFileListGeneratorFixed(prefix)
2637 / cmFileListGeneratorMacProject(this->Names, ".app")
2638 / cmFileListGeneratorFixed("Contents/Resources")
2639 / cmFileListGeneratorCaseInsensitive("cmake");
2649 // TODO: Debug cmsys::Glob double slash problem.