Resync
[CMakeLuaTailorHgBridge.git] / CMakeLua / Source / cmFindPackageCommand.cxx
blob3756aa0bddf66bebc2bba4299fb4efa7c3aace92
1 /*=========================================================================
3 Program: CMake - Cross-Platform Makefile Generator
4 Module: $RCSfile: cmFindPackageCommand.cxx,v $
5 Language: C++
6 Date: $Date: 2009-01-22 18:18:39 $
7 Version: $Revision: 1.58 $
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"
18 #include <cmsys/RegularExpression.hxx>
20 #ifdef CMAKE_BUILD_WITH_CMAKE
21 #include "cmVariableWatch.h"
22 #endif
24 void cmFindPackageNeedBackwardsCompatibility(const std::string& variable,
25 int access_type, void*, const char* newValue,
26 const cmMakefile*)
28 (void)newValue;
29 #ifdef CMAKE_BUILD_WITH_CMAKE
30 if(access_type == cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS)
32 std::string message = "An attempt was made to access a variable: ";
33 message += variable;
34 message +=
35 " that has not been defined. This variable is created by the "
36 "FIND_PACKAGE command. CMake version 1.6 always converted the "
37 "variable name to upper-case, but this behavior is no longer the "
38 "case. To fix this you might need to set the cache value of "
39 "CMAKE_BACKWARDS_COMPATIBILITY to 1.6 or less. If you are writing a "
40 "CMake listfile, you should change the variable reference to use "
41 "the case of the argument to FIND_PACKAGE.";
42 cmSystemTools::Error(message.c_str());
44 #else
45 (void)variable;
46 (void)access_type;
47 #endif
50 //----------------------------------------------------------------------------
51 cmFindPackageCommand::cmFindPackageCommand()
53 cmSystemTools::ReplaceString(this->GenericDocumentationRootPath,
54 "CMAKE_FIND_ROOT_PATH_MODE_XXX",
55 "CMAKE_FIND_ROOT_PATH_MODE_PACKAGE");
56 cmSystemTools::ReplaceString(this->GenericDocumentationPathsOrder,
57 "FIND_ARGS_XXX", "<package>");
58 cmSystemTools::ReplaceString(this->GenericDocumentationPathsOrder,
59 "FIND_XXX", "find_package");
60 this->CMakePathName = "PACKAGE";
61 this->Quiet = false;
62 this->Required = false;
63 this->NoBuilds = false;
64 this->NoModule = false;
65 this->DebugMode = false;
66 this->UseLib64Paths = false;
67 this->PolicyScope = true;
68 this->VersionMajor = 0;
69 this->VersionMinor = 0;
70 this->VersionPatch = 0;
71 this->VersionTweak = 0;
72 this->VersionCount = 0;
73 this->VersionExact = false;
74 this->VersionFoundMajor = 0;
75 this->VersionFoundMinor = 0;
76 this->VersionFoundPatch = 0;
77 this->VersionFoundTweak = 0;
78 this->VersionFoundCount = 0;
79 this->CommandDocumentation =
80 " find_package(<package> [version] [EXACT] [QUIET]\n"
81 " [[REQUIRED|COMPONENTS] [components...]]\n"
82 " [NO_POLICY_SCOPE])\n"
83 "Finds and loads settings from an external project. "
84 "<package>_FOUND will be set to indicate whether the package was found. "
85 "When the package is found package-specific information is provided "
86 "through variables documented by the package itself. "
87 "The QUIET option disables messages if the package cannot be found. "
88 "The REQUIRED option stops processing with an error message if the "
89 "package cannot be found. "
90 "A package-specific list of components may be listed after the "
91 "REQUIRED option or after the COMPONENTS option if no REQUIRED "
92 "option is given. "
93 "The [version] argument requests a version with which the package found "
94 "should be compatible (format is major[.minor[.patch[.tweak]]]). "
95 "The EXACT option requests that the version be matched exactly. "
96 "If no [version] is given to a recursive invocation inside a "
97 "find-module, the [version] and EXACT arguments are forwarded "
98 "automatically from the outer call. "
99 "Version support is currently provided only on a package-by-package "
100 "basis (details below).\n"
101 "User code should generally look for packages using the above simple "
102 "signature. The remainder of this command documentation specifies the "
103 "full command signature and details of the search process. Project "
104 "maintainers wishing to provide a package to be found by this command "
105 "are encouraged to read on.\n"
106 "The command has two modes by which it searches for packages: "
107 "\"Module\" mode and \"Config\" mode. "
108 "Module mode is available when the command is invoked with the above "
109 "reduced signature. "
110 "CMake searches for a file called \"Find<package>.cmake\" in "
111 "the CMAKE_MODULE_PATH followed by the CMake installation. "
112 "If the file is found, it is read and processed by CMake. "
113 "It is responsible for finding the package, checking the version, "
114 "and producing any needed messages. "
115 "Many find-modules provide limited or no support for versioning; "
116 "check the module documentation. "
117 "If no module is found the command proceeds to Config mode.\n"
118 "The complete Config mode command signature is:\n"
119 " find_package(<package> [version] [EXACT] [QUIET]\n"
120 " [[REQUIRED|COMPONENTS] [components...]] [NO_MODULE]\n"
121 " [NO_POLICY_SCOPE]\n"
122 " [NAMES name1 [name2 ...]]\n"
123 " [CONFIGS config1 [config2 ...]]\n"
124 " [HINTS path1 [path2 ... ]]\n"
125 " [PATHS path1 [path2 ... ]]\n"
126 " [PATH_SUFFIXES suffix1 [suffix2 ...]]\n"
127 " [NO_DEFAULT_PATH]\n"
128 " [NO_CMAKE_ENVIRONMENT_PATH]\n"
129 " [NO_CMAKE_PATH]\n"
130 " [NO_SYSTEM_ENVIRONMENT_PATH]\n"
131 " [NO_CMAKE_BUILDS_PATH]\n"
132 " [NO_CMAKE_SYSTEM_PATH]\n"
133 " [CMAKE_FIND_ROOT_PATH_BOTH |\n"
134 " ONLY_CMAKE_FIND_ROOT_PATH |\n"
135 " NO_CMAKE_FIND_ROOT_PATH])\n"
136 "The NO_MODULE option may be used to skip Module mode explicitly. "
137 "It is also implied by use of options not specified in the reduced "
138 "signature. "
139 "\n"
140 "Config mode attempts to locate a configuration file provided by the "
141 "package to be found. A cache entry called <package>_DIR is created to "
142 "hold the directory containing the file. "
143 "By default the command searches for a package with the name <package>. "
144 "If the NAMES option is given the names following it are used instead "
145 "of <package>. "
146 "The command searches for a file called \"<name>Config.cmake\" or "
147 "\"<lower-case-name>-config.cmake\" for each name specified. "
148 "A replacement set of possible configuration file names may be given "
149 "using the CONFIGS option. "
150 "The search procedure is specified below. Once found, the configuration "
151 "file is read and processed by CMake. Since the file is provided by the "
152 "package it already knows the location of package contents. "
153 "The full path to the configuration file is stored in the cmake "
154 "variable <package>_CONFIG."
155 "\n"
156 "If the package configuration file cannot be found CMake "
157 "will generate an error describing the problem unless the QUIET "
158 "argument is specified. If REQUIRED is specified and the package "
159 "is not found a fatal error is generated and the configure step stops "
160 "executing. If <package>_DIR has been set to a directory not containing "
161 "a configuration file CMake will ignore it and search from scratch."
162 "\n"
163 "When the [version] argument is given Config mode will only find a "
164 "version of the package that claims compatibility with the requested "
165 "version (format is major[.minor[.patch[.tweak]]]). "
166 "If the EXACT option is given only a version of the package claiming "
167 "an exact match of the requested version may be found. "
168 "CMake does not establish any convention for the meaning of version "
169 "numbers. "
170 "Package version numbers are checked by \"version\" files provided by "
171 "the packages themselves. "
172 "For a candidate package confguration file \"<config-file>.cmake\" the "
173 "corresponding version file is located next to it and named either "
174 "\"<config-file>-version.cmake\" or \"<config-file>Version.cmake\". "
175 "If no such version file is available then the configuration file "
176 "is assumed to not be compatible with any requested version. "
177 "When a version file is found it is loaded to check the requested "
178 "version number. "
179 "The version file is loaded in a nested scope in which the following "
180 "variables have been defined:\n"
181 " PACKAGE_FIND_NAME = the <package> name\n"
182 " PACKAGE_FIND_VERSION = full requested version string\n"
183 " PACKAGE_FIND_VERSION_MAJOR = major version if requested, else 0\n"
184 " PACKAGE_FIND_VERSION_MINOR = minor version if requested, else 0\n"
185 " PACKAGE_FIND_VERSION_PATCH = patch version if requested, else 0\n"
186 " PACKAGE_FIND_VERSION_TWEAK = tweak version if requested, else 0\n"
187 " PACKAGE_FIND_VERSION_COUNT = number of version components, 0 to 4\n"
188 "The version file checks whether it satisfies the requested version "
189 "and sets these variables:\n"
190 " PACKAGE_VERSION = full provided version string\n"
191 " PACKAGE_VERSION_EXACT = true if version is exact match\n"
192 " PACKAGE_VERSION_COMPATIBLE = true if version is compatible\n"
193 " PACKAGE_VERSION_UNSUITABLE = true if unsuitable as any version\n"
194 "These variables are checked by the find_package command to determine "
195 "whether the configuration file provides an acceptable version. "
196 "They are not available after the find_package call returns. "
197 "If the version is acceptable the following variables are set:\n"
198 " <package>_VERSION = full provided version string\n"
199 " <package>_VERSION_MAJOR = major version if provided, else 0\n"
200 " <package>_VERSION_MINOR = minor version if provided, else 0\n"
201 " <package>_VERSION_PATCH = patch version if provided, else 0\n"
202 " <package>_VERSION_TWEAK = tweak version if provided, else 0\n"
203 " <package>_VERSION_COUNT = number of version components, 0 to 4\n"
204 "and the corresponding package configuration file is loaded. "
205 "When multiple package configuration files are available whose version "
206 "files claim compatibility with the version requested it is unspecified "
207 "which one is chosen. "
208 "No attempt is made to choose a highest or closest version number."
209 "\n"
210 "Config mode provides an elaborate interface and search procedure. "
211 "Much of the interface is provided for completeness and for use "
212 "internally by find-modules loaded by Module mode. "
213 "Most user code should simply call\n"
214 " find_package(<package> [major[.minor]] [EXACT] [REQUIRED|QUIET])\n"
215 "in order to find a package. Package maintainers providing CMake "
216 "package configuration files are encouraged to name and install "
217 "them such that the procedure outlined below will find them "
218 "without requiring use of additional options."
219 "\n"
220 "CMake constructs a set of possible installation prefixes for the "
221 "package. Under each prefix several directories are searched for a "
222 "configuration file. The tables below show the directories searched. "
223 "Each entry is meant for installation trees following Windows (W), "
224 "UNIX (U), or Apple (A) conventions.\n"
225 " <prefix>/ (W)\n"
226 " <prefix>/(cmake|CMake)/ (W)\n"
227 " <prefix>/<name>*/ (W)\n"
228 " <prefix>/<name>*/(cmake|CMake)/ (W)\n"
229 " <prefix>/(share|lib)/cmake/<name>*/ (U)\n"
230 " <prefix>/(share|lib)/<name>*/ (U)\n"
231 " <prefix>/(share|lib)/<name>*/(cmake|CMake)/ (U)\n"
232 "On systems supporting OS X Frameworks and Application Bundles "
233 "the following directories are searched for frameworks or bundles "
234 "containing a configuration file:\n"
235 " <prefix>/<name>.framework/Resources/ (A)\n"
236 " <prefix>/<name>.framework/Resources/CMake/ (A)\n"
237 " <prefix>/<name>.framework/Versions/*/Resources/ (A)\n"
238 " <prefix>/<name>.framework/Versions/*/Resources/CMake/ (A)\n"
239 " <prefix>/<name>.app/Contents/Resources/ (A)\n"
240 " <prefix>/<name>.app/Contents/Resources/CMake/ (A)\n"
241 "In all cases the <name> is treated as case-insensitive and corresponds "
242 "to any of the names specified (<package> or names given by NAMES). "
243 "If PATH_SUFFIXES is specified the suffixes are appended to each "
244 "(W) or (U) directory entry one-by-one.\n"
245 "This set of directories is intended to work in cooperation with "
246 "projects that provide configuration files in their installation trees. "
247 "Directories above marked with (W) are intended for installations on "
248 "Windows where the prefix may point at the top of an application's "
249 "installation directory. Those marked with (U) are intended for "
250 "installations on UNIX platforms where the prefix is shared by "
251 "multiple packages. This is merely a convention, so all (W) and (U) "
252 "directories are still searched on all platforms. "
253 "Directories marked with (A) are intended for installations on "
254 "Apple platforms. The cmake variables CMAKE_FIND_FRAMEWORK and "
255 "CMAKE_FIND_APPBUNDLE determine the order of preference "
256 "as specified below.\n"
257 "The set of installation prefixes is constructed using the following "
258 "steps. If NO_DEFAULT_PATH is specified all NO_* options are enabled.\n"
259 "1. Search paths specified in cmake-specific cache variables. "
260 "These are intended to be used on the command line with a -DVAR=value. "
261 "This can be skipped if NO_CMAKE_PATH is passed.\n"
262 " CMAKE_PREFIX_PATH\n"
263 " CMAKE_FRAMEWORK_PATH\n"
264 " CMAKE_APPBUNDLE_PATH\n"
265 "2. Search paths specified in cmake-specific environment variables. "
266 "These are intended to be set in the user's shell configuration. "
267 "This can be skipped if NO_CMAKE_ENVIRONMENT_PATH is passed.\n"
268 " CMAKE_PREFIX_PATH\n"
269 " CMAKE_FRAMEWORK_PATH\n"
270 " CMAKE_APPBUNDLE_PATH\n"
271 "3. Search paths specified by the HINTS option. "
272 "These should be paths computed by system introspection, such as a "
273 "hint provided by the location of another item already found. "
274 "Hard-coded guesses should be specified with the PATHS option.\n"
275 "4. Search the standard system environment variables. "
276 "This can be skipped if NO_SYSTEM_ENVIRONMENT_PATH is passed. "
277 "Path entries ending in \"/bin\" or \"/sbin\" are automatically "
278 "converted to their parent directories.\n"
279 " PATH\n"
280 "5. Search project build trees recently configured in a CMake GUI. "
281 "This can be skipped if NO_CMAKE_BUILDS_PATH is passed. "
282 "It is intended for the case when a user is building multiple "
283 "dependent projects one after another.\n"
284 "6. Search cmake variables defined in the Platform files "
285 "for the current system. This can be skipped if NO_CMAKE_SYSTEM_PATH "
286 "is passed.\n"
287 " CMAKE_SYSTEM_PREFIX_PATH\n"
288 " CMAKE_SYSTEM_FRAMEWORK_PATH\n"
289 " CMAKE_SYSTEM_APPBUNDLE_PATH\n"
290 "7. Search paths specified by the PATHS option. "
291 "These are typically hard-coded guesses.\n"
293 this->CommandDocumentation += this->GenericDocumentationMacPolicy;
294 this->CommandDocumentation += this->GenericDocumentationRootPath;
295 this->CommandDocumentation += this->GenericDocumentationPathsOrder;
296 this->CommandDocumentation +=
297 "\n"
298 "See the cmake_policy() command documentation for discussion of the "
299 "NO_POLICY_SCOPE option."
303 //----------------------------------------------------------------------------
304 const char* cmFindPackageCommand::GetFullDocumentation()
306 return this->CommandDocumentation.c_str();
309 //----------------------------------------------------------------------------
310 bool cmFindPackageCommand
311 ::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
313 if(args.size() < 1)
315 this->SetError("called with incorrect number of arguments");
316 return false;
319 // Check for debug mode.
320 this->DebugMode = this->Makefile->IsOn("CMAKE_FIND_DEBUG_MODE");
322 // Lookup whether lib64 paths should be used.
323 if(const char* sizeof_dptr =
324 this->Makefile->GetDefinition("CMAKE_SIZEOF_VOID_P"))
326 if(atoi(sizeof_dptr) == 8 &&
327 this->Makefile->GetCMakeInstance()
328 ->GetPropertyAsBool("FIND_LIBRARY_USE_LIB64_PATHS"))
330 this->UseLib64Paths = true;
334 // Find the current root path mode.
335 this->SelectDefaultRootPathMode();
337 // Find the current bundle/framework search policy.
338 this->SelectDefaultMacMode();
340 // Record options.
341 this->Name = args[0];
342 std::string components;
343 const char* components_sep = "";
345 // Check ancient compatibility.
346 this->Compatibility_1_6 =
347 this->Makefile->GetLocalGenerator()
348 ->NeedBackwardsCompatibility(1, 6);
350 // Always search directly in a generated path.
351 this->SearchPathSuffixes.push_back("");
353 // Parse the arguments.
354 enum Doing { DoingNone, DoingComponents, DoingNames, DoingPaths,
355 DoingPathSuffixes, DoingConfigs, DoingHints };
356 Doing doing = DoingNone;
357 cmsys::RegularExpression version("^[0-9.]+$");
358 bool haveVersion = false;
359 for(unsigned int i=1; i < args.size(); ++i)
361 if(args[i] == "QUIET")
363 this->Quiet = true;
364 doing = DoingNone;
366 else if(args[i] == "EXACT")
368 this->VersionExact = true;
369 this->Compatibility_1_6 = false;
370 doing = DoingNone;
372 else if(args[i] == "NO_MODULE")
374 this->NoModule = true;
375 doing = DoingNone;
377 else if(args[i] == "REQUIRED")
379 this->Required = true;
380 doing = DoingComponents;
382 else if(args[i] == "COMPONENTS")
384 this->Compatibility_1_6 = false;
385 doing = DoingComponents;
387 else if(args[i] == "NAMES")
389 this->NoModule = true;
390 this->Compatibility_1_6 = false;
391 doing = DoingNames;
393 else if(args[i] == "PATHS")
395 this->NoModule = true;
396 this->Compatibility_1_6 = false;
397 doing = DoingPaths;
399 else if(args[i] == "HINTS")
401 this->NoModule = true;
402 this->Compatibility_1_6 = false;
403 doing = DoingHints;
405 else if(args[i] == "PATH_SUFFIXES")
407 this->NoModule = true;
408 this->Compatibility_1_6 = false;
409 doing = DoingPathSuffixes;
411 else if(args[i] == "CONFIGS")
413 this->NoModule = true;
414 this->Compatibility_1_6 = false;
415 doing = DoingConfigs;
417 else if(args[i] == "NO_POLICY_SCOPE")
419 this->PolicyScope = false;
420 this->Compatibility_1_6 = false;
421 doing = DoingNone;
423 else if(args[i] == "NO_CMAKE_BUILDS_PATH")
425 this->NoBuilds = true;
426 this->NoModule = true;
427 this->Compatibility_1_6 = false;
428 doing = DoingNone;
430 else if(this->CheckCommonArgument(args[i]))
432 this->NoModule = true;
433 this->Compatibility_1_6 = false;
434 doing = DoingNone;
436 else if(doing == DoingComponents)
438 // Set a variable telling the find script this component
439 // is required.
440 std::string req_var = this->Name + "_FIND_REQUIRED_" + args[i];
441 this->AddFindDefinition(req_var.c_str(), "1");
443 // Append to the list of required components.
444 components += components_sep;
445 components += args[i];
446 components_sep = ";";
448 else if(doing == DoingNames)
450 this->Names.push_back(args[i]);
452 else if(doing == DoingPaths)
454 this->AddUserPath(args[i], this->UserPaths);
456 else if(doing == DoingHints)
458 this->AddUserPath(args[i], this->UserHints);
460 else if(doing == DoingPathSuffixes)
462 this->AddPathSuffix(args[i]);
464 else if(doing == DoingConfigs)
466 if(args[i].find_first_of(":/\\") != args[i].npos ||
467 cmSystemTools::GetFilenameLastExtension(args[i]) != ".cmake")
469 cmOStringStream e;
470 e << "given CONFIGS option followed by invalid file name \""
471 << args[i] << "\". The names given must be file names without "
472 << "a path and with a \".cmake\" extension.";
473 return false;
475 this->Configs.push_back(args[i]);
477 else if(!haveVersion && version.find(args[i].c_str()))
479 haveVersion = true;
480 this->Version = args[i];
482 else
484 cmOStringStream e;
485 e << "called with invalid argument \"" << args[i].c_str() << "\"";
486 this->SetError(e.str().c_str());
487 return false;
491 // Ignore EXACT with no version.
492 if(this->Version.empty() && this->VersionExact)
494 this->VersionExact = false;
495 this->Makefile->IssueMessage(
496 cmake::AUTHOR_WARNING, "Ignoring EXACT since no version is requested.");
499 if(this->Version.empty())
501 // Check whether we are recursing inside "Find<name>.cmake" within
502 // another find_package(<name>) call.
503 std::string mod = this->Name;
504 mod += "_FIND_MODULE";
505 if(this->Makefile->IsOn(mod.c_str()))
507 // Get version information from the outer call if necessary.
508 // Requested version string.
509 std::string ver = this->Name;
510 ver += "_FIND_VERSION";
511 this->Version = this->Makefile->GetSafeDefinition(ver.c_str());
513 // Whether an exact version is required.
514 std::string exact = this->Name;
515 exact += "_FIND_VERSION_EXACT";
516 this->VersionExact = this->Makefile->IsOn(exact.c_str());
520 if(!this->Version.empty())
522 // Try to parse the version number and store the results that were
523 // successfully parsed.
524 unsigned int parsed_major;
525 unsigned int parsed_minor;
526 unsigned int parsed_patch;
527 unsigned int parsed_tweak;
528 this->VersionCount = sscanf(this->Version.c_str(), "%u.%u.%u.%u",
529 &parsed_major, &parsed_minor,
530 &parsed_patch, &parsed_tweak);
531 switch(this->VersionCount)
533 case 4: this->VersionTweak = parsed_tweak; // no break!
534 case 3: this->VersionPatch = parsed_patch; // no break!
535 case 2: this->VersionMinor = parsed_minor; // no break!
536 case 1: this->VersionMajor = parsed_major; // no break!
537 default: break;
541 this->SetModuleVariables(components);
543 // See if there is a Find<package>.cmake module.
544 if(!this->NoModule)
546 bool foundModule = false;
547 if(!this->FindModule(foundModule))
549 this->AppendSuccessInformation();
550 return false;
552 if(foundModule)
554 this->AppendSuccessInformation();
555 return true;
559 // No find module. Assume the project has a CMake config file. Use
560 // a <package>_DIR cache variable to locate it.
561 this->Variable = this->Name;
562 this->Variable += "_DIR";
564 // Add the default name.
565 if(this->Names.empty())
567 this->Names.push_back(this->Name);
570 // Add the default configs.
571 if(this->Configs.empty())
573 for(std::vector<std::string>::const_iterator ni = this->Names.begin();
574 ni != this->Names.end(); ++ni)
576 std::string config = *ni;
577 config += "Config.cmake";
578 this->Configs.push_back(config);
580 config = cmSystemTools::LowerCase(*ni);
581 config += "-config.cmake";
582 this->Configs.push_back(config);
586 // Find and load the package.
587 bool result = this->HandlePackageMode();
588 this->AppendSuccessInformation();
589 return result;
593 //----------------------------------------------------------------------------
594 void cmFindPackageCommand::SetModuleVariables(const std::string& components)
596 // Store the list of components.
597 std::string components_var = this->Name + "_FIND_COMPONENTS";
598 this->AddFindDefinition(components_var.c_str(), components.c_str());
600 if(this->Quiet)
602 // Tell the module that is about to be read that it should find
603 // quietly.
604 std::string quietly = this->Name;
605 quietly += "_FIND_QUIETLY";
606 this->AddFindDefinition(quietly.c_str(), "1");
609 if(this->Required)
611 // Tell the module that is about to be read that it should report
612 // a fatal error if the package is not found.
613 std::string req = this->Name;
614 req += "_FIND_REQUIRED";
615 this->AddFindDefinition(req.c_str(), "1");
618 if(!this->Version.empty())
620 // Tell the module that is about to be read what version of the
621 // package has been requested.
622 std::string ver = this->Name;
623 ver += "_FIND_VERSION";
624 this->AddFindDefinition(ver.c_str(), this->Version.c_str());
625 char buf[64];
626 sprintf(buf, "%u", this->VersionMajor);
627 this->AddFindDefinition((ver+"_MAJOR").c_str(), buf);
628 sprintf(buf, "%u", this->VersionMinor);
629 this->AddFindDefinition((ver+"_MINOR").c_str(), buf);
630 sprintf(buf, "%u", this->VersionPatch);
631 this->AddFindDefinition((ver+"_PATCH").c_str(), buf);
632 sprintf(buf, "%u", this->VersionTweak);
633 this->AddFindDefinition((ver+"_TWEAK").c_str(), buf);
634 sprintf(buf, "%u", this->VersionCount);
635 this->AddFindDefinition((ver+"_COUNT").c_str(), buf);
637 // Tell the module whether an exact version has been requested.
638 std::string exact = this->Name;
639 exact += "_FIND_VERSION_EXACT";
640 this->AddFindDefinition(exact.c_str(), this->VersionExact? "1":"0");
644 //----------------------------------------------------------------------------
645 void cmFindPackageCommand::AddFindDefinition(const char* var, const char* val)
647 if(const char* old = this->Makefile->GetDefinition(var))
649 this->OriginalDefs[var].exists = true;
650 this->OriginalDefs[var].value = old;
652 else
654 this->OriginalDefs[var].exists = false;
656 this->Makefile->AddDefinition(var, val);
659 //----------------------------------------------------------------------------
660 void cmFindPackageCommand::RestoreFindDefinitions()
662 for(std::map<cmStdString, OriginalDef>::iterator
663 i = this->OriginalDefs.begin(); i != this->OriginalDefs.end(); ++i)
665 OriginalDef const& od = i->second;
666 if(od.exists)
668 this->Makefile->AddDefinition(i->first.c_str(), od.value.c_str());
670 else
672 this->Makefile->RemoveDefinition(i->first.c_str());
677 //----------------------------------------------------------------------------
678 bool cmFindPackageCommand::FindModule(bool& found)
680 std::string module = "Find";
681 module += this->Name;
682 module += ".cmake";
683 std::string mfile = this->Makefile->GetModulesFile(module.c_str());
684 if ( mfile.size() )
686 // Load the module we found, and set "<name>_FIND_MODULE" to true
687 // while inside it.
688 found = true;
689 std::string var = this->Name;
690 var += "_FIND_MODULE";
691 this->Makefile->AddDefinition(var.c_str(), "1");
692 bool result = this->ReadListFile(mfile.c_str(), DoPolicyScope);
693 this->Makefile->RemoveDefinition(var.c_str());
694 return result;
696 return true;
699 //----------------------------------------------------------------------------
700 bool cmFindPackageCommand::HandlePackageMode()
702 // Support old capitalization behavior.
703 std::string upperDir = cmSystemTools::UpperCase(this->Name);
704 std::string upperFound = cmSystemTools::UpperCase(this->Name);
705 upperDir += "_DIR";
706 upperFound += "_FOUND";
707 if(upperDir == this->Variable)
709 this->Compatibility_1_6 = false;
712 // Try to find the config file.
713 const char* def = this->Makefile->GetDefinition(this->Variable.c_str());
714 if(this->Compatibility_1_6 && cmSystemTools::IsOff(def))
716 // Use the setting of the old name of the variable to provide the
717 // value of the new.
718 const char* oldDef = this->Makefile->GetDefinition(upperDir.c_str());
719 if(!cmSystemTools::IsOff(oldDef))
721 this->Makefile->AddDefinition(this->Variable.c_str(), oldDef);
722 def = this->Makefile->GetDefinition(this->Variable.c_str());
726 // Try to load the config file if the directory is known
727 bool cachedDirectoryOk = false;
728 if(!cmSystemTools::IsOff(def))
730 // Get the directory from the variable value.
731 std::string dir = def;
732 cmSystemTools::ConvertToUnixSlashes(dir);
734 // Treat relative paths with respect to the current source dir.
735 if(!cmSystemTools::FileIsFullPath(dir.c_str()))
737 dir = "/" + dir;
738 dir = this->Makefile->GetCurrentDirectory() + dir;
740 // The file location was cached. Look for the correct file.
741 std::string file;
742 if (this->FindConfigFile(dir, file))
744 this->FileFound = file;
745 cachedDirectoryOk = true;
747 def = this->Makefile->GetDefinition(this->Variable.c_str());
750 // Search for the config file if it is not already found.
751 if(cmSystemTools::IsOff(def) || !cachedDirectoryOk)
753 this->FindConfig();
754 def = this->Makefile->GetDefinition(this->Variable.c_str());
757 // If the directory for the config file was found, try to read the file.
758 bool result = true;
759 bool found = false;
760 // in the following test FileFound should never be empty if def is valid
761 // but I don't want to put an assert() in there now, in case this still
762 // makes it into 2.6.3
763 if(!cmSystemTools::IsOff(def) && (!this->FileFound.empty()))
765 // Set the version variables before loading the config file.
766 // It may override them.
767 this->StoreVersionFound();
769 // Parse the configuration file.
770 if(this->ReadListFile(this->FileFound.c_str(), DoPolicyScope))
772 // The package has been found.
773 found = true;
775 else
777 // The configuration file is invalid.
778 result = false;
781 else if(!this->Quiet || this->Required)
783 // The variable is not set.
784 cmOStringStream e;
785 e << "Could not find ";
786 if(!this->NoModule)
788 e << "module Find" << this->Name << ".cmake or ";
790 e << "a configuration file for package " << this->Name << ".\n";
791 if(!this->NoModule)
793 e << "Adjust CMAKE_MODULE_PATH to find Find"
794 << this->Name << ".cmake or set ";
796 else
798 e << "Set ";
800 e << this->Variable << " to the directory containing a CMake "
801 << "configuration file for " << this->Name << ". ";
802 if(this->Configs.size() == 1)
804 e << "The file will be called " << this->Configs[0];
806 else
808 e << "The file will have one of the following names:\n";
809 for(std::vector<std::string>::const_iterator ci = this->Configs.begin();
810 ci != this->Configs.end(); ++ci)
812 e << " " << *ci << "\n";
815 this->Makefile->IssueMessage(
816 this->Required? cmake::FATAL_ERROR : cmake::WARNING, e.str());
819 // Set a variable marking whether the package was found.
820 std::string foundVar = this->Name;
821 foundVar += "_FOUND";
822 this->Makefile->AddDefinition(foundVar.c_str(), found? "1":"0");
824 // Set a variable naming the configuration file that was found.
825 std::string fileVar = this->Name;
826 fileVar += "_CONFIG";
827 if(found)
829 this->Makefile->AddDefinition(fileVar.c_str(), this->FileFound.c_str());
831 else
833 this->Makefile->RemoveDefinition(fileVar.c_str());
836 // Handle some ancient compatibility stuff.
837 if(this->Compatibility_1_6)
839 // Listfiles will be looking for the capitalized version of the
840 // name. Provide it.
841 this->Makefile->AddDefinition
842 (upperDir.c_str(),
843 this->Makefile->GetDefinition(this->Variable.c_str()));
844 this->Makefile->AddDefinition
845 (upperFound.c_str(),
846 this->Makefile->GetDefinition(foundVar.c_str()));
849 #ifdef CMAKE_BUILD_WITH_CMAKE
850 if(!(upperDir == this->Variable))
852 if(this->Compatibility_1_6)
854 // Listfiles may use the capitalized version of the name.
855 // Remove any previously added watch.
856 this->Makefile->GetVariableWatch()->RemoveWatch(
857 upperDir.c_str(),
858 cmFindPackageNeedBackwardsCompatibility
861 else
863 // Listfiles should not be using the capitalized version of the
864 // name. Add a watch to warn the user.
865 this->Makefile->GetVariableWatch()->AddWatch(
866 upperDir.c_str(),
867 cmFindPackageNeedBackwardsCompatibility
871 #endif
873 return result;
876 //----------------------------------------------------------------------------
877 void cmFindPackageCommand::FindConfig()
879 // Compute the set of search prefixes.
880 this->ComputePrefixes();
882 // Look for the project's configuration file.
883 bool found = false;
885 // Search for frameworks.
886 if(!found && this->SearchFrameworkFirst || this->SearchFrameworkOnly)
888 found = this->FindFrameworkConfig();
891 // Search for apps.
892 if(!found && this->SearchAppBundleFirst || this->SearchAppBundleOnly)
894 found = this->FindAppBundleConfig();
897 // Search prefixes.
898 if(!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly))
900 found = this->FindPrefixedConfig();
903 // Search for frameworks.
904 if(!found && this->SearchFrameworkLast)
906 found = this->FindFrameworkConfig();
909 // Search for apps.
910 if(!found && this->SearchAppBundleLast)
912 found = this->FindAppBundleConfig();
915 // Store the entry in the cache so it can be set by the user.
916 std::string init;
917 if(found)
919 init = cmSystemTools::GetFilenamePath(this->FileFound);
921 else
923 init = this->Variable + "-NOTFOUND";
925 std::string help =
926 "The directory containing a CMake configuration file for ";
927 help += this->Name;
928 help += ".";
929 this->Makefile->AddCacheDefinition(this->Variable.c_str(),
930 init.c_str(), help.c_str(),
931 cmCacheManager::PATH);
934 //----------------------------------------------------------------------------
935 bool cmFindPackageCommand::FindPrefixedConfig()
937 std::vector<std::string>& prefixes = this->SearchPaths;
938 for(std::vector<std::string>::const_iterator pi = prefixes.begin();
939 pi != prefixes.end(); ++pi)
941 if(this->SearchPrefix(*pi))
943 return true;
946 return false;
949 //----------------------------------------------------------------------------
950 bool cmFindPackageCommand::FindFrameworkConfig()
952 std::vector<std::string>& prefixes = this->SearchPaths;
953 for(std::vector<std::string>::const_iterator i = prefixes.begin();
954 i != prefixes.end(); ++i)
956 if(this->SearchFrameworkPrefix(*i))
958 return true;
961 return false;
964 //----------------------------------------------------------------------------
965 bool cmFindPackageCommand::FindAppBundleConfig()
967 std::vector<std::string>& prefixes = this->SearchPaths;
968 for(std::vector<std::string>::const_iterator i = prefixes.begin();
969 i != prefixes.end(); ++i)
971 if(this->SearchAppBundlePrefix(*i))
973 return true;
976 return false;
979 //----------------------------------------------------------------------------
980 bool cmFindPackageCommand::ReadListFile(const char* f, PolicyScopeRule psr)
982 if(this->Makefile->ReadListFile(this->Makefile->GetCurrentListFile(), f, 0,
983 !this->PolicyScope || psr == NoPolicyScope))
985 return true;
987 std::string e = "Error reading CMake code from \"";
988 e += f;
989 e += "\".";
990 this->SetError(e.c_str());
991 return false;
994 //----------------------------------------------------------------------------
995 void cmFindPackageCommand::AppendToProperty(const char* propertyName)
997 std::string propertyValue;
998 const char *prop =
999 this->Makefile->GetCMakeInstance()->GetProperty(propertyName);
1000 if (prop && *prop)
1002 propertyValue = prop;
1004 std::vector<std::string> contents;
1005 cmSystemTools::ExpandListArgument(propertyValue, contents, false);
1007 bool alreadyInserted = false;
1008 for(std::vector<std::string>::const_iterator it = contents.begin();
1009 it != contents.end(); ++ it )
1011 if (*it == this->Name)
1013 alreadyInserted = true;
1014 break;
1017 if (!alreadyInserted)
1019 propertyValue += ";";
1020 propertyValue += this->Name;
1023 else
1025 propertyValue = this->Name;
1027 this->Makefile->GetCMakeInstance()->SetProperty(propertyName,
1028 propertyValue.c_str());
1031 //----------------------------------------------------------------------------
1032 void cmFindPackageCommand::AppendSuccessInformation()
1034 std::string found = this->Name;
1035 found += "_FOUND";
1036 std::string upperFound = cmSystemTools::UpperCase(found);
1038 const char* upperResult = this->Makefile->GetDefinition(upperFound.c_str());
1039 const char* result = this->Makefile->GetDefinition(found.c_str());
1040 if ((cmSystemTools::IsOn(result)) || (cmSystemTools::IsOn(upperResult)))
1042 this->AppendToProperty("PACKAGES_FOUND");
1043 if (!this->Quiet)
1045 this->AppendToProperty("ENABLED_FEATURES");
1048 else
1050 this->AppendToProperty("PACKAGES_NOT_FOUND");
1051 if (!this->Quiet)
1053 this->AppendToProperty("DISABLED_FEATURES");
1057 // Restore original state of "_FIND_" variables we set.
1058 this->RestoreFindDefinitions();
1061 //----------------------------------------------------------------------------
1062 void cmFindPackageCommand::ComputePrefixes()
1064 this->AddPrefixesCMakeVariable();
1065 this->AddPrefixesCMakeEnvironment();
1066 this->AddPrefixesUserHints();
1067 this->AddPrefixesSystemEnvironment();
1068 this->AddPrefixesBuilds();
1069 this->AddPrefixesCMakeSystemVariable();
1070 this->AddPrefixesUserGuess();
1071 this->ComputeFinalPrefixes();
1074 //----------------------------------------------------------------------------
1075 void cmFindPackageCommand::AddPrefixesCMakeEnvironment()
1077 if(!this->NoCMakeEnvironmentPath && !this->NoDefaultPath)
1079 // Check the environment variable with the same name as the cache
1080 // entry.
1081 std::string env;
1082 if(cmSystemTools::GetEnv(this->Variable.c_str(), env) && env.length() > 0)
1084 cmSystemTools::ConvertToUnixSlashes(env);
1085 this->AddPathInternal(env, EnvPath);
1088 this->AddEnvPath("CMAKE_PREFIX_PATH");
1089 this->AddEnvPath("CMAKE_FRAMEWORK_PATH");
1090 this->AddEnvPath("CMAKE_APPBUNDLE_PATH");
1094 //----------------------------------------------------------------------------
1095 void cmFindPackageCommand::AddPrefixesCMakeVariable()
1097 if(!this->NoCMakePath && !this->NoDefaultPath)
1099 this->AddCMakePath("CMAKE_PREFIX_PATH");
1100 this->AddCMakePath("CMAKE_FRAMEWORK_PATH");
1101 this->AddCMakePath("CMAKE_APPBUNDLE_PATH");
1105 //----------------------------------------------------------------------------
1106 void cmFindPackageCommand::AddPrefixesSystemEnvironment()
1108 if(!this->NoSystemEnvironmentPath && !this->NoDefaultPath)
1110 // Use the system search path to generate prefixes.
1111 // Relative paths are interpreted with respect to the current
1112 // working directory.
1113 std::vector<std::string> tmp;
1114 cmSystemTools::GetPath(tmp);
1115 for(std::vector<std::string>::iterator i = tmp.begin();
1116 i != tmp.end(); ++i)
1118 std::string const& d = *i;
1120 // If the path is a PREFIX/bin case then add its parent instead.
1121 if(d.size() >= 4 && strcmp(d.c_str()+d.size()-4, "/bin") == 0 ||
1122 d.size() >= 5 && strcmp(d.c_str()+d.size()-5, "/sbin") == 0)
1124 this->AddPathInternal(cmSystemTools::GetFilenamePath(d), EnvPath);
1126 else
1128 this->AddPathInternal(d, EnvPath);
1134 //----------------------------------------------------------------------------
1135 void cmFindPackageCommand::AddPrefixesBuilds()
1137 if(!this->NoBuilds && !this->NoDefaultPath)
1139 // It is likely that CMake will have recently built the project.
1140 for(int i=1; i <= 10; ++i)
1142 cmOStringStream r;
1143 r <<
1144 "[HKEY_CURRENT_USER\\Software\\Kitware\\CMakeSetup\\"
1145 "Settings\\StartPath;WhereBuild" << i << "]";
1146 std::string f = r.str();
1147 cmSystemTools::ExpandRegistryValues(f);
1148 cmSystemTools::ConvertToUnixSlashes(f);
1149 if(cmSystemTools::FileIsFullPath(f.c_str()) &&
1150 cmSystemTools::FileIsDirectory(f.c_str()))
1152 this->AddPathInternal(f, FullPath);
1158 //----------------------------------------------------------------------------
1159 void cmFindPackageCommand::AddPrefixesCMakeSystemVariable()
1161 if(!this->NoCMakeSystemPath && !this->NoDefaultPath)
1163 this->AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
1164 this->AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
1165 this->AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
1169 //----------------------------------------------------------------------------
1170 void cmFindPackageCommand::AddPrefixesUserGuess()
1172 // Add guesses specified by the caller.
1173 this->AddPathsInternal(this->UserPaths, CMakePath);
1176 //----------------------------------------------------------------------------
1177 void cmFindPackageCommand::AddPrefixesUserHints()
1179 // Add hints specified by the caller.
1180 this->AddPathsInternal(this->UserHints, CMakePath);
1183 //----------------------------------------------------------------------------
1184 void cmFindPackageCommand::ComputeFinalPrefixes()
1186 std::vector<std::string>& prefixes = this->SearchPaths;
1188 // Construct the final set of prefixes.
1189 this->RerootPaths(prefixes);
1191 // Add a trailing slash to all prefixes to aid the search process.
1192 this->AddTrailingSlashes(prefixes);
1195 //----------------------------------------------------------------------------
1196 bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
1198 assert(!dir.empty() && dir[dir.size()-1] == '/');
1200 // Check each path suffix on this directory.
1201 for(std::vector<std::string>::const_iterator
1202 si = this->SearchPathSuffixes.begin();
1203 si != this->SearchPathSuffixes.end(); ++si)
1205 std::string d = dir;
1206 if(!si->empty())
1208 d += *si;
1209 d += "/";
1211 if(this->CheckDirectory(d))
1213 return true;
1216 return false;
1219 //----------------------------------------------------------------------------
1220 bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
1222 assert(!dir.empty() && dir[dir.size()-1] == '/');
1224 // Look for the file in this directory.
1225 std::string d = dir.substr(0, dir.size()-1);
1226 if(this->FindConfigFile(d, this->FileFound))
1228 // Remove duplicate slashes.
1229 cmSystemTools::ConvertToUnixSlashes(this->FileFound);
1230 return true;
1232 return false;
1235 //----------------------------------------------------------------------------
1236 bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
1237 std::string& file)
1239 for(std::vector<std::string>::const_iterator ci = this->Configs.begin();
1240 ci != this->Configs.end(); ++ci)
1242 file = dir;
1243 file += "/";
1244 file += *ci;
1245 if(this->DebugMode)
1247 fprintf(stderr, "Checking file [%s]\n", file.c_str());
1249 if(cmSystemTools::FileExists(file.c_str(), true) &&
1250 this->CheckVersion(file))
1252 return true;
1255 return false;
1258 //----------------------------------------------------------------------------
1259 bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
1261 // Get the filename without the .cmake extension.
1262 std::string::size_type pos = config_file.rfind('.');
1263 std::string version_file_base = config_file.substr(0, pos);
1265 // Look for foo-config-version.cmake
1266 std::string version_file = version_file_base;
1267 version_file += "-version.cmake";
1268 if(cmSystemTools::FileExists(version_file.c_str(), true))
1270 return this->CheckVersionFile(version_file);
1273 // Look for fooConfigVersion.cmake
1274 version_file = version_file_base;
1275 version_file += "Version.cmake";
1276 if(cmSystemTools::FileExists(version_file.c_str(), true))
1278 return this->CheckVersionFile(version_file);
1281 // If no version was requested a versionless package is acceptable.
1282 if(this->Version.empty())
1284 return true;
1287 // No version file found. Assume the version is incompatible.
1288 return false;
1291 //----------------------------------------------------------------------------
1292 bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file)
1294 // The version file will be loaded in an isolated scope.
1295 cmMakefile::ScopePushPop varScope(this->Makefile);
1296 cmMakefile::PolicyPushPop polScope(this->Makefile);
1297 static_cast<void>(varScope);
1298 static_cast<void>(polScope);
1300 // Clear the output variables.
1301 this->Makefile->RemoveDefinition("PACKAGE_VERSION");
1302 this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
1303 this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
1304 this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
1306 // Set the input variables.
1307 this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name.c_str());
1308 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION",
1309 this->Version.c_str());
1310 char buf[64];
1311 sprintf(buf, "%u", this->VersionMajor);
1312 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MAJOR", buf);
1313 sprintf(buf, "%u", this->VersionMinor);
1314 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MINOR", buf);
1315 sprintf(buf, "%u", this->VersionPatch);
1316 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_PATCH", buf);
1317 sprintf(buf, "%u", this->VersionTweak);
1318 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_TWEAK", buf);
1319 sprintf(buf, "%u", this->VersionCount);
1320 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COUNT", buf);
1322 // Load the version check file. Pass NoPolicyScope because we do
1323 // our own policy push/pop independent of CMP0011.
1324 bool suitable = false;
1325 if(this->ReadListFile(version_file.c_str(), NoPolicyScope))
1327 // Check the output variables.
1328 bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
1329 bool unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
1330 if(!okay && !this->VersionExact)
1332 okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
1335 // The package is suitable if the version is okay and not
1336 // explicitly unsuitable.
1337 suitable = !unsuitable && (okay || this->Version.empty());
1338 if(suitable)
1340 // Get the version found.
1341 this->VersionFound =
1342 this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
1344 // Try to parse the version number and store the results that were
1345 // successfully parsed.
1346 unsigned int parsed_major;
1347 unsigned int parsed_minor;
1348 unsigned int parsed_patch;
1349 unsigned int parsed_tweak;
1350 this->VersionFoundCount =
1351 sscanf(this->VersionFound.c_str(), "%u.%u.%u.%u",
1352 &parsed_major, &parsed_minor,
1353 &parsed_patch, &parsed_tweak);
1354 switch(this->VersionFoundCount)
1356 case 4: this->VersionFoundTweak = parsed_tweak; // no break!
1357 case 3: this->VersionFoundPatch = parsed_patch; // no break!
1358 case 2: this->VersionFoundMinor = parsed_minor; // no break!
1359 case 1: this->VersionFoundMajor = parsed_major; // no break!
1360 default: break;
1365 // Succeed if the version is suitable.
1366 return suitable;
1369 //----------------------------------------------------------------------------
1370 void cmFindPackageCommand::StoreVersionFound()
1372 // Store the whole version string.
1373 std::string ver = this->Name;
1374 ver += "_VERSION";
1375 if(this->VersionFound.empty())
1377 this->Makefile->RemoveDefinition(ver.c_str());
1379 else
1381 this->Makefile->AddDefinition(ver.c_str(), this->VersionFound.c_str());
1384 // Store the version components.
1385 char buf[64];
1386 sprintf(buf, "%u", this->VersionFoundMajor);
1387 this->Makefile->AddDefinition((ver+"_MAJOR").c_str(), buf);
1388 sprintf(buf, "%u", this->VersionFoundMinor);
1389 this->Makefile->AddDefinition((ver+"_MINOR").c_str(), buf);
1390 sprintf(buf, "%u", this->VersionFoundPatch);
1391 this->Makefile->AddDefinition((ver+"_PATCH").c_str(), buf);
1392 sprintf(buf, "%u", this->VersionFoundTweak);
1393 this->Makefile->AddDefinition((ver+"_TWEAK").c_str(), buf);
1394 sprintf(buf, "%u", this->VersionFoundCount);
1395 this->Makefile->AddDefinition((ver+"_COUNT").c_str(), buf);
1398 //----------------------------------------------------------------------------
1399 #include <cmsys/Directory.hxx>
1400 #include <cmsys/Glob.hxx>
1401 #include <cmsys/String.h>
1402 #include <cmsys/auto_ptr.hxx>
1404 class cmFileList;
1405 class cmFileListGeneratorBase
1407 public:
1408 virtual ~cmFileListGeneratorBase() {}
1409 protected:
1410 bool Consider(std::string const& fullPath, cmFileList& listing);
1411 private:
1412 bool Search(cmFileList&);
1413 virtual bool Search(std::string const& parent, cmFileList&) = 0;
1414 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const = 0;
1415 friend class cmFileList;
1416 cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next);
1417 cmsys::auto_ptr<cmFileListGeneratorBase> Next;
1420 class cmFileList
1422 public:
1423 cmFileList(): First(), Last(0) {}
1424 virtual ~cmFileList() {}
1425 cmFileList& operator/(cmFileListGeneratorBase const& rhs)
1427 if(this->Last)
1429 this->Last = this->Last->SetNext(rhs);
1431 else
1433 this->First = rhs.Clone();
1434 this->Last = this->First.get();
1436 return *this;
1438 bool Search()
1440 if(this->First.get())
1442 return this->First->Search(*this);
1444 return false;
1446 private:
1447 virtual bool Visit(std::string const& fullPath) = 0;
1448 friend class cmFileListGeneratorBase;
1449 cmsys::auto_ptr<cmFileListGeneratorBase> First;
1450 cmFileListGeneratorBase* Last;
1453 class cmFindPackageFileList: public cmFileList
1455 public:
1456 cmFindPackageFileList(cmFindPackageCommand* fpc,
1457 bool use_suffixes = true):
1458 cmFileList(), FPC(fpc), UseSuffixes(use_suffixes) {}
1459 private:
1460 bool Visit(std::string const& fullPath)
1462 if(this->UseSuffixes)
1464 return this->FPC->SearchDirectory(fullPath);
1466 else
1468 return this->FPC->CheckDirectory(fullPath);
1471 cmFindPackageCommand* FPC;
1472 bool UseSuffixes;
1475 bool cmFileListGeneratorBase::Search(cmFileList& listing)
1477 return this->Search("", listing);
1480 cmFileListGeneratorBase*
1481 cmFileListGeneratorBase::SetNext(cmFileListGeneratorBase const& next)
1483 this->Next = next.Clone();
1484 return this->Next.get();
1487 bool cmFileListGeneratorBase::Consider(std::string const& fullPath,
1488 cmFileList& listing)
1490 if(this->Next.get())
1492 return this->Next->Search(fullPath + "/", listing);
1494 else
1496 return listing.Visit(fullPath + "/");
1500 class cmFileListGeneratorFixed: public cmFileListGeneratorBase
1502 public:
1503 cmFileListGeneratorFixed(std::string const& str):
1504 cmFileListGeneratorBase(), String(str) {}
1505 cmFileListGeneratorFixed(cmFileListGeneratorFixed const& r):
1506 cmFileListGeneratorBase(), String(r.String) {}
1507 private:
1508 std::string String;
1509 virtual bool Search(std::string const& parent, cmFileList& lister)
1511 std::string fullPath = parent + this->String;
1512 return this->Consider(fullPath, lister);
1514 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1516 cmsys::auto_ptr<cmFileListGeneratorBase>
1517 g(new cmFileListGeneratorFixed(*this));
1518 return g;
1522 class cmFileListGeneratorEnumerate: public cmFileListGeneratorBase
1524 public:
1525 cmFileListGeneratorEnumerate(std::vector<std::string> const& v):
1526 cmFileListGeneratorBase(), Vector(v) {}
1527 cmFileListGeneratorEnumerate(cmFileListGeneratorEnumerate const& r):
1528 cmFileListGeneratorBase(), Vector(r.Vector) {}
1529 private:
1530 std::vector<std::string> const& Vector;
1531 virtual bool Search(std::string const& parent, cmFileList& lister)
1533 for(std::vector<std::string>::const_iterator i = this->Vector.begin();
1534 i != this->Vector.end(); ++i)
1536 if(this->Consider(parent + *i, lister))
1538 return true;
1541 return false;
1543 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1545 cmsys::auto_ptr<cmFileListGeneratorBase>
1546 g(new cmFileListGeneratorEnumerate(*this));
1547 return g;
1551 class cmFileListGeneratorProject: public cmFileListGeneratorBase
1553 public:
1554 cmFileListGeneratorProject(std::vector<std::string> const& names):
1555 cmFileListGeneratorBase(), Names(names) {}
1556 cmFileListGeneratorProject(cmFileListGeneratorProject const& r):
1557 cmFileListGeneratorBase(), Names(r.Names) {}
1558 private:
1559 std::vector<std::string> const& Names;
1560 virtual bool Search(std::string const& parent, cmFileList& lister)
1562 // Construct a list of matches.
1563 std::vector<std::string> matches;
1564 cmsys::Directory d;
1565 d.Load(parent.c_str());
1566 for(unsigned long i=0; i < d.GetNumberOfFiles(); ++i)
1568 const char* fname = d.GetFile(i);
1569 if(strcmp(fname, ".") == 0 ||
1570 strcmp(fname, "..") == 0)
1572 continue;
1574 for(std::vector<std::string>::const_iterator ni = this->Names.begin();
1575 ni != this->Names.end(); ++ni)
1577 if(cmsysString_strncasecmp(fname, ni->c_str(),
1578 ni->length()) == 0)
1580 matches.push_back(fname);
1585 for(std::vector<std::string>::const_iterator i = matches.begin();
1586 i != matches.end(); ++i)
1588 if(this->Consider(parent + *i, lister))
1590 return true;
1593 return false;
1595 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1597 cmsys::auto_ptr<cmFileListGeneratorBase>
1598 g(new cmFileListGeneratorProject(*this));
1599 return g;
1603 class cmFileListGeneratorMacProject: public cmFileListGeneratorBase
1605 public:
1606 cmFileListGeneratorMacProject(std::vector<std::string> const& names,
1607 const char* ext):
1608 cmFileListGeneratorBase(), Names(names), Extension(ext) {}
1609 cmFileListGeneratorMacProject(cmFileListGeneratorMacProject const& r):
1610 cmFileListGeneratorBase(), Names(r.Names), Extension(r.Extension) {}
1611 private:
1612 std::vector<std::string> const& Names;
1613 std::string Extension;
1614 virtual bool Search(std::string const& parent, cmFileList& lister)
1616 // Construct a list of matches.
1617 std::vector<std::string> matches;
1618 cmsys::Directory d;
1619 d.Load(parent.c_str());
1620 for(unsigned long i=0; i < d.GetNumberOfFiles(); ++i)
1622 const char* fname = d.GetFile(i);
1623 if(strcmp(fname, ".") == 0 ||
1624 strcmp(fname, "..") == 0)
1626 continue;
1628 for(std::vector<std::string>::const_iterator ni = this->Names.begin();
1629 ni != this->Names.end(); ++ni)
1631 std::string name = *ni;
1632 name += this->Extension;
1633 if(cmsysString_strcasecmp(fname, name.c_str()) == 0)
1635 matches.push_back(fname);
1640 for(std::vector<std::string>::const_iterator i = matches.begin();
1641 i != matches.end(); ++i)
1643 if(this->Consider(parent + *i, lister))
1645 return true;
1648 return false;
1650 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1652 cmsys::auto_ptr<cmFileListGeneratorBase>
1653 g(new cmFileListGeneratorMacProject(*this));
1654 return g;
1658 class cmFileListGeneratorCaseInsensitive: public cmFileListGeneratorBase
1660 public:
1661 cmFileListGeneratorCaseInsensitive(std::string const& str):
1662 cmFileListGeneratorBase(), String(str) {}
1663 cmFileListGeneratorCaseInsensitive(
1664 cmFileListGeneratorCaseInsensitive const& r):
1665 cmFileListGeneratorBase(), String(r.String) {}
1666 private:
1667 std::string String;
1668 virtual bool Search(std::string const& parent, cmFileList& lister)
1670 // Look for matching files.
1671 std::vector<std::string> matches;
1672 cmsys::Directory d;
1673 d.Load(parent.c_str());
1674 for(unsigned long i=0; i < d.GetNumberOfFiles(); ++i)
1676 const char* fname = d.GetFile(i);
1677 if(strcmp(fname, ".") == 0 ||
1678 strcmp(fname, "..") == 0)
1680 continue;
1682 if(cmsysString_strcasecmp(fname, this->String.c_str()) == 0)
1684 if(this->Consider(parent + fname, lister))
1686 return true;
1690 return false;
1692 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1694 cmsys::auto_ptr<cmFileListGeneratorBase>
1695 g(new cmFileListGeneratorCaseInsensitive(*this));
1696 return g;
1700 class cmFileListGeneratorGlob: public cmFileListGeneratorBase
1702 public:
1703 cmFileListGeneratorGlob(std::string const& str):
1704 cmFileListGeneratorBase(), Pattern(str) {}
1705 cmFileListGeneratorGlob(cmFileListGeneratorGlob const& r):
1706 cmFileListGeneratorBase(), Pattern(r.Pattern) {}
1707 private:
1708 std::string Pattern;
1709 virtual bool Search(std::string const& parent, cmFileList& lister)
1711 // Glob the set of matching files.
1712 std::string expr = parent;
1713 expr += this->Pattern;
1714 cmsys::Glob g;
1715 if(!g.FindFiles(expr))
1717 return false;
1719 std::vector<std::string> const& files = g.GetFiles();
1721 // Look for directories among the matches.
1722 for(std::vector<std::string>::const_iterator fi = files.begin();
1723 fi != files.end(); ++fi)
1725 if(cmSystemTools::FileIsDirectory(fi->c_str()))
1727 if(this->Consider(*fi, lister))
1729 return true;
1733 return false;
1735 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1737 cmsys::auto_ptr<cmFileListGeneratorBase>
1738 g(new cmFileListGeneratorGlob(*this));
1739 return g;
1743 //----------------------------------------------------------------------------
1744 bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
1746 assert(!prefix_in.empty() && prefix_in[prefix_in.size()-1] == '/');
1747 if(this->DebugMode)
1749 fprintf(stderr, "Checking prefix [%s]\n", prefix_in.c_str());
1752 // Skip this if the prefix does not exist.
1753 if(!cmSystemTools::FileIsDirectory(prefix_in.c_str()))
1755 return false;
1758 // PREFIX/ (useful on windows or in build trees)
1759 if(this->SearchDirectory(prefix_in))
1761 return true;
1764 // Strip the trailing slash because the path generator is about to
1765 // add one.
1766 std::string prefix = prefix_in.substr(0, prefix_in.size()-1);
1768 // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
1770 cmFindPackageFileList lister(this);
1771 lister
1772 / cmFileListGeneratorFixed(prefix)
1773 / cmFileListGeneratorCaseInsensitive("cmake");
1774 if(lister.Search())
1776 return true;
1780 // PREFIX/(Foo|foo|FOO).*/
1782 cmFindPackageFileList lister(this);
1783 lister
1784 / cmFileListGeneratorFixed(prefix)
1785 / cmFileListGeneratorProject(this->Names);
1786 if(lister.Search())
1788 return true;
1792 // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
1794 cmFindPackageFileList lister(this);
1795 lister
1796 / cmFileListGeneratorFixed(prefix)
1797 / cmFileListGeneratorProject(this->Names)
1798 / cmFileListGeneratorCaseInsensitive("cmake");
1799 if(lister.Search())
1801 return true;
1805 // Construct list of common install locations (lib and share).
1806 std::vector<std::string> common;
1807 if(this->UseLib64Paths)
1809 common.push_back("lib64");
1811 common.push_back("lib");
1812 common.push_back("share");
1814 // PREFIX/(share|lib)/cmake/(Foo|foo|FOO).*/
1816 cmFindPackageFileList lister(this);
1817 lister
1818 / cmFileListGeneratorFixed(prefix)
1819 / cmFileListGeneratorEnumerate(common)
1820 / cmFileListGeneratorFixed("cmake")
1821 / cmFileListGeneratorProject(this->Names);
1822 if(lister.Search())
1824 return true;
1828 // PREFIX/(share|lib)/(Foo|foo|FOO).*/
1830 cmFindPackageFileList lister(this);
1831 lister
1832 / cmFileListGeneratorFixed(prefix)
1833 / cmFileListGeneratorEnumerate(common)
1834 / cmFileListGeneratorProject(this->Names);
1835 if(lister.Search())
1837 return true;
1841 // PREFIX/(share|lib)/(Foo|foo|FOO).*/(cmake|CMake)/
1843 cmFindPackageFileList lister(this);
1844 lister
1845 / cmFileListGeneratorFixed(prefix)
1846 / cmFileListGeneratorEnumerate(common)
1847 / cmFileListGeneratorProject(this->Names)
1848 / cmFileListGeneratorCaseInsensitive("cmake");
1849 if(lister.Search())
1851 return true;
1855 return false;
1858 //----------------------------------------------------------------------------
1859 bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
1861 assert(!prefix_in.empty() && prefix_in[prefix_in.size()-1] == '/');
1862 if(this->DebugMode)
1864 fprintf(stderr, "Checking framework prefix [%s]\n", prefix_in.c_str());
1867 // Strip the trailing slash because the path generator is about to
1868 // add one.
1869 std::string prefix = prefix_in.substr(0, prefix_in.size()-1);
1871 // <prefix>/Foo.framework/Resources/
1873 cmFindPackageFileList lister(this);
1874 lister
1875 / cmFileListGeneratorFixed(prefix)
1876 / cmFileListGeneratorMacProject(this->Names, ".framework")
1877 / cmFileListGeneratorFixed("Resources");
1878 if(lister.Search())
1880 return true;
1883 // <prefix>/Foo.framework/Resources/CMake/
1885 cmFindPackageFileList lister(this);
1886 lister
1887 / cmFileListGeneratorFixed(prefix)
1888 / cmFileListGeneratorMacProject(this->Names, ".framework")
1889 / cmFileListGeneratorFixed("Resources")
1890 / cmFileListGeneratorCaseInsensitive("cmake");
1891 if(lister.Search())
1893 return true;
1897 // <prefix>/Foo.framework/Versions/*/Resources/
1899 cmFindPackageFileList lister(this);
1900 lister
1901 / cmFileListGeneratorFixed(prefix)
1902 / cmFileListGeneratorMacProject(this->Names, ".framework")
1903 / cmFileListGeneratorFixed("Versions")
1904 / cmFileListGeneratorGlob("*/Resources");
1905 if(lister.Search())
1907 return true;
1911 // <prefix>/Foo.framework/Versions/*/Resources/CMake/
1913 cmFindPackageFileList lister(this);
1914 lister
1915 / cmFileListGeneratorFixed(prefix)
1916 / cmFileListGeneratorMacProject(this->Names, ".framework")
1917 / cmFileListGeneratorFixed("Versions")
1918 / cmFileListGeneratorGlob("*/Resources")
1919 / cmFileListGeneratorCaseInsensitive("cmake");
1920 if(lister.Search())
1922 return true;
1926 return false;
1929 //----------------------------------------------------------------------------
1930 bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
1932 assert(!prefix_in.empty() && prefix_in[prefix_in.size()-1] == '/');
1933 if(this->DebugMode)
1935 fprintf(stderr, "Checking bundle prefix [%s]\n", prefix_in.c_str());
1938 // Strip the trailing slash because the path generator is about to
1939 // add one.
1940 std::string prefix = prefix_in.substr(0, prefix_in.size()-1);
1942 // <prefix>/Foo.app/Contents/Resources
1944 cmFindPackageFileList lister(this);
1945 lister
1946 / cmFileListGeneratorFixed(prefix)
1947 / cmFileListGeneratorMacProject(this->Names, ".app")
1948 / cmFileListGeneratorFixed("Contents/Resources");
1949 if(lister.Search())
1951 return true;
1955 // <prefix>/Foo.app/Contents/Resources/CMake
1957 cmFindPackageFileList lister(this);
1958 lister
1959 / cmFileListGeneratorFixed(prefix)
1960 / cmFileListGeneratorMacProject(this->Names, ".app")
1961 / cmFileListGeneratorFixed("Contents/Resources")
1962 / cmFileListGeneratorCaseInsensitive("cmake");
1963 if(lister.Search())
1965 return true;
1969 return false;
1972 // TODO: Debug cmsys::Glob double slash problem.
1974 // TODO: Add registry entries after cmake system search path?
1975 // Currently the user must specify them with the PATHS option.
1977 // [HKEY_CURRENT_USER\Software\*\Foo*;InstallDir]
1978 // [HKEY_CURRENT_USER\Software\*\*\Foo*;InstallDir]
1979 // [HKEY_LOCAL_MACHINE\Software\*\Foo*;InstallDir]
1980 // [HKEY_LOCAL_MACHINE\Software\*\*\Foo*;InstallDir]