Clarify documentation for if.
[cmake.git] / Source / cmFindPackageCommand.cxx
blob06df2224fccf5f893c81e55ccd48c0a61bf89dea
1 /*=========================================================================
3 Program: CMake - Cross-Platform Makefile Generator
4 Module: $RCSfile: cmFindPackageCommand.cxx,v $
5 Language: C++
6 Date: $Date: 2009-09-11 12:18:07 $
7 Version: $Revision: 1.62 $
9 Copyright (c) 2002 Kitware, Inc., Insight Consortium. All rights reserved.
10 See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.
12 This software is distributed WITHOUT ANY WARRANTY; without even
13 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 PURPOSE. See the above copyright notices for more information.
16 =========================================================================*/
17 #include "cmFindPackageCommand.h"
19 #include <cmsys/Directory.hxx>
20 #include <cmsys/RegularExpression.hxx>
22 #ifdef CMAKE_BUILD_WITH_CMAKE
23 #include "cmVariableWatch.h"
24 #endif
26 void cmFindPackageNeedBackwardsCompatibility(const std::string& variable,
27 int access_type, void*, const char* newValue,
28 const cmMakefile*)
30 (void)newValue;
31 #ifdef CMAKE_BUILD_WITH_CMAKE
32 if(access_type == cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS)
34 std::string message = "An attempt was made to access a variable: ";
35 message += variable;
36 message +=
37 " that has not been defined. This variable is created by the "
38 "FIND_PACKAGE command. CMake version 1.6 always converted the "
39 "variable name to upper-case, but this behavior is no longer the "
40 "case. To fix this you might need to set the cache value of "
41 "CMAKE_BACKWARDS_COMPATIBILITY to 1.6 or less. If you are writing a "
42 "CMake listfile, you should change the variable reference to use "
43 "the case of the argument to FIND_PACKAGE.";
44 cmSystemTools::Error(message.c_str());
46 #else
47 (void)variable;
48 (void)access_type;
49 #endif
52 //----------------------------------------------------------------------------
53 cmFindPackageCommand::cmFindPackageCommand()
55 cmSystemTools::ReplaceString(this->GenericDocumentationRootPath,
56 "CMAKE_FIND_ROOT_PATH_MODE_XXX",
57 "CMAKE_FIND_ROOT_PATH_MODE_PACKAGE");
58 cmSystemTools::ReplaceString(this->GenericDocumentationPathsOrder,
59 "FIND_ARGS_XXX", "<package>");
60 cmSystemTools::ReplaceString(this->GenericDocumentationPathsOrder,
61 "FIND_XXX", "find_package");
62 this->CMakePathName = "PACKAGE";
63 this->Quiet = false;
64 this->Required = false;
65 this->NoRegistry = false;
66 this->NoBuilds = false;
67 this->NoModule = false;
68 this->DebugMode = false;
69 this->UseLib64Paths = false;
70 this->PolicyScope = true;
71 this->VersionMajor = 0;
72 this->VersionMinor = 0;
73 this->VersionPatch = 0;
74 this->VersionTweak = 0;
75 this->VersionCount = 0;
76 this->VersionExact = false;
77 this->VersionFoundMajor = 0;
78 this->VersionFoundMinor = 0;
79 this->VersionFoundPatch = 0;
80 this->VersionFoundTweak = 0;
81 this->VersionFoundCount = 0;
82 this->CommandDocumentation =
83 " find_package(<package> [version] [EXACT] [QUIET]\n"
84 " [[REQUIRED|COMPONENTS] [components...]]\n"
85 " [NO_POLICY_SCOPE])\n"
86 "Finds and loads settings from an external project. "
87 "<package>_FOUND will be set to indicate whether the package was found. "
88 "When the package is found package-specific information is provided "
89 "through variables documented by the package itself. "
90 "The QUIET option disables messages if the package cannot be found. "
91 "The REQUIRED option stops processing with an error message if the "
92 "package cannot be found. "
93 "A package-specific list of components may be listed after the "
94 "REQUIRED option or after the COMPONENTS option if no REQUIRED "
95 "option is given. "
96 "The [version] argument requests a version with which the package found "
97 "should be compatible (format is major[.minor[.patch[.tweak]]]). "
98 "The EXACT option requests that the version be matched exactly. "
99 "If no [version] is given to a recursive invocation inside a "
100 "find-module, the [version] and EXACT arguments are forwarded "
101 "automatically from the outer call. "
102 "Version support is currently provided only on a package-by-package "
103 "basis (details below).\n"
104 "User code should generally look for packages using the above simple "
105 "signature. The remainder of this command documentation specifies the "
106 "full command signature and details of the search process. Project "
107 "maintainers wishing to provide a package to be found by this command "
108 "are encouraged to read on.\n"
109 "The command has two modes by which it searches for packages: "
110 "\"Module\" mode and \"Config\" mode. "
111 "Module mode is available when the command is invoked with the above "
112 "reduced signature. "
113 "CMake searches for a file called \"Find<package>.cmake\" in "
114 "the CMAKE_MODULE_PATH followed by the CMake installation. "
115 "If the file is found, it is read and processed by CMake. "
116 "It is responsible for finding the package, checking the version, "
117 "and producing any needed messages. "
118 "Many find-modules provide limited or no support for versioning; "
119 "check the module documentation. "
120 "If no module is found the command proceeds to Config mode.\n"
121 "The complete Config mode command signature is:\n"
122 " find_package(<package> [version] [EXACT] [QUIET]\n"
123 " [[REQUIRED|COMPONENTS] [components...]] [NO_MODULE]\n"
124 " [NO_POLICY_SCOPE]\n"
125 " [NAMES name1 [name2 ...]]\n"
126 " [CONFIGS config1 [config2 ...]]\n"
127 " [HINTS path1 [path2 ... ]]\n"
128 " [PATHS path1 [path2 ... ]]\n"
129 " [PATH_SUFFIXES suffix1 [suffix2 ...]]\n"
130 " [NO_DEFAULT_PATH]\n"
131 " [NO_CMAKE_ENVIRONMENT_PATH]\n"
132 " [NO_CMAKE_PATH]\n"
133 " [NO_SYSTEM_ENVIRONMENT_PATH]\n"
134 " [NO_CMAKE_PACKAGE_REGISTRY]\n"
135 " [NO_CMAKE_BUILDS_PATH]\n"
136 " [NO_CMAKE_SYSTEM_PATH]\n"
137 " [CMAKE_FIND_ROOT_PATH_BOTH |\n"
138 " ONLY_CMAKE_FIND_ROOT_PATH |\n"
139 " NO_CMAKE_FIND_ROOT_PATH])\n"
140 "The NO_MODULE option may be used to skip Module mode explicitly. "
141 "It is also implied by use of options not specified in the reduced "
142 "signature. "
143 "\n"
144 "Config mode attempts to locate a configuration file provided by the "
145 "package to be found. A cache entry called <package>_DIR is created to "
146 "hold the directory containing the file. "
147 "By default the command searches for a package with the name <package>. "
148 "If the NAMES option is given the names following it are used instead "
149 "of <package>. "
150 "The command searches for a file called \"<name>Config.cmake\" or "
151 "\"<lower-case-name>-config.cmake\" for each name specified. "
152 "A replacement set of possible configuration file names may be given "
153 "using the CONFIGS option. "
154 "The search procedure is specified below. Once found, the configuration "
155 "file is read and processed by CMake. Since the file is provided by the "
156 "package it already knows the location of package contents. "
157 "The full path to the configuration file is stored in the cmake "
158 "variable <package>_CONFIG."
159 "\n"
160 "If the package configuration file cannot be found CMake "
161 "will generate an error describing the problem unless the QUIET "
162 "argument is specified. If REQUIRED is specified and the package "
163 "is not found a fatal error is generated and the configure step stops "
164 "executing. If <package>_DIR has been set to a directory not containing "
165 "a configuration file CMake will ignore it and search from scratch."
166 "\n"
167 "When the [version] argument is given Config mode will only find a "
168 "version of the package that claims compatibility with the requested "
169 "version (format is major[.minor[.patch[.tweak]]]). "
170 "If the EXACT option is given only a version of the package claiming "
171 "an exact match of the requested version may be found. "
172 "CMake does not establish any convention for the meaning of version "
173 "numbers. "
174 "Package version numbers are checked by \"version\" files provided by "
175 "the packages themselves. "
176 "For a candidate package configuration file \"<config-file>.cmake\" the "
177 "corresponding version file is located next to it and named either "
178 "\"<config-file>-version.cmake\" or \"<config-file>Version.cmake\". "
179 "If no such version file is available then the configuration file "
180 "is assumed to not be compatible with any requested version. "
181 "When a version file is found it is loaded to check the requested "
182 "version number. "
183 "The version file is loaded in a nested scope in which the following "
184 "variables have been defined:\n"
185 " PACKAGE_FIND_NAME = the <package> name\n"
186 " PACKAGE_FIND_VERSION = full requested version string\n"
187 " PACKAGE_FIND_VERSION_MAJOR = major version if requested, else 0\n"
188 " PACKAGE_FIND_VERSION_MINOR = minor version if requested, else 0\n"
189 " PACKAGE_FIND_VERSION_PATCH = patch version if requested, else 0\n"
190 " PACKAGE_FIND_VERSION_TWEAK = tweak version if requested, else 0\n"
191 " PACKAGE_FIND_VERSION_COUNT = number of version components, 0 to 4\n"
192 "The version file checks whether it satisfies the requested version "
193 "and sets these variables:\n"
194 " PACKAGE_VERSION = full provided version string\n"
195 " PACKAGE_VERSION_EXACT = true if version is exact match\n"
196 " PACKAGE_VERSION_COMPATIBLE = true if version is compatible\n"
197 " PACKAGE_VERSION_UNSUITABLE = true if unsuitable as any version\n"
198 "These variables are checked by the find_package command to determine "
199 "whether the configuration file provides an acceptable version. "
200 "They are not available after the find_package call returns. "
201 "If the version is acceptable the following variables are set:\n"
202 " <package>_VERSION = full provided version string\n"
203 " <package>_VERSION_MAJOR = major version if provided, else 0\n"
204 " <package>_VERSION_MINOR = minor version if provided, else 0\n"
205 " <package>_VERSION_PATCH = patch version if provided, else 0\n"
206 " <package>_VERSION_TWEAK = tweak version if provided, else 0\n"
207 " <package>_VERSION_COUNT = number of version components, 0 to 4\n"
208 "and the corresponding package configuration file is loaded. "
209 "When multiple package configuration files are available whose version "
210 "files claim compatibility with the version requested it is unspecified "
211 "which one is chosen. "
212 "No attempt is made to choose a highest or closest version number."
213 "\n"
214 "Config mode provides an elaborate interface and search procedure. "
215 "Much of the interface is provided for completeness and for use "
216 "internally by find-modules loaded by Module mode. "
217 "Most user code should simply call\n"
218 " find_package(<package> [major[.minor]] [EXACT] [REQUIRED|QUIET])\n"
219 "in order to find a package. Package maintainers providing CMake "
220 "package configuration files are encouraged to name and install "
221 "them such that the procedure outlined below will find them "
222 "without requiring use of additional options."
223 "\n"
224 "CMake constructs a set of possible installation prefixes for the "
225 "package. Under each prefix several directories are searched for a "
226 "configuration file. The tables below show the directories searched. "
227 "Each entry is meant for installation trees following Windows (W), "
228 "UNIX (U), or Apple (A) conventions.\n"
229 " <prefix>/ (W)\n"
230 " <prefix>/(cmake|CMake)/ (W)\n"
231 " <prefix>/<name>*/ (W)\n"
232 " <prefix>/<name>*/(cmake|CMake)/ (W)\n"
233 " <prefix>/(share|lib)/cmake/<name>*/ (U)\n"
234 " <prefix>/(share|lib)/<name>*/ (U)\n"
235 " <prefix>/(share|lib)/<name>*/(cmake|CMake)/ (U)\n"
236 "On systems supporting OS X Frameworks and Application Bundles "
237 "the following directories are searched for frameworks or bundles "
238 "containing a configuration file:\n"
239 " <prefix>/<name>.framework/Resources/ (A)\n"
240 " <prefix>/<name>.framework/Resources/CMake/ (A)\n"
241 " <prefix>/<name>.framework/Versions/*/Resources/ (A)\n"
242 " <prefix>/<name>.framework/Versions/*/Resources/CMake/ (A)\n"
243 " <prefix>/<name>.app/Contents/Resources/ (A)\n"
244 " <prefix>/<name>.app/Contents/Resources/CMake/ (A)\n"
245 "In all cases the <name> is treated as case-insensitive and corresponds "
246 "to any of the names specified (<package> or names given by NAMES). "
247 "If PATH_SUFFIXES is specified the suffixes are appended to each "
248 "(W) or (U) directory entry one-by-one.\n"
249 "This set of directories is intended to work in cooperation with "
250 "projects that provide configuration files in their installation trees. "
251 "Directories above marked with (W) are intended for installations on "
252 "Windows where the prefix may point at the top of an application's "
253 "installation directory. Those marked with (U) are intended for "
254 "installations on UNIX platforms where the prefix is shared by "
255 "multiple packages. This is merely a convention, so all (W) and (U) "
256 "directories are still searched on all platforms. "
257 "Directories marked with (A) are intended for installations on "
258 "Apple platforms. The cmake variables CMAKE_FIND_FRAMEWORK and "
259 "CMAKE_FIND_APPBUNDLE determine the order of preference "
260 "as specified below.\n"
261 "The set of installation prefixes is constructed using the following "
262 "steps. If NO_DEFAULT_PATH is specified all NO_* options are enabled.\n"
263 "1. Search paths specified in cmake-specific cache variables. "
264 "These are intended to be used on the command line with a -DVAR=value. "
265 "This can be skipped if NO_CMAKE_PATH is passed.\n"
266 " CMAKE_PREFIX_PATH\n"
267 " CMAKE_FRAMEWORK_PATH\n"
268 " CMAKE_APPBUNDLE_PATH\n"
269 "2. Search paths specified in cmake-specific environment variables. "
270 "These are intended to be set in the user's shell configuration. "
271 "This can be skipped if NO_CMAKE_ENVIRONMENT_PATH is passed.\n"
272 " CMAKE_PREFIX_PATH\n"
273 " CMAKE_FRAMEWORK_PATH\n"
274 " CMAKE_APPBUNDLE_PATH\n"
275 "3. Search paths specified by the HINTS option. "
276 "These should be paths computed by system introspection, such as a "
277 "hint provided by the location of another item already found. "
278 "Hard-coded guesses should be specified with the PATHS option.\n"
279 "4. Search the standard system environment variables. "
280 "This can be skipped if NO_SYSTEM_ENVIRONMENT_PATH is passed. "
281 "Path entries ending in \"/bin\" or \"/sbin\" are automatically "
282 "converted to their parent directories.\n"
283 " PATH\n"
284 "5. Search project build trees recently configured in a CMake GUI. "
285 "This can be skipped if NO_CMAKE_BUILDS_PATH is passed. "
286 "It is intended for the case when a user is building multiple "
287 "dependent projects one after another.\n"
288 "6. Search paths stored in the CMake user package registry. "
289 "This can be skipped if NO_CMAKE_PACKAGE_REGISTRY is passed. "
290 "Paths are stored in the registry when CMake configures a project "
291 "that invokes export(PACKAGE <name>). "
292 "See the export(PACKAGE) command documentation for more details."
293 "\n"
294 "7. Search cmake variables defined in the Platform files "
295 "for the current system. This can be skipped if NO_CMAKE_SYSTEM_PATH "
296 "is passed.\n"
297 " CMAKE_SYSTEM_PREFIX_PATH\n"
298 " CMAKE_SYSTEM_FRAMEWORK_PATH\n"
299 " CMAKE_SYSTEM_APPBUNDLE_PATH\n"
300 "8. Search paths specified by the PATHS option. "
301 "These are typically hard-coded guesses.\n"
303 this->CommandDocumentation += this->GenericDocumentationMacPolicy;
304 this->CommandDocumentation += this->GenericDocumentationRootPath;
305 this->CommandDocumentation += this->GenericDocumentationPathsOrder;
306 this->CommandDocumentation +=
307 "\n"
308 "See the cmake_policy() command documentation for discussion of the "
309 "NO_POLICY_SCOPE option."
313 //----------------------------------------------------------------------------
314 const char* cmFindPackageCommand::GetFullDocumentation()
316 return this->CommandDocumentation.c_str();
319 //----------------------------------------------------------------------------
320 bool cmFindPackageCommand
321 ::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
323 if(args.size() < 1)
325 this->SetError("called with incorrect number of arguments");
326 return false;
329 // Check for debug mode.
330 this->DebugMode = this->Makefile->IsOn("CMAKE_FIND_DEBUG_MODE");
332 // Lookup whether lib64 paths should be used.
333 if(const char* sizeof_dptr =
334 this->Makefile->GetDefinition("CMAKE_SIZEOF_VOID_P"))
336 if(atoi(sizeof_dptr) == 8 &&
337 this->Makefile->GetCMakeInstance()
338 ->GetPropertyAsBool("FIND_LIBRARY_USE_LIB64_PATHS"))
340 this->UseLib64Paths = true;
344 // Find the current root path mode.
345 this->SelectDefaultRootPathMode();
347 // Find the current bundle/framework search policy.
348 this->SelectDefaultMacMode();
350 // Record options.
351 this->Name = args[0];
352 std::string components;
353 const char* components_sep = "";
355 // Check ancient compatibility.
356 this->Compatibility_1_6 =
357 this->Makefile->GetLocalGenerator()
358 ->NeedBackwardsCompatibility(1, 6);
360 // Always search directly in a generated path.
361 this->SearchPathSuffixes.push_back("");
363 // Parse the arguments.
364 enum Doing { DoingNone, DoingComponents, DoingNames, DoingPaths,
365 DoingPathSuffixes, DoingConfigs, DoingHints };
366 Doing doing = DoingNone;
367 cmsys::RegularExpression version("^[0-9.]+$");
368 bool haveVersion = false;
369 for(unsigned int i=1; i < args.size(); ++i)
371 if(args[i] == "QUIET")
373 this->Quiet = true;
374 doing = DoingNone;
376 else if(args[i] == "EXACT")
378 this->VersionExact = true;
379 this->Compatibility_1_6 = false;
380 doing = DoingNone;
382 else if(args[i] == "NO_MODULE")
384 this->NoModule = true;
385 doing = DoingNone;
387 else if(args[i] == "REQUIRED")
389 this->Required = true;
390 doing = DoingComponents;
392 else if(args[i] == "COMPONENTS")
394 this->Compatibility_1_6 = false;
395 doing = DoingComponents;
397 else if(args[i] == "NAMES")
399 this->NoModule = true;
400 this->Compatibility_1_6 = false;
401 doing = DoingNames;
403 else if(args[i] == "PATHS")
405 this->NoModule = true;
406 this->Compatibility_1_6 = false;
407 doing = DoingPaths;
409 else if(args[i] == "HINTS")
411 this->NoModule = true;
412 this->Compatibility_1_6 = false;
413 doing = DoingHints;
415 else if(args[i] == "PATH_SUFFIXES")
417 this->NoModule = true;
418 this->Compatibility_1_6 = false;
419 doing = DoingPathSuffixes;
421 else if(args[i] == "CONFIGS")
423 this->NoModule = true;
424 this->Compatibility_1_6 = false;
425 doing = DoingConfigs;
427 else if(args[i] == "NO_POLICY_SCOPE")
429 this->PolicyScope = false;
430 this->Compatibility_1_6 = false;
431 doing = DoingNone;
433 else if(args[i] == "NO_CMAKE_PACKAGE_REGISTRY")
435 this->NoRegistry = true;
436 this->NoModule = true;
437 this->Compatibility_1_6 = false;
438 doing = DoingNone;
440 else if(args[i] == "NO_CMAKE_BUILDS_PATH")
442 this->NoBuilds = true;
443 this->NoModule = true;
444 this->Compatibility_1_6 = false;
445 doing = DoingNone;
447 else if(this->CheckCommonArgument(args[i]))
449 this->NoModule = true;
450 this->Compatibility_1_6 = false;
451 doing = DoingNone;
453 else if(doing == DoingComponents)
455 // Set a variable telling the find script this component
456 // is required.
457 std::string req_var = this->Name + "_FIND_REQUIRED_" + args[i];
458 this->AddFindDefinition(req_var.c_str(), "1");
460 // Append to the list of required components.
461 components += components_sep;
462 components += args[i];
463 components_sep = ";";
465 else if(doing == DoingNames)
467 this->Names.push_back(args[i]);
469 else if(doing == DoingPaths)
471 this->AddUserPath(args[i], this->UserPaths);
473 else if(doing == DoingHints)
475 this->AddUserPath(args[i], this->UserHints);
477 else if(doing == DoingPathSuffixes)
479 this->AddPathSuffix(args[i]);
481 else if(doing == DoingConfigs)
483 if(args[i].find_first_of(":/\\") != args[i].npos ||
484 cmSystemTools::GetFilenameLastExtension(args[i]) != ".cmake")
486 cmOStringStream e;
487 e << "given CONFIGS option followed by invalid file name \""
488 << args[i] << "\". The names given must be file names without "
489 << "a path and with a \".cmake\" extension.";
490 return false;
492 this->Configs.push_back(args[i]);
494 else if(!haveVersion && version.find(args[i].c_str()))
496 haveVersion = true;
497 this->Version = args[i];
499 else
501 cmOStringStream e;
502 e << "called with invalid argument \"" << args[i].c_str() << "\"";
503 this->SetError(e.str().c_str());
504 return false;
508 // Ignore EXACT with no version.
509 if(this->Version.empty() && this->VersionExact)
511 this->VersionExact = false;
512 this->Makefile->IssueMessage(
513 cmake::AUTHOR_WARNING, "Ignoring EXACT since no version is requested.");
516 if(this->Version.empty())
518 // Check whether we are recursing inside "Find<name>.cmake" within
519 // another find_package(<name>) call.
520 std::string mod = this->Name;
521 mod += "_FIND_MODULE";
522 if(this->Makefile->IsOn(mod.c_str()))
524 // Get version information from the outer call if necessary.
525 // Requested version string.
526 std::string ver = this->Name;
527 ver += "_FIND_VERSION";
528 this->Version = this->Makefile->GetSafeDefinition(ver.c_str());
530 // Whether an exact version is required.
531 std::string exact = this->Name;
532 exact += "_FIND_VERSION_EXACT";
533 this->VersionExact = this->Makefile->IsOn(exact.c_str());
537 if(!this->Version.empty())
539 // Try to parse the version number and store the results that were
540 // successfully parsed.
541 unsigned int parsed_major;
542 unsigned int parsed_minor;
543 unsigned int parsed_patch;
544 unsigned int parsed_tweak;
545 this->VersionCount = sscanf(this->Version.c_str(), "%u.%u.%u.%u",
546 &parsed_major, &parsed_minor,
547 &parsed_patch, &parsed_tweak);
548 switch(this->VersionCount)
550 case 4: this->VersionTweak = parsed_tweak; // no break!
551 case 3: this->VersionPatch = parsed_patch; // no break!
552 case 2: this->VersionMinor = parsed_minor; // no break!
553 case 1: this->VersionMajor = parsed_major; // no break!
554 default: break;
558 this->SetModuleVariables(components);
560 // See if there is a Find<package>.cmake module.
561 if(!this->NoModule)
563 bool foundModule = false;
564 if(!this->FindModule(foundModule))
566 this->AppendSuccessInformation();
567 return false;
569 if(foundModule)
571 this->AppendSuccessInformation();
572 return true;
576 // No find module. Assume the project has a CMake config file. Use
577 // a <package>_DIR cache variable to locate it.
578 this->Variable = this->Name;
579 this->Variable += "_DIR";
581 // Add the default name.
582 if(this->Names.empty())
584 this->Names.push_back(this->Name);
587 // Add the default configs.
588 if(this->Configs.empty())
590 for(std::vector<std::string>::const_iterator ni = this->Names.begin();
591 ni != this->Names.end(); ++ni)
593 std::string config = *ni;
594 config += "Config.cmake";
595 this->Configs.push_back(config);
597 config = cmSystemTools::LowerCase(*ni);
598 config += "-config.cmake";
599 this->Configs.push_back(config);
603 // Find and load the package.
604 bool result = this->HandlePackageMode();
605 this->AppendSuccessInformation();
606 return result;
610 //----------------------------------------------------------------------------
611 void cmFindPackageCommand::SetModuleVariables(const std::string& components)
613 // Store the list of components.
614 std::string components_var = this->Name + "_FIND_COMPONENTS";
615 this->AddFindDefinition(components_var.c_str(), components.c_str());
617 if(this->Quiet)
619 // Tell the module that is about to be read that it should find
620 // quietly.
621 std::string quietly = this->Name;
622 quietly += "_FIND_QUIETLY";
623 this->AddFindDefinition(quietly.c_str(), "1");
626 if(this->Required)
628 // Tell the module that is about to be read that it should report
629 // a fatal error if the package is not found.
630 std::string req = this->Name;
631 req += "_FIND_REQUIRED";
632 this->AddFindDefinition(req.c_str(), "1");
635 if(!this->Version.empty())
637 // Tell the module that is about to be read what version of the
638 // package has been requested.
639 std::string ver = this->Name;
640 ver += "_FIND_VERSION";
641 this->AddFindDefinition(ver.c_str(), this->Version.c_str());
642 char buf[64];
643 sprintf(buf, "%u", this->VersionMajor);
644 this->AddFindDefinition((ver+"_MAJOR").c_str(), buf);
645 sprintf(buf, "%u", this->VersionMinor);
646 this->AddFindDefinition((ver+"_MINOR").c_str(), buf);
647 sprintf(buf, "%u", this->VersionPatch);
648 this->AddFindDefinition((ver+"_PATCH").c_str(), buf);
649 sprintf(buf, "%u", this->VersionTweak);
650 this->AddFindDefinition((ver+"_TWEAK").c_str(), buf);
651 sprintf(buf, "%u", this->VersionCount);
652 this->AddFindDefinition((ver+"_COUNT").c_str(), buf);
654 // Tell the module whether an exact version has been requested.
655 std::string exact = this->Name;
656 exact += "_FIND_VERSION_EXACT";
657 this->AddFindDefinition(exact.c_str(), this->VersionExact? "1":"0");
661 //----------------------------------------------------------------------------
662 void cmFindPackageCommand::AddFindDefinition(const char* var, const char* val)
664 if(const char* old = this->Makefile->GetDefinition(var))
666 this->OriginalDefs[var].exists = true;
667 this->OriginalDefs[var].value = old;
669 else
671 this->OriginalDefs[var].exists = false;
673 this->Makefile->AddDefinition(var, val);
676 //----------------------------------------------------------------------------
677 void cmFindPackageCommand::RestoreFindDefinitions()
679 for(std::map<cmStdString, OriginalDef>::iterator
680 i = this->OriginalDefs.begin(); i != this->OriginalDefs.end(); ++i)
682 OriginalDef const& od = i->second;
683 if(od.exists)
685 this->Makefile->AddDefinition(i->first.c_str(), od.value.c_str());
687 else
689 this->Makefile->RemoveDefinition(i->first.c_str());
694 //----------------------------------------------------------------------------
695 bool cmFindPackageCommand::FindModule(bool& found)
697 std::string module = "Find";
698 module += this->Name;
699 module += ".cmake";
700 std::string mfile = this->Makefile->GetModulesFile(module.c_str());
701 if ( mfile.size() )
703 // Load the module we found, and set "<name>_FIND_MODULE" to true
704 // while inside it.
705 found = true;
706 std::string var = this->Name;
707 var += "_FIND_MODULE";
708 this->Makefile->AddDefinition(var.c_str(), "1");
709 bool result = this->ReadListFile(mfile.c_str(), DoPolicyScope);
710 this->Makefile->RemoveDefinition(var.c_str());
711 return result;
713 return true;
716 //----------------------------------------------------------------------------
717 bool cmFindPackageCommand::HandlePackageMode()
719 // Support old capitalization behavior.
720 std::string upperDir = cmSystemTools::UpperCase(this->Name);
721 std::string upperFound = cmSystemTools::UpperCase(this->Name);
722 upperDir += "_DIR";
723 upperFound += "_FOUND";
724 if(upperDir == this->Variable)
726 this->Compatibility_1_6 = false;
729 // Try to find the config file.
730 const char* def = this->Makefile->GetDefinition(this->Variable.c_str());
731 if(this->Compatibility_1_6 && cmSystemTools::IsOff(def))
733 // Use the setting of the old name of the variable to provide the
734 // value of the new.
735 const char* oldDef = this->Makefile->GetDefinition(upperDir.c_str());
736 if(!cmSystemTools::IsOff(oldDef))
738 this->Makefile->AddDefinition(this->Variable.c_str(), oldDef);
739 def = this->Makefile->GetDefinition(this->Variable.c_str());
743 // Try to load the config file if the directory is known
744 bool cachedDirectoryOk = false;
745 if(!cmSystemTools::IsOff(def))
747 // Get the directory from the variable value.
748 std::string dir = def;
749 cmSystemTools::ConvertToUnixSlashes(dir);
751 // Treat relative paths with respect to the current source dir.
752 if(!cmSystemTools::FileIsFullPath(dir.c_str()))
754 dir = "/" + dir;
755 dir = this->Makefile->GetCurrentDirectory() + dir;
757 // The file location was cached. Look for the correct file.
758 std::string file;
759 if (this->FindConfigFile(dir, file))
761 this->FileFound = file;
762 cachedDirectoryOk = true;
764 def = this->Makefile->GetDefinition(this->Variable.c_str());
767 // Search for the config file if it is not already found.
768 if(cmSystemTools::IsOff(def) || !cachedDirectoryOk)
770 this->FindConfig();
771 def = this->Makefile->GetDefinition(this->Variable.c_str());
774 // If the directory for the config file was found, try to read the file.
775 bool result = true;
776 bool found = false;
777 // in the following test FileFound should never be empty if def is valid
778 // but I don't want to put an assert() in there now, in case this still
779 // makes it into 2.6.3
780 if(!cmSystemTools::IsOff(def) && (!this->FileFound.empty()))
782 // Set the version variables before loading the config file.
783 // It may override them.
784 this->StoreVersionFound();
786 // Parse the configuration file.
787 if(this->ReadListFile(this->FileFound.c_str(), DoPolicyScope))
789 // The package has been found.
790 found = true;
792 else
794 // The configuration file is invalid.
795 result = false;
798 else if(!this->Quiet || this->Required)
800 // The variable is not set.
801 cmOStringStream e;
802 e << "Could not find ";
803 if(!this->NoModule)
805 e << "module Find" << this->Name << ".cmake or ";
807 e << "a configuration file for package " << this->Name << ".\n";
808 if(!this->NoModule)
810 e << "Adjust CMAKE_MODULE_PATH to find Find"
811 << this->Name << ".cmake or set ";
813 else
815 e << "Set ";
817 e << this->Variable << " to the directory containing a CMake "
818 << "configuration file for " << this->Name << ". ";
819 if(this->Configs.size() == 1)
821 e << "The file will be called " << this->Configs[0];
823 else
825 e << "The file will have one of the following names:\n";
826 for(std::vector<std::string>::const_iterator ci = this->Configs.begin();
827 ci != this->Configs.end(); ++ci)
829 e << " " << *ci << "\n";
832 this->Makefile->IssueMessage(
833 this->Required? cmake::FATAL_ERROR : cmake::WARNING, e.str());
836 // Set a variable marking whether the package was found.
837 std::string foundVar = this->Name;
838 foundVar += "_FOUND";
839 this->Makefile->AddDefinition(foundVar.c_str(), found? "1":"0");
841 // Set a variable naming the configuration file that was found.
842 std::string fileVar = this->Name;
843 fileVar += "_CONFIG";
844 if(found)
846 this->Makefile->AddDefinition(fileVar.c_str(), this->FileFound.c_str());
848 else
850 this->Makefile->RemoveDefinition(fileVar.c_str());
853 // Handle some ancient compatibility stuff.
854 if(this->Compatibility_1_6)
856 // Listfiles will be looking for the capitalized version of the
857 // name. Provide it.
858 this->Makefile->AddDefinition
859 (upperDir.c_str(),
860 this->Makefile->GetDefinition(this->Variable.c_str()));
861 this->Makefile->AddDefinition
862 (upperFound.c_str(),
863 this->Makefile->GetDefinition(foundVar.c_str()));
866 #ifdef CMAKE_BUILD_WITH_CMAKE
867 if(!(upperDir == this->Variable))
869 if(this->Compatibility_1_6)
871 // Listfiles may use the capitalized version of the name.
872 // Remove any previously added watch.
873 this->Makefile->GetVariableWatch()->RemoveWatch(
874 upperDir.c_str(),
875 cmFindPackageNeedBackwardsCompatibility
878 else
880 // Listfiles should not be using the capitalized version of the
881 // name. Add a watch to warn the user.
882 this->Makefile->GetVariableWatch()->AddWatch(
883 upperDir.c_str(),
884 cmFindPackageNeedBackwardsCompatibility
888 #endif
890 return result;
893 //----------------------------------------------------------------------------
894 void cmFindPackageCommand::FindConfig()
896 // Compute the set of search prefixes.
897 this->ComputePrefixes();
899 // Look for the project's configuration file.
900 bool found = false;
902 // Search for frameworks.
903 if(!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly))
905 found = this->FindFrameworkConfig();
908 // Search for apps.
909 if(!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly))
911 found = this->FindAppBundleConfig();
914 // Search prefixes.
915 if(!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly))
917 found = this->FindPrefixedConfig();
920 // Search for frameworks.
921 if(!found && this->SearchFrameworkLast)
923 found = this->FindFrameworkConfig();
926 // Search for apps.
927 if(!found && this->SearchAppBundleLast)
929 found = this->FindAppBundleConfig();
932 // Store the entry in the cache so it can be set by the user.
933 std::string init;
934 if(found)
936 init = cmSystemTools::GetFilenamePath(this->FileFound);
938 else
940 init = this->Variable + "-NOTFOUND";
942 std::string help =
943 "The directory containing a CMake configuration file for ";
944 help += this->Name;
945 help += ".";
946 this->Makefile->AddCacheDefinition(this->Variable.c_str(),
947 init.c_str(), help.c_str(),
948 cmCacheManager::PATH);
951 //----------------------------------------------------------------------------
952 bool cmFindPackageCommand::FindPrefixedConfig()
954 std::vector<std::string>& prefixes = this->SearchPaths;
955 for(std::vector<std::string>::const_iterator pi = prefixes.begin();
956 pi != prefixes.end(); ++pi)
958 if(this->SearchPrefix(*pi))
960 return true;
963 return false;
966 //----------------------------------------------------------------------------
967 bool cmFindPackageCommand::FindFrameworkConfig()
969 std::vector<std::string>& prefixes = this->SearchPaths;
970 for(std::vector<std::string>::const_iterator i = prefixes.begin();
971 i != prefixes.end(); ++i)
973 if(this->SearchFrameworkPrefix(*i))
975 return true;
978 return false;
981 //----------------------------------------------------------------------------
982 bool cmFindPackageCommand::FindAppBundleConfig()
984 std::vector<std::string>& prefixes = this->SearchPaths;
985 for(std::vector<std::string>::const_iterator i = prefixes.begin();
986 i != prefixes.end(); ++i)
988 if(this->SearchAppBundlePrefix(*i))
990 return true;
993 return false;
996 //----------------------------------------------------------------------------
997 bool cmFindPackageCommand::ReadListFile(const char* f, PolicyScopeRule psr)
999 if(this->Makefile->ReadListFile(this->Makefile->GetCurrentListFile(), f, 0,
1000 !this->PolicyScope || psr == NoPolicyScope))
1002 return true;
1004 std::string e = "Error reading CMake code from \"";
1005 e += f;
1006 e += "\".";
1007 this->SetError(e.c_str());
1008 return false;
1011 //----------------------------------------------------------------------------
1012 void cmFindPackageCommand::AppendToProperty(const char* propertyName)
1014 std::string propertyValue;
1015 const char *prop =
1016 this->Makefile->GetCMakeInstance()->GetProperty(propertyName);
1017 if (prop && *prop)
1019 propertyValue = prop;
1021 std::vector<std::string> contents;
1022 cmSystemTools::ExpandListArgument(propertyValue, contents, false);
1024 bool alreadyInserted = false;
1025 for(std::vector<std::string>::const_iterator it = contents.begin();
1026 it != contents.end(); ++ it )
1028 if (*it == this->Name)
1030 alreadyInserted = true;
1031 break;
1034 if (!alreadyInserted)
1036 propertyValue += ";";
1037 propertyValue += this->Name;
1040 else
1042 propertyValue = this->Name;
1044 this->Makefile->GetCMakeInstance()->SetProperty(propertyName,
1045 propertyValue.c_str());
1048 //----------------------------------------------------------------------------
1049 void cmFindPackageCommand::AppendSuccessInformation()
1051 std::string found = this->Name;
1052 found += "_FOUND";
1053 std::string upperFound = cmSystemTools::UpperCase(found);
1055 const char* upperResult = this->Makefile->GetDefinition(upperFound.c_str());
1056 const char* result = this->Makefile->GetDefinition(found.c_str());
1057 if ((cmSystemTools::IsOn(result)) || (cmSystemTools::IsOn(upperResult)))
1059 this->AppendToProperty("PACKAGES_FOUND");
1060 if (!this->Quiet)
1062 this->AppendToProperty("ENABLED_FEATURES");
1065 else
1067 this->AppendToProperty("PACKAGES_NOT_FOUND");
1068 if (!this->Quiet)
1070 this->AppendToProperty("DISABLED_FEATURES");
1074 // Restore original state of "_FIND_" variables we set.
1075 this->RestoreFindDefinitions();
1078 //----------------------------------------------------------------------------
1079 void cmFindPackageCommand::ComputePrefixes()
1081 this->AddPrefixesCMakeVariable();
1082 this->AddPrefixesCMakeEnvironment();
1083 this->AddPrefixesUserHints();
1084 this->AddPrefixesSystemEnvironment();
1085 this->AddPrefixesRegistry();
1086 this->AddPrefixesBuilds();
1087 this->AddPrefixesCMakeSystemVariable();
1088 this->AddPrefixesUserGuess();
1089 this->ComputeFinalPrefixes();
1092 //----------------------------------------------------------------------------
1093 void cmFindPackageCommand::AddPrefixesCMakeEnvironment()
1095 if(!this->NoCMakeEnvironmentPath && !this->NoDefaultPath)
1097 // Check the environment variable with the same name as the cache
1098 // entry.
1099 std::string env;
1100 if(cmSystemTools::GetEnv(this->Variable.c_str(), env) && env.length() > 0)
1102 cmSystemTools::ConvertToUnixSlashes(env);
1103 this->AddPathInternal(env, EnvPath);
1106 this->AddEnvPath("CMAKE_PREFIX_PATH");
1107 this->AddEnvPath("CMAKE_FRAMEWORK_PATH");
1108 this->AddEnvPath("CMAKE_APPBUNDLE_PATH");
1112 //----------------------------------------------------------------------------
1113 void cmFindPackageCommand::AddPrefixesCMakeVariable()
1115 if(!this->NoCMakePath && !this->NoDefaultPath)
1117 this->AddCMakePath("CMAKE_PREFIX_PATH");
1118 this->AddCMakePath("CMAKE_FRAMEWORK_PATH");
1119 this->AddCMakePath("CMAKE_APPBUNDLE_PATH");
1123 //----------------------------------------------------------------------------
1124 void cmFindPackageCommand::AddPrefixesSystemEnvironment()
1126 if(!this->NoSystemEnvironmentPath && !this->NoDefaultPath)
1128 // Use the system search path to generate prefixes.
1129 // Relative paths are interpreted with respect to the current
1130 // working directory.
1131 std::vector<std::string> tmp;
1132 cmSystemTools::GetPath(tmp);
1133 for(std::vector<std::string>::iterator i = tmp.begin();
1134 i != tmp.end(); ++i)
1136 std::string const& d = *i;
1138 // If the path is a PREFIX/bin case then add its parent instead.
1139 if((d.size() >= 4 && strcmp(d.c_str()+d.size()-4, "/bin") == 0) ||
1140 (d.size() >= 5 && strcmp(d.c_str()+d.size()-5, "/sbin") == 0))
1142 this->AddPathInternal(cmSystemTools::GetFilenamePath(d), EnvPath);
1144 else
1146 this->AddPathInternal(d, EnvPath);
1152 //----------------------------------------------------------------------------
1153 void cmFindPackageCommand::AddPrefixesRegistry()
1155 if(this->NoRegistry || this->NoDefaultPath)
1157 return;
1160 #if defined(_WIN32) && !defined(__CYGWIN__)
1161 this->LoadPackageRegistryWin();
1162 #else
1163 if(const char* home = cmSystemTools::GetEnv("HOME"))
1165 std::string dir = home;
1166 dir += "/.cmake/packages/";
1167 dir += this->Name;
1168 this->LoadPackageRegistryDir(dir);
1170 #endif
1173 #if defined(_WIN32) && !defined(__CYGWIN__)
1174 # include <windows.h>
1175 # undef GetCurrentDirectory
1176 //----------------------------------------------------------------------------
1177 void cmFindPackageCommand::LoadPackageRegistryWin()
1179 std::string key = "Software\\Kitware\\CMake\\Packages\\";
1180 key += this->Name;
1181 std::set<cmStdString> bad;
1182 HKEY hKey;
1183 if(RegOpenKeyEx(HKEY_CURRENT_USER, key.c_str(),
1184 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
1186 DWORD valueType = REG_NONE;
1187 char name[16384];
1188 std::vector<char> data(512);
1189 bool done = false;
1190 DWORD index = 0;
1191 while(!done)
1193 DWORD nameSize = static_cast<DWORD>(sizeof(name));
1194 DWORD dataSize = static_cast<DWORD>(data.size()-1);
1195 switch(RegEnumValue(hKey, index, name, &nameSize,
1196 0, &valueType, (BYTE*)&data[0], &dataSize))
1198 case ERROR_SUCCESS:
1199 ++index;
1200 if(valueType == REG_SZ)
1202 data[dataSize] = 0;
1203 cmsys_ios::stringstream ss(&data[0]);
1204 if(this->CheckPackageRegistryEntry(ss))
1206 // The entry is okay.
1207 continue;
1210 bad.insert(name);
1211 break;
1212 case ERROR_MORE_DATA:
1213 data.resize(dataSize+1);
1214 break;
1215 case ERROR_NO_MORE_ITEMS: default: done = true; break;
1218 RegCloseKey(hKey);
1221 // Remove bad values if possible.
1222 if(!bad.empty() &&
1223 RegOpenKeyEx(HKEY_CURRENT_USER, key.c_str(),
1224 0, KEY_SET_VALUE, &hKey) == ERROR_SUCCESS)
1226 for(std::set<cmStdString>::const_iterator vi = bad.begin();
1227 vi != bad.end(); ++vi)
1229 RegDeleteValue(hKey, vi->c_str());
1231 RegCloseKey(hKey);
1234 #else
1235 //----------------------------------------------------------------------------
1236 class cmFindPackageCommandHoldFile
1238 const char* File;
1239 public:
1240 cmFindPackageCommandHoldFile(const char* f): File(f) {}
1241 ~cmFindPackageCommandHoldFile()
1242 { if(this->File) { cmSystemTools::RemoveFile(this->File); } }
1243 void Release() { this->File = 0; }
1246 //----------------------------------------------------------------------------
1247 void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir)
1249 cmsys::Directory files;
1250 if(!files.Load(dir.c_str()))
1252 return;
1255 std::string fname;
1256 for(unsigned long i=0; i < files.GetNumberOfFiles(); ++i)
1258 fname = dir;
1259 fname += "/";
1260 fname += files.GetFile(i);
1262 if(!cmSystemTools::FileIsDirectory(fname.c_str()))
1264 // Hold this file hostage until it behaves.
1265 cmFindPackageCommandHoldFile holdFile(fname.c_str());
1267 // Load the file.
1268 std::ifstream fin(fname.c_str(), std::ios::in | cmsys_ios_binary);
1269 if(fin && this->CheckPackageRegistryEntry(fin))
1271 // The file references an existing package, so release it.
1272 holdFile.Release();
1277 // TODO: Wipe out the directory if it is empty.
1279 #endif
1281 //----------------------------------------------------------------------------
1282 bool cmFindPackageCommand::CheckPackageRegistryEntry(std::istream& is)
1284 // Parse the content of one package registry entry.
1285 std::string fname;
1286 if(cmSystemTools::GetLineFromStream(is, fname) &&
1287 cmSystemTools::FileIsFullPath(fname.c_str()))
1289 // The first line in the stream is the full path to a file or
1290 // directory containing the package.
1291 if(cmSystemTools::FileExists(fname.c_str()))
1293 // The path exists. Look for the package here.
1294 if(!cmSystemTools::FileIsDirectory(fname.c_str()))
1296 fname = cmSystemTools::GetFilenamePath(fname);
1298 this->AddPathInternal(fname, FullPath);
1299 return true;
1301 else
1303 // The path does not exist. Assume the stream content is
1304 // associated with an old package that no longer exists, and
1305 // delete it to keep the package registry clean.
1306 return false;
1309 else
1311 // The first line in the stream is not the full path to a file or
1312 // directory. Assume the stream content was created by a future
1313 // version of CMake that uses a different format, and leave it.
1314 return true;
1318 //----------------------------------------------------------------------------
1319 void cmFindPackageCommand::AddPrefixesBuilds()
1321 if(!this->NoBuilds && !this->NoDefaultPath)
1323 // It is likely that CMake will have recently built the project.
1324 for(int i=0; i <= 10; ++i)
1326 cmOStringStream r;
1327 r <<
1328 "[HKEY_CURRENT_USER\\Software\\Kitware\\CMakeSetup\\"
1329 "Settings\\StartPath;WhereBuild" << i << "]";
1330 std::string f = r.str();
1331 cmSystemTools::ExpandRegistryValues(f);
1332 cmSystemTools::ConvertToUnixSlashes(f);
1333 if(cmSystemTools::FileIsFullPath(f.c_str()) &&
1334 cmSystemTools::FileIsDirectory(f.c_str()))
1336 this->AddPathInternal(f, FullPath);
1342 //----------------------------------------------------------------------------
1343 void cmFindPackageCommand::AddPrefixesCMakeSystemVariable()
1345 if(!this->NoCMakeSystemPath && !this->NoDefaultPath)
1347 this->AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
1348 this->AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
1349 this->AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
1353 //----------------------------------------------------------------------------
1354 void cmFindPackageCommand::AddPrefixesUserGuess()
1356 // Add guesses specified by the caller.
1357 this->AddPathsInternal(this->UserPaths, CMakePath);
1360 //----------------------------------------------------------------------------
1361 void cmFindPackageCommand::AddPrefixesUserHints()
1363 // Add hints specified by the caller.
1364 this->AddPathsInternal(this->UserHints, CMakePath);
1367 //----------------------------------------------------------------------------
1368 void cmFindPackageCommand::ComputeFinalPrefixes()
1370 std::vector<std::string>& prefixes = this->SearchPaths;
1372 // Construct the final set of prefixes.
1373 this->RerootPaths(prefixes);
1375 // Add a trailing slash to all prefixes to aid the search process.
1376 this->AddTrailingSlashes(prefixes);
1379 //----------------------------------------------------------------------------
1380 bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
1382 assert(!dir.empty() && dir[dir.size()-1] == '/');
1384 // Check each path suffix on this directory.
1385 for(std::vector<std::string>::const_iterator
1386 si = this->SearchPathSuffixes.begin();
1387 si != this->SearchPathSuffixes.end(); ++si)
1389 std::string d = dir;
1390 if(!si->empty())
1392 d += *si;
1393 d += "/";
1395 if(this->CheckDirectory(d))
1397 return true;
1400 return false;
1403 //----------------------------------------------------------------------------
1404 bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
1406 assert(!dir.empty() && dir[dir.size()-1] == '/');
1408 // Look for the file in this directory.
1409 std::string d = dir.substr(0, dir.size()-1);
1410 if(this->FindConfigFile(d, this->FileFound))
1412 // Remove duplicate slashes.
1413 cmSystemTools::ConvertToUnixSlashes(this->FileFound);
1414 return true;
1416 return false;
1419 //----------------------------------------------------------------------------
1420 bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
1421 std::string& file)
1423 for(std::vector<std::string>::const_iterator ci = this->Configs.begin();
1424 ci != this->Configs.end(); ++ci)
1426 file = dir;
1427 file += "/";
1428 file += *ci;
1429 if(this->DebugMode)
1431 fprintf(stderr, "Checking file [%s]\n", file.c_str());
1433 if(cmSystemTools::FileExists(file.c_str(), true) &&
1434 this->CheckVersion(file))
1436 return true;
1439 return false;
1442 //----------------------------------------------------------------------------
1443 bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
1445 // Get the filename without the .cmake extension.
1446 std::string::size_type pos = config_file.rfind('.');
1447 std::string version_file_base = config_file.substr(0, pos);
1449 // Look for foo-config-version.cmake
1450 std::string version_file = version_file_base;
1451 version_file += "-version.cmake";
1452 if(cmSystemTools::FileExists(version_file.c_str(), true))
1454 return this->CheckVersionFile(version_file);
1457 // Look for fooConfigVersion.cmake
1458 version_file = version_file_base;
1459 version_file += "Version.cmake";
1460 if(cmSystemTools::FileExists(version_file.c_str(), true))
1462 return this->CheckVersionFile(version_file);
1465 // If no version was requested a versionless package is acceptable.
1466 if(this->Version.empty())
1468 return true;
1471 // No version file found. Assume the version is incompatible.
1472 return false;
1475 //----------------------------------------------------------------------------
1476 bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file)
1478 // The version file will be loaded in an isolated scope.
1479 cmMakefile::ScopePushPop varScope(this->Makefile);
1480 cmMakefile::PolicyPushPop polScope(this->Makefile);
1481 static_cast<void>(varScope);
1482 static_cast<void>(polScope);
1484 // Clear the output variables.
1485 this->Makefile->RemoveDefinition("PACKAGE_VERSION");
1486 this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
1487 this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
1488 this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
1490 // Set the input variables.
1491 this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name.c_str());
1492 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION",
1493 this->Version.c_str());
1494 char buf[64];
1495 sprintf(buf, "%u", this->VersionMajor);
1496 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MAJOR", buf);
1497 sprintf(buf, "%u", this->VersionMinor);
1498 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MINOR", buf);
1499 sprintf(buf, "%u", this->VersionPatch);
1500 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_PATCH", buf);
1501 sprintf(buf, "%u", this->VersionTweak);
1502 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_TWEAK", buf);
1503 sprintf(buf, "%u", this->VersionCount);
1504 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COUNT", buf);
1506 // Load the version check file. Pass NoPolicyScope because we do
1507 // our own policy push/pop independent of CMP0011.
1508 bool suitable = false;
1509 if(this->ReadListFile(version_file.c_str(), NoPolicyScope))
1511 // Check the output variables.
1512 bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
1513 bool unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
1514 if(!okay && !this->VersionExact)
1516 okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
1519 // The package is suitable if the version is okay and not
1520 // explicitly unsuitable.
1521 suitable = !unsuitable && (okay || this->Version.empty());
1522 if(suitable)
1524 // Get the version found.
1525 this->VersionFound =
1526 this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
1528 // Try to parse the version number and store the results that were
1529 // successfully parsed.
1530 unsigned int parsed_major;
1531 unsigned int parsed_minor;
1532 unsigned int parsed_patch;
1533 unsigned int parsed_tweak;
1534 this->VersionFoundCount =
1535 sscanf(this->VersionFound.c_str(), "%u.%u.%u.%u",
1536 &parsed_major, &parsed_minor,
1537 &parsed_patch, &parsed_tweak);
1538 switch(this->VersionFoundCount)
1540 case 4: this->VersionFoundTweak = parsed_tweak; // no break!
1541 case 3: this->VersionFoundPatch = parsed_patch; // no break!
1542 case 2: this->VersionFoundMinor = parsed_minor; // no break!
1543 case 1: this->VersionFoundMajor = parsed_major; // no break!
1544 default: break;
1549 // Succeed if the version is suitable.
1550 return suitable;
1553 //----------------------------------------------------------------------------
1554 void cmFindPackageCommand::StoreVersionFound()
1556 // Store the whole version string.
1557 std::string ver = this->Name;
1558 ver += "_VERSION";
1559 if(this->VersionFound.empty())
1561 this->Makefile->RemoveDefinition(ver.c_str());
1563 else
1565 this->Makefile->AddDefinition(ver.c_str(), this->VersionFound.c_str());
1568 // Store the version components.
1569 char buf[64];
1570 sprintf(buf, "%u", this->VersionFoundMajor);
1571 this->Makefile->AddDefinition((ver+"_MAJOR").c_str(), buf);
1572 sprintf(buf, "%u", this->VersionFoundMinor);
1573 this->Makefile->AddDefinition((ver+"_MINOR").c_str(), buf);
1574 sprintf(buf, "%u", this->VersionFoundPatch);
1575 this->Makefile->AddDefinition((ver+"_PATCH").c_str(), buf);
1576 sprintf(buf, "%u", this->VersionFoundTweak);
1577 this->Makefile->AddDefinition((ver+"_TWEAK").c_str(), buf);
1578 sprintf(buf, "%u", this->VersionFoundCount);
1579 this->Makefile->AddDefinition((ver+"_COUNT").c_str(), buf);
1582 //----------------------------------------------------------------------------
1583 #include <cmsys/Glob.hxx>
1584 #include <cmsys/String.h>
1585 #include <cmsys/auto_ptr.hxx>
1587 class cmFileList;
1588 class cmFileListGeneratorBase
1590 public:
1591 virtual ~cmFileListGeneratorBase() {}
1592 protected:
1593 bool Consider(std::string const& fullPath, cmFileList& listing);
1594 private:
1595 bool Search(cmFileList&);
1596 virtual bool Search(std::string const& parent, cmFileList&) = 0;
1597 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const = 0;
1598 friend class cmFileList;
1599 cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next);
1600 cmsys::auto_ptr<cmFileListGeneratorBase> Next;
1603 class cmFileList
1605 public:
1606 cmFileList(): First(), Last(0) {}
1607 virtual ~cmFileList() {}
1608 cmFileList& operator/(cmFileListGeneratorBase const& rhs)
1610 if(this->Last)
1612 this->Last = this->Last->SetNext(rhs);
1614 else
1616 this->First = rhs.Clone();
1617 this->Last = this->First.get();
1619 return *this;
1621 bool Search()
1623 if(this->First.get())
1625 return this->First->Search(*this);
1627 return false;
1629 private:
1630 virtual bool Visit(std::string const& fullPath) = 0;
1631 friend class cmFileListGeneratorBase;
1632 cmsys::auto_ptr<cmFileListGeneratorBase> First;
1633 cmFileListGeneratorBase* Last;
1636 class cmFindPackageFileList: public cmFileList
1638 public:
1639 cmFindPackageFileList(cmFindPackageCommand* fpc,
1640 bool use_suffixes = true):
1641 cmFileList(), FPC(fpc), UseSuffixes(use_suffixes) {}
1642 private:
1643 bool Visit(std::string const& fullPath)
1645 if(this->UseSuffixes)
1647 return this->FPC->SearchDirectory(fullPath);
1649 else
1651 return this->FPC->CheckDirectory(fullPath);
1654 cmFindPackageCommand* FPC;
1655 bool UseSuffixes;
1658 bool cmFileListGeneratorBase::Search(cmFileList& listing)
1660 return this->Search("", listing);
1663 cmFileListGeneratorBase*
1664 cmFileListGeneratorBase::SetNext(cmFileListGeneratorBase const& next)
1666 this->Next = next.Clone();
1667 return this->Next.get();
1670 bool cmFileListGeneratorBase::Consider(std::string const& fullPath,
1671 cmFileList& listing)
1673 if(this->Next.get())
1675 return this->Next->Search(fullPath + "/", listing);
1677 else
1679 return listing.Visit(fullPath + "/");
1683 class cmFileListGeneratorFixed: public cmFileListGeneratorBase
1685 public:
1686 cmFileListGeneratorFixed(std::string const& str):
1687 cmFileListGeneratorBase(), String(str) {}
1688 cmFileListGeneratorFixed(cmFileListGeneratorFixed const& r):
1689 cmFileListGeneratorBase(), String(r.String) {}
1690 private:
1691 std::string String;
1692 virtual bool Search(std::string const& parent, cmFileList& lister)
1694 std::string fullPath = parent + this->String;
1695 return this->Consider(fullPath, lister);
1697 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1699 cmsys::auto_ptr<cmFileListGeneratorBase>
1700 g(new cmFileListGeneratorFixed(*this));
1701 return g;
1705 class cmFileListGeneratorEnumerate: public cmFileListGeneratorBase
1707 public:
1708 cmFileListGeneratorEnumerate(std::vector<std::string> const& v):
1709 cmFileListGeneratorBase(), Vector(v) {}
1710 cmFileListGeneratorEnumerate(cmFileListGeneratorEnumerate const& r):
1711 cmFileListGeneratorBase(), Vector(r.Vector) {}
1712 private:
1713 std::vector<std::string> const& Vector;
1714 virtual bool Search(std::string const& parent, cmFileList& lister)
1716 for(std::vector<std::string>::const_iterator i = this->Vector.begin();
1717 i != this->Vector.end(); ++i)
1719 if(this->Consider(parent + *i, lister))
1721 return true;
1724 return false;
1726 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1728 cmsys::auto_ptr<cmFileListGeneratorBase>
1729 g(new cmFileListGeneratorEnumerate(*this));
1730 return g;
1734 class cmFileListGeneratorProject: public cmFileListGeneratorBase
1736 public:
1737 cmFileListGeneratorProject(std::vector<std::string> const& names):
1738 cmFileListGeneratorBase(), Names(names) {}
1739 cmFileListGeneratorProject(cmFileListGeneratorProject const& r):
1740 cmFileListGeneratorBase(), Names(r.Names) {}
1741 private:
1742 std::vector<std::string> const& Names;
1743 virtual bool Search(std::string const& parent, cmFileList& lister)
1745 // Construct a list of matches.
1746 std::vector<std::string> matches;
1747 cmsys::Directory d;
1748 d.Load(parent.c_str());
1749 for(unsigned long i=0; i < d.GetNumberOfFiles(); ++i)
1751 const char* fname = d.GetFile(i);
1752 if(strcmp(fname, ".") == 0 ||
1753 strcmp(fname, "..") == 0)
1755 continue;
1757 for(std::vector<std::string>::const_iterator ni = this->Names.begin();
1758 ni != this->Names.end(); ++ni)
1760 if(cmsysString_strncasecmp(fname, ni->c_str(),
1761 ni->length()) == 0)
1763 matches.push_back(fname);
1768 for(std::vector<std::string>::const_iterator i = matches.begin();
1769 i != matches.end(); ++i)
1771 if(this->Consider(parent + *i, lister))
1773 return true;
1776 return false;
1778 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1780 cmsys::auto_ptr<cmFileListGeneratorBase>
1781 g(new cmFileListGeneratorProject(*this));
1782 return g;
1786 class cmFileListGeneratorMacProject: public cmFileListGeneratorBase
1788 public:
1789 cmFileListGeneratorMacProject(std::vector<std::string> const& names,
1790 const char* ext):
1791 cmFileListGeneratorBase(), Names(names), Extension(ext) {}
1792 cmFileListGeneratorMacProject(cmFileListGeneratorMacProject const& r):
1793 cmFileListGeneratorBase(), Names(r.Names), Extension(r.Extension) {}
1794 private:
1795 std::vector<std::string> const& Names;
1796 std::string Extension;
1797 virtual bool Search(std::string const& parent, cmFileList& lister)
1799 // Construct a list of matches.
1800 std::vector<std::string> matches;
1801 cmsys::Directory d;
1802 d.Load(parent.c_str());
1803 for(unsigned long i=0; i < d.GetNumberOfFiles(); ++i)
1805 const char* fname = d.GetFile(i);
1806 if(strcmp(fname, ".") == 0 ||
1807 strcmp(fname, "..") == 0)
1809 continue;
1811 for(std::vector<std::string>::const_iterator ni = this->Names.begin();
1812 ni != this->Names.end(); ++ni)
1814 std::string name = *ni;
1815 name += this->Extension;
1816 if(cmsysString_strcasecmp(fname, name.c_str()) == 0)
1818 matches.push_back(fname);
1823 for(std::vector<std::string>::const_iterator i = matches.begin();
1824 i != matches.end(); ++i)
1826 if(this->Consider(parent + *i, lister))
1828 return true;
1831 return false;
1833 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1835 cmsys::auto_ptr<cmFileListGeneratorBase>
1836 g(new cmFileListGeneratorMacProject(*this));
1837 return g;
1841 class cmFileListGeneratorCaseInsensitive: public cmFileListGeneratorBase
1843 public:
1844 cmFileListGeneratorCaseInsensitive(std::string const& str):
1845 cmFileListGeneratorBase(), String(str) {}
1846 cmFileListGeneratorCaseInsensitive(
1847 cmFileListGeneratorCaseInsensitive const& r):
1848 cmFileListGeneratorBase(), String(r.String) {}
1849 private:
1850 std::string String;
1851 virtual bool Search(std::string const& parent, cmFileList& lister)
1853 // Look for matching files.
1854 std::vector<std::string> matches;
1855 cmsys::Directory d;
1856 d.Load(parent.c_str());
1857 for(unsigned long i=0; i < d.GetNumberOfFiles(); ++i)
1859 const char* fname = d.GetFile(i);
1860 if(strcmp(fname, ".") == 0 ||
1861 strcmp(fname, "..") == 0)
1863 continue;
1865 if(cmsysString_strcasecmp(fname, this->String.c_str()) == 0)
1867 if(this->Consider(parent + fname, lister))
1869 return true;
1873 return false;
1875 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1877 cmsys::auto_ptr<cmFileListGeneratorBase>
1878 g(new cmFileListGeneratorCaseInsensitive(*this));
1879 return g;
1883 class cmFileListGeneratorGlob: public cmFileListGeneratorBase
1885 public:
1886 cmFileListGeneratorGlob(std::string const& str):
1887 cmFileListGeneratorBase(), Pattern(str) {}
1888 cmFileListGeneratorGlob(cmFileListGeneratorGlob const& r):
1889 cmFileListGeneratorBase(), Pattern(r.Pattern) {}
1890 private:
1891 std::string Pattern;
1892 virtual bool Search(std::string const& parent, cmFileList& lister)
1894 // Glob the set of matching files.
1895 std::string expr = parent;
1896 expr += this->Pattern;
1897 cmsys::Glob g;
1898 if(!g.FindFiles(expr))
1900 return false;
1902 std::vector<std::string> const& files = g.GetFiles();
1904 // Look for directories among the matches.
1905 for(std::vector<std::string>::const_iterator fi = files.begin();
1906 fi != files.end(); ++fi)
1908 if(cmSystemTools::FileIsDirectory(fi->c_str()))
1910 if(this->Consider(*fi, lister))
1912 return true;
1916 return false;
1918 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1920 cmsys::auto_ptr<cmFileListGeneratorBase>
1921 g(new cmFileListGeneratorGlob(*this));
1922 return g;
1926 //----------------------------------------------------------------------------
1927 bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
1929 assert(!prefix_in.empty() && prefix_in[prefix_in.size()-1] == '/');
1930 if(this->DebugMode)
1932 fprintf(stderr, "Checking prefix [%s]\n", prefix_in.c_str());
1935 // Skip this if the prefix does not exist.
1936 if(!cmSystemTools::FileIsDirectory(prefix_in.c_str()))
1938 return false;
1941 // PREFIX/ (useful on windows or in build trees)
1942 if(this->SearchDirectory(prefix_in))
1944 return true;
1947 // Strip the trailing slash because the path generator is about to
1948 // add one.
1949 std::string prefix = prefix_in.substr(0, prefix_in.size()-1);
1951 // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
1953 cmFindPackageFileList lister(this);
1954 lister
1955 / cmFileListGeneratorFixed(prefix)
1956 / cmFileListGeneratorCaseInsensitive("cmake");
1957 if(lister.Search())
1959 return true;
1963 // PREFIX/(Foo|foo|FOO).*/
1965 cmFindPackageFileList lister(this);
1966 lister
1967 / cmFileListGeneratorFixed(prefix)
1968 / cmFileListGeneratorProject(this->Names);
1969 if(lister.Search())
1971 return true;
1975 // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
1977 cmFindPackageFileList lister(this);
1978 lister
1979 / cmFileListGeneratorFixed(prefix)
1980 / cmFileListGeneratorProject(this->Names)
1981 / cmFileListGeneratorCaseInsensitive("cmake");
1982 if(lister.Search())
1984 return true;
1988 // Construct list of common install locations (lib and share).
1989 std::vector<std::string> common;
1990 if(this->UseLib64Paths)
1992 common.push_back("lib64");
1994 common.push_back("lib");
1995 common.push_back("share");
1997 // PREFIX/(share|lib)/cmake/(Foo|foo|FOO).*/
1999 cmFindPackageFileList lister(this);
2000 lister
2001 / cmFileListGeneratorFixed(prefix)
2002 / cmFileListGeneratorEnumerate(common)
2003 / cmFileListGeneratorFixed("cmake")
2004 / cmFileListGeneratorProject(this->Names);
2005 if(lister.Search())
2007 return true;
2011 // PREFIX/(share|lib)/(Foo|foo|FOO).*/
2013 cmFindPackageFileList lister(this);
2014 lister
2015 / cmFileListGeneratorFixed(prefix)
2016 / cmFileListGeneratorEnumerate(common)
2017 / cmFileListGeneratorProject(this->Names);
2018 if(lister.Search())
2020 return true;
2024 // PREFIX/(share|lib)/(Foo|foo|FOO).*/(cmake|CMake)/
2026 cmFindPackageFileList lister(this);
2027 lister
2028 / cmFileListGeneratorFixed(prefix)
2029 / cmFileListGeneratorEnumerate(common)
2030 / cmFileListGeneratorProject(this->Names)
2031 / cmFileListGeneratorCaseInsensitive("cmake");
2032 if(lister.Search())
2034 return true;
2038 return false;
2041 //----------------------------------------------------------------------------
2042 bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
2044 assert(!prefix_in.empty() && prefix_in[prefix_in.size()-1] == '/');
2045 if(this->DebugMode)
2047 fprintf(stderr, "Checking framework prefix [%s]\n", prefix_in.c_str());
2050 // Strip the trailing slash because the path generator is about to
2051 // add one.
2052 std::string prefix = prefix_in.substr(0, prefix_in.size()-1);
2054 // <prefix>/Foo.framework/Resources/
2056 cmFindPackageFileList lister(this);
2057 lister
2058 / cmFileListGeneratorFixed(prefix)
2059 / cmFileListGeneratorMacProject(this->Names, ".framework")
2060 / cmFileListGeneratorFixed("Resources");
2061 if(lister.Search())
2063 return true;
2066 // <prefix>/Foo.framework/Resources/CMake/
2068 cmFindPackageFileList lister(this);
2069 lister
2070 / cmFileListGeneratorFixed(prefix)
2071 / cmFileListGeneratorMacProject(this->Names, ".framework")
2072 / cmFileListGeneratorFixed("Resources")
2073 / cmFileListGeneratorCaseInsensitive("cmake");
2074 if(lister.Search())
2076 return true;
2080 // <prefix>/Foo.framework/Versions/*/Resources/
2082 cmFindPackageFileList lister(this);
2083 lister
2084 / cmFileListGeneratorFixed(prefix)
2085 / cmFileListGeneratorMacProject(this->Names, ".framework")
2086 / cmFileListGeneratorFixed("Versions")
2087 / cmFileListGeneratorGlob("*/Resources");
2088 if(lister.Search())
2090 return true;
2094 // <prefix>/Foo.framework/Versions/*/Resources/CMake/
2096 cmFindPackageFileList lister(this);
2097 lister
2098 / cmFileListGeneratorFixed(prefix)
2099 / cmFileListGeneratorMacProject(this->Names, ".framework")
2100 / cmFileListGeneratorFixed("Versions")
2101 / cmFileListGeneratorGlob("*/Resources")
2102 / cmFileListGeneratorCaseInsensitive("cmake");
2103 if(lister.Search())
2105 return true;
2109 return false;
2112 //----------------------------------------------------------------------------
2113 bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
2115 assert(!prefix_in.empty() && prefix_in[prefix_in.size()-1] == '/');
2116 if(this->DebugMode)
2118 fprintf(stderr, "Checking bundle prefix [%s]\n", prefix_in.c_str());
2121 // Strip the trailing slash because the path generator is about to
2122 // add one.
2123 std::string prefix = prefix_in.substr(0, prefix_in.size()-1);
2125 // <prefix>/Foo.app/Contents/Resources
2127 cmFindPackageFileList lister(this);
2128 lister
2129 / cmFileListGeneratorFixed(prefix)
2130 / cmFileListGeneratorMacProject(this->Names, ".app")
2131 / cmFileListGeneratorFixed("Contents/Resources");
2132 if(lister.Search())
2134 return true;
2138 // <prefix>/Foo.app/Contents/Resources/CMake
2140 cmFindPackageFileList lister(this);
2141 lister
2142 / cmFileListGeneratorFixed(prefix)
2143 / cmFileListGeneratorMacProject(this->Names, ".app")
2144 / cmFileListGeneratorFixed("Contents/Resources")
2145 / cmFileListGeneratorCaseInsensitive("cmake");
2146 if(lister.Search())
2148 return true;
2152 return false;
2155 // TODO: Debug cmsys::Glob double slash problem.
2157 // TODO: Add registry entries after cmake system search path?
2158 // Currently the user must specify them with the PATHS option.
2160 // [HKEY_CURRENT_USER\Software\*\Foo*;InstallDir]
2161 // [HKEY_CURRENT_USER\Software\*\*\Foo*;InstallDir]
2162 // [HKEY_LOCAL_MACHINE\Software\*\Foo*;InstallDir]
2163 // [HKEY_LOCAL_MACHINE\Software\*\*\Foo*;InstallDir]