ENH: fix for VS6 and Cygwin
[cmake.git] / Source / cmFindPackageCommand.cxx
blob5b9cbbbdb97c887726a85fbe9191f1b712117f16
1 /*=========================================================================
3 Program: CMake - Cross-Platform Makefile Generator
4 Module: $RCSfile: cmFindPackageCommand.cxx,v $
5 Language: C++
6 Date: $Date: 2008-09-10 14:11:47 $
7 Version: $Revision: 1.45 $
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->VersionMajor = 0;
68 this->VersionMinor = 0;
69 this->VersionPatch = 0;
70 this->VersionTweak = 0;
71 this->VersionCount = 0;
72 this->VersionExact = false;
73 this->VersionFoundMajor = 0;
74 this->VersionFoundMinor = 0;
75 this->VersionFoundPatch = 0;
76 this->VersionFoundTweak = 0;
77 this->VersionFoundCount = 0;
78 this->CommandDocumentation =
79 " find_package(<package> [version] [EXACT] [QUIET]\n"
80 " [[REQUIRED|COMPONENTS] [components...]])\n"
81 "Finds and loads settings from an external project. "
82 "<package>_FOUND will be set to indicate whether the package was found. "
83 "When the package is found package-specific information is provided "
84 "through variables documented by the package itself. "
85 "The QUIET option disables messages if the package cannot be found. "
86 "The REQUIRED option stops processing with an error message if the "
87 "package cannot be found. "
88 "A package-specific list of components may be listed after the "
89 "REQUIRED option or after the COMPONENTS option if no REQUIRED "
90 "option is given. "
91 "The [version] argument requests a version with which the package found "
92 "should be compatible (format is major[.minor[.patch[.tweak]]]). "
93 "The EXACT option requests that the version be matched exactly. "
94 "Version support is currently provided only on a package-by-package "
95 "basis (details below).\n"
96 "User code should generally look for packages using the above simple "
97 "signature. The remainder of this command documentation specifies the "
98 "full command signature and details of the search process. Project "
99 "maintainers wishing to provide a package to be found by this command "
100 "are encouraged to read on.\n"
101 "The command has two modes by which it searches for packages: "
102 "\"Module\" mode and \"Config\" mode. "
103 "Module mode is available when the command is invoked with the above "
104 "reduced signature. "
105 "CMake searches for a file called \"Find<package>.cmake\" in "
106 "the CMAKE_MODULE_PATH followed by the CMake installation. "
107 "If the file is found, it is read and processed by CMake. "
108 "It is responsible for finding the package, checking the version, "
109 "and producing any needed messages. "
110 "Many find-modules provide limited or no support for versioning; "
111 "check the module documentation. "
112 "If no module is found the command proceeds to Config mode.\n"
113 "The complete Config mode command signature is:\n"
114 " find_package(<package> [version] [EXACT] [QUIET]\n"
115 " [[REQUIRED|COMPONENTS] [components...]] [NO_MODULE]\n"
116 " [NAMES name1 [name2 ...]]\n"
117 " [CONFIGS config1 [config2 ...]]\n"
118 " [HINTS path1 [path2 ... ]]\n"
119 " [PATHS path1 [path2 ... ]]\n"
120 " [PATH_SUFFIXES suffix1 [suffix2 ...]]\n"
121 " [NO_DEFAULT_PATH]\n"
122 " [NO_CMAKE_ENVIRONMENT_PATH]\n"
123 " [NO_CMAKE_PATH]\n"
124 " [NO_SYSTEM_ENVIRONMENT_PATH]\n"
125 " [NO_CMAKE_BUILDS_PATH]\n"
126 " [NO_CMAKE_SYSTEM_PATH]\n"
127 " [CMAKE_FIND_ROOT_PATH_BOTH |\n"
128 " ONLY_CMAKE_FIND_ROOT_PATH |\n"
129 " NO_CMAKE_FIND_ROOT_PATH])\n"
130 "The NO_MODULE option may be used to skip Module mode explicitly. "
131 "It is also implied by use of options not specified in the reduced "
132 "signature. "
133 "\n"
134 "Config mode attempts to locate a configuration file provided by the "
135 "package to be found. A cache entry called <package>_DIR is created to "
136 "hold the directory containing the file. "
137 "By default the command searches for a package with the name <package>. "
138 "If the NAMES option is given the names following it are used instead "
139 "of <package>. "
140 "The command searches for a file called \"<name>Config.cmake\" or "
141 "\"<lower-case-name>-config.cmake\" for each name specified. "
142 "A replacement set of possible configuration file names may be given "
143 "using the CONFIGS option. "
144 "The search procedure is specified below. Once found, the configuration "
145 "file is read and processed by CMake. Since the file is provided by the "
146 "package it already knows the location of package contents. "
147 "The full path to the configuration file is stored in the cmake "
148 "variable <package>_CONFIG."
149 "\n"
150 "If the package configuration file cannot be found CMake "
151 "will generate an error describing the problem unless the QUIET "
152 "argument is specified. If REQUIRED is specified and the package "
153 "is not found a fatal error is generated and the configure step stops "
154 "executing. If <package>_DIR has been set to a directory not containing "
155 "a configuration file a fatal error is always generated because user "
156 "intervention is required."
157 "\n"
158 "When the [version] argument is given Config mode will only find a "
159 "version of the package that claims compatibility with the requested "
160 "version (format is major[.minor[.patch[.tweak]]]). "
161 "If the EXACT option is given only a version of the package claiming "
162 "an exact match of the requested version may be found. "
163 "CMake does not establish any convention for the meaning of version "
164 "numbers. "
165 "Package version numbers are checked by \"version\" files provided by "
166 "the packages themselves. "
167 "For a candidate package confguration file \"<config-file>.cmake\" the "
168 "corresponding version file is located next to it and named either "
169 "\"<config-file>-version.cmake\" or \"<config-file>Version.cmake\". "
170 "If no such version file is available then the configuration file "
171 "is assumed to not be compatible with any requested version. "
172 "When a version file is found it is loaded to check the requested "
173 "version number. "
174 "The version file is loaded in a nested scope in which the following "
175 "variables have been defined:\n"
176 " PACKAGE_FIND_NAME = the <package> name\n"
177 " PACKAGE_FIND_VERSION = full requested version string\n"
178 " PACKAGE_FIND_VERSION_MAJOR = major version if requested, else 0\n"
179 " PACKAGE_FIND_VERSION_MINOR = minor version if requested, else 0\n"
180 " PACKAGE_FIND_VERSION_PATCH = patch version if requested, else 0\n"
181 " PACKAGE_FIND_VERSION_TWEAK = tweak version if requested, else 0\n"
182 " PACKAGE_FIND_VERSION_COUNT = number of version components, 0 to 4\n"
183 "The version file checks whether it satisfies the requested version "
184 "and sets these variables:\n"
185 " PACKAGE_VERSION = full provided version string\n"
186 " PACKAGE_VERSION_EXACT = true if version is exact match\n"
187 " PACKAGE_VERSION_COMPATIBLE = true if version is compatible\n"
188 "These variables are checked by the find_package command to determine "
189 "whether the configuration file provides an acceptable version. "
190 "They are not available after the find_package call returns. "
191 "If the version is acceptable the following variables are set:\n"
192 " <package>_VERSION = full provided version string\n"
193 " <package>_VERSION_MAJOR = major version if provided, else 0\n"
194 " <package>_VERSION_MINOR = minor version if provided, else 0\n"
195 " <package>_VERSION_PATCH = patch version if provided, else 0\n"
196 " <package>_VERSION_TWEAK = tweak version if provided, else 0\n"
197 " <package>_VERSION_COUNT = number of version components, 0 to 4\n"
198 "and the corresponding package configuration file is loaded. "
199 "When multiple package configuration files are available whose version "
200 "files claim compatibility with the version requested it is unspecified "
201 "which one is chosen. "
202 "No attempt is made to choose a highest or closest version number."
203 "\n"
204 "Config mode provides an elaborate interface and search procedure. "
205 "Much of the interface is provided for completeness and for use "
206 "internally by find-modules loaded by Module mode. "
207 "Most user code should simply call\n"
208 " find_package(<package> [major[.minor]] [EXACT] [REQUIRED|QUIET])\n"
209 "in order to find a package. Package maintainers providing CMake "
210 "package configuration files are encouraged to name and install "
211 "them such that the procedure outlined below will find them "
212 "without requiring use of additional options."
213 "\n"
214 "CMake constructs a set of possible installation prefixes for the "
215 "package. Under each prefix several directories are searched for a "
216 "configuration file. The tables below show the directories searched. "
217 "Each entry is meant for installation trees following Windows (W), "
218 "UNIX (U), or Apple (A) conventions.\n"
219 " <prefix>/ (W)\n"
220 " <prefix>/(cmake|CMake)/ (W)\n"
221 " <prefix>/(share|lib)/<name>*/ (U)\n"
222 " <prefix>/(share|lib)/<name>*/(cmake|CMake)/ (U)\n"
223 "On systems supporting OS X Frameworks and Application Bundles "
224 "the following directories are searched for frameworks or bundles "
225 "containing a configuration file:\n"
226 " <prefix>/<name>.framework/Resources/ (A)\n"
227 " <prefix>/<name>.framework/Resources/CMake/ (A)\n"
228 " <prefix>/<name>.framework/Versions/*/Resources/ (A)\n"
229 " <prefix>/<name>.framework/Versions/*/Resources/CMake/ (A)\n"
230 " <prefix>/<name>.app/Contents/Resources/ (A)\n"
231 " <prefix>/<name>.app/Contents/Resources/CMake/ (A)\n"
232 "In all cases the <name> is treated as case-insensitive and corresponds "
233 "to any of the names specified (<package> or names given by NAMES). "
234 "If PATH_SUFFIXES is specified the suffixes are appended to each "
235 "(W) or (U) directory entry one-by-one.\n"
236 "This set of directories is intended to work in cooperation with "
237 "projects that provide configuration files in their installation trees. "
238 "Directories above marked with (W) are intended for installations on "
239 "Windows where the prefix may point at the top of an application's "
240 "installation directory. Those marked with (U) are intended for "
241 "installations on UNIX platforms where the prefix is shared by "
242 "multiple packages. This is merely a convention, so all (W) and (U) "
243 "directories are still searched on all platforms. "
244 "Directories marked with (A) are intended for installations on "
245 "Apple platforms. The cmake variables CMAKE_FIND_FRAMEWORK and "
246 "CMAKE_FIND_APPBUNDLE determine the order of preference "
247 "as specified below.\n"
248 "The set of installation prefixes is constructed using the following "
249 "steps. If NO_DEFAULT_PATH is specified all NO_* options are enabled.\n"
250 "1. Search paths specified in cmake-specific cache variables. "
251 "These are intended to be used on the command line with a -DVAR=value. "
252 "This can be skipped if NO_CMAKE_PATH is passed.\n"
253 " CMAKE_PREFIX_PATH\n"
254 " CMAKE_FRAMEWORK_PATH\n"
255 " CMAKE_APPBUNDLE_PATH\n"
256 "2. Search paths specified in cmake-specific environment variables. "
257 "These are intended to be set in the user's shell configuration. "
258 "This can be skipped if NO_CMAKE_ENVIRONMENT_PATH is passed.\n"
259 " CMAKE_PREFIX_PATH\n"
260 " CMAKE_FRAMEWORK_PATH\n"
261 " CMAKE_APPBUNDLE_PATH\n"
262 "3. Search paths specified by the HINTS option. "
263 "These should be paths computed by system introspection, such as a "
264 "hint provided by the location of another item already found. "
265 "Hard-coded guesses should be specified with the PATHS option.\n"
266 "4. Search the standard system environment variables. "
267 "This can be skipped if NO_SYSTEM_ENVIRONMENT_PATH is passed. "
268 "Path entries ending in \"/bin\" or \"/sbin\" are automatically "
269 "converted to their parent directories.\n"
270 " PATH\n"
271 "5. Search project build trees recently configured in a CMake GUI. "
272 "This can be skipped if NO_CMAKE_BUILDS_PATH is passed. "
273 "It is intended for the case when a user is building multiple "
274 "dependent projects one after another.\n"
275 "6. Search cmake variables defined in the Platform files "
276 "for the current system. This can be skipped if NO_CMAKE_SYSTEM_PATH "
277 "is passed.\n"
278 " CMAKE_SYSTEM_PREFIX_PATH\n"
279 " CMAKE_SYSTEM_FRAMEWORK_PATH\n"
280 " CMAKE_SYSTEM_APPBUNDLE_PATH\n"
281 "7. Search paths specified by the PATHS option. "
282 "These are typically hard-coded guesses.\n"
284 this->CommandDocumentation += this->GenericDocumentationMacPolicy;
285 this->CommandDocumentation += this->GenericDocumentationRootPath;
286 this->CommandDocumentation += this->GenericDocumentationPathsOrder;
289 //----------------------------------------------------------------------------
290 const char* cmFindPackageCommand::GetFullDocumentation()
292 return this->CommandDocumentation.c_str();
295 //----------------------------------------------------------------------------
296 bool cmFindPackageCommand
297 ::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
299 if(args.size() < 1)
301 this->SetError("called with incorrect number of arguments");
302 return false;
305 // Check for debug mode.
306 this->DebugMode = this->Makefile->IsOn("CMAKE_FIND_DEBUG_MODE");
308 // Lookup whether lib64 paths should be used.
309 if(const char* sizeof_dptr =
310 this->Makefile->GetDefinition("CMAKE_SIZEOF_VOID_P"))
312 if(atoi(sizeof_dptr) == 8 &&
313 this->Makefile->GetCMakeInstance()
314 ->GetPropertyAsBool("FIND_LIBRARY_USE_LIB64_PATHS"))
316 this->UseLib64Paths = true;
320 // Find the current root path mode.
321 this->SelectDefaultRootPathMode();
323 // Find the current bundle/framework search policy.
324 this->SelectDefaultMacMode();
326 // Record options.
327 this->Name = args[0];
328 std::string components;
329 const char* components_sep = "";
331 // Check ancient compatibility.
332 this->Compatibility_1_6 =
333 this->Makefile->GetLocalGenerator()
334 ->NeedBackwardsCompatibility(1, 6);
336 // Always search directly in a generated path.
337 this->SearchPathSuffixes.push_back("");
339 // Parse the arguments.
340 enum Doing { DoingNone, DoingComponents, DoingNames, DoingPaths,
341 DoingPathSuffixes, DoingConfigs, DoingHints };
342 Doing doing = DoingNone;
343 cmsys::RegularExpression version("^[0-9.]+$");
344 bool haveVersion = false;
345 for(unsigned int i=1; i < args.size(); ++i)
347 if(args[i] == "QUIET")
349 this->Quiet = true;
350 doing = DoingNone;
352 else if(args[i] == "EXACT")
354 this->VersionExact = true;
355 this->Compatibility_1_6 = false;
356 doing = DoingNone;
358 else if(args[i] == "NO_MODULE")
360 this->NoModule = true;
361 doing = DoingNone;
363 else if(args[i] == "REQUIRED")
365 this->Required = true;
366 doing = DoingComponents;
368 else if(args[i] == "COMPONENTS")
370 this->Compatibility_1_6 = false;
371 doing = DoingComponents;
373 else if(args[i] == "NAMES")
375 this->NoModule = true;
376 this->Compatibility_1_6 = false;
377 doing = DoingNames;
379 else if(args[i] == "PATHS")
381 this->NoModule = true;
382 this->Compatibility_1_6 = false;
383 doing = DoingPaths;
385 else if(args[i] == "HINTS")
387 this->NoModule = true;
388 this->Compatibility_1_6 = false;
389 doing = DoingHints;
391 else if(args[i] == "PATH_SUFFIXES")
393 this->NoModule = true;
394 this->Compatibility_1_6 = false;
395 doing = DoingPathSuffixes;
397 else if(args[i] == "CONFIGS")
399 this->NoModule = true;
400 this->Compatibility_1_6 = false;
401 doing = DoingConfigs;
403 else if(args[i] == "NO_CMAKE_BUILDS_PATH")
405 this->NoBuilds = true;
406 this->NoModule = true;
407 this->Compatibility_1_6 = false;
408 doing = DoingNone;
410 else if(this->CheckCommonArgument(args[i]))
412 this->NoModule = true;
413 this->Compatibility_1_6 = false;
414 doing = DoingNone;
416 else if(doing == DoingComponents)
418 // Set a variable telling the find script this component
419 // is required.
420 std::string req_var = this->Name + "_FIND_REQUIRED_" + args[i];
421 this->Makefile->AddDefinition(req_var.c_str(), "1");
423 // Append to the list of required components.
424 components += components_sep;
425 components += args[i];
426 components_sep = ";";
428 else if(doing == DoingNames)
430 this->Names.push_back(args[i]);
432 else if(doing == DoingPaths)
434 this->AddUserPath(args[i], this->UserPaths);
436 else if(doing == DoingHints)
438 this->AddUserPath(args[i], this->UserHints);
440 else if(doing == DoingPathSuffixes)
442 this->AddPathSuffix(args[i]);
444 else if(doing == DoingConfigs)
446 if(args[i].find_first_of(":/\\") != args[i].npos ||
447 cmSystemTools::GetFilenameLastExtension(args[i]) != ".cmake")
449 cmOStringStream e;
450 e << "given CONFIGS option followed by invalid file name \""
451 << args[i] << "\". The names given must be file names without "
452 << "a path and with a \".cmake\" extension.";
453 return false;
455 this->Configs.push_back(args[i]);
457 else if(!haveVersion && version.find(args[i].c_str()))
459 haveVersion = true;
460 this->Version = args[i];
462 else
464 cmOStringStream e;
465 e << "called with invalid argument \"" << args[i].c_str() << "\"";
466 this->SetError(e.str().c_str());
467 return false;
471 if(!this->Version.empty())
473 // Try to parse the version number and store the results that were
474 // successfully parsed.
475 unsigned int parsed_major;
476 unsigned int parsed_minor;
477 unsigned int parsed_patch;
478 unsigned int parsed_tweak;
479 this->VersionCount = sscanf(this->Version.c_str(), "%u.%u.%u.%u",
480 &parsed_major, &parsed_minor,
481 &parsed_patch, &parsed_tweak);
482 switch(this->VersionCount)
484 case 4: this->VersionTweak = parsed_tweak; // no break!
485 case 3: this->VersionPatch = parsed_patch; // no break!
486 case 2: this->VersionMinor = parsed_minor; // no break!
487 case 1: this->VersionMajor = parsed_major; // no break!
488 default: break;
492 this->SetModuleVariables(components);
494 // See if there is a Find<package>.cmake module.
495 if(!this->NoModule)
497 bool foundModule = false;
498 if(!this->FindModule(foundModule))
500 this->AppendSuccessInformation();
501 return false;
503 if(foundModule)
505 this->AppendSuccessInformation();
506 return true;
510 // No find module. Assume the project has a CMake config file. Use
511 // a <package>_DIR cache variable to locate it.
512 this->Variable = this->Name;
513 this->Variable += "_DIR";
515 // Add the default name.
516 if(this->Names.empty())
518 this->Names.push_back(this->Name);
521 // Add the default configs.
522 if(this->Configs.empty())
524 for(std::vector<std::string>::const_iterator ni = this->Names.begin();
525 ni != this->Names.end(); ++ni)
527 std::string config = *ni;
528 config += "Config.cmake";
529 this->Configs.push_back(config);
531 config = cmSystemTools::LowerCase(*ni);
532 config += "-config.cmake";
533 this->Configs.push_back(config);
537 // Find and load the package.
538 bool result = this->HandlePackageMode();
539 this->AppendSuccessInformation();
540 return result;
544 //----------------------------------------------------------------------------
545 void cmFindPackageCommand::SetModuleVariables(const std::string& components)
547 // Store the list of components.
548 std::string components_var = this->Name + "_FIND_COMPONENTS";
549 this->Makefile->AddDefinition(components_var.c_str(), components.c_str());
551 if(this->Quiet)
553 // Tell the module that is about to be read that it should find
554 // quietly.
555 std::string quietly = this->Name;
556 quietly += "_FIND_QUIETLY";
557 this->Makefile->AddDefinition(quietly.c_str(), "1");
560 if(this->Required)
562 // Tell the module that is about to be read that it should report
563 // a fatal error if the package is not found.
564 std::string req = this->Name;
565 req += "_FIND_REQUIRED";
566 this->Makefile->AddDefinition(req.c_str(), "1");
569 if(!this->Version.empty())
571 // Tell the module that is about to be read what version of the
572 // package has been requested.
573 std::string ver = this->Name;
574 ver += "_FIND_VERSION";
575 this->Makefile->AddDefinition(ver.c_str(), this->Version.c_str());
576 char buf[64];
577 sprintf(buf, "%u", this->VersionMajor);
578 this->Makefile->AddDefinition((ver+"_MAJOR").c_str(), buf);
579 sprintf(buf, "%u", this->VersionMinor);
580 this->Makefile->AddDefinition((ver+"_MINOR").c_str(), buf);
581 sprintf(buf, "%u", this->VersionPatch);
582 this->Makefile->AddDefinition((ver+"_PATCH").c_str(), buf);
583 sprintf(buf, "%u", this->VersionTweak);
584 this->Makefile->AddDefinition((ver+"_TWEAK").c_str(), buf);
585 sprintf(buf, "%u", this->VersionCount);
586 this->Makefile->AddDefinition((ver+"_COUNT").c_str(), buf);
588 // Tell the module whether an exact version has been requested.
589 std::string exact = this->Name;
590 exact += "_FIND_VERSION_EXACT";
591 this->Makefile->AddDefinition(exact.c_str(),
592 this->VersionExact? "1":"0");
597 //----------------------------------------------------------------------------
598 bool cmFindPackageCommand::FindModule(bool& found)
600 std::string module = "Find";
601 module += this->Name;
602 module += ".cmake";
603 std::string mfile = this->Makefile->GetModulesFile(module.c_str());
604 if ( mfile.size() )
606 // Load the module we found.
607 found = true;
608 return this->ReadListFile(mfile.c_str());
610 return true;
613 //----------------------------------------------------------------------------
614 bool cmFindPackageCommand::HandlePackageMode()
616 // Support old capitalization behavior.
617 std::string upperDir = cmSystemTools::UpperCase(this->Name);
618 std::string upperFound = cmSystemTools::UpperCase(this->Name);
619 upperDir += "_DIR";
620 upperFound += "_FOUND";
621 if(upperDir == this->Variable)
623 this->Compatibility_1_6 = false;
626 // Try to find the config file.
627 const char* def = this->Makefile->GetDefinition(this->Variable.c_str());
628 if(this->Compatibility_1_6 && cmSystemTools::IsOff(def))
630 // Use the setting of the old name of the variable to provide the
631 // value of the new.
632 const char* oldDef = this->Makefile->GetDefinition(upperDir.c_str());
633 if(!cmSystemTools::IsOff(oldDef))
635 this->Makefile->AddDefinition(this->Variable.c_str(), oldDef);
636 def = this->Makefile->GetDefinition(this->Variable.c_str());
640 // Search for the config file if it is not already found.
641 if(cmSystemTools::IsOff(def))
643 this->FindConfig();
644 def = this->Makefile->GetDefinition(this->Variable.c_str());
647 // If the config file was found, load it.
648 std::string file;
649 bool result = true;
650 bool found = false;
651 if(!cmSystemTools::IsOff(def))
653 // Get the directory from the variable value.
654 std::string dir = def;
655 cmSystemTools::ConvertToUnixSlashes(dir);
657 // Treat relative paths with respect to the current source dir.
658 if(!cmSystemTools::FileIsFullPath(dir.c_str()))
660 dir = "/" + dir;
661 dir = this->Makefile->GetCurrentDirectory() + dir;
664 // Find the configuration file.
665 if(this->FindConfigFileToLoad(dir, file))
667 // Set the version variables before loading the config file.
668 // It may override them.
669 this->StoreVersionFound();
671 // Parse the configuration file.
672 if(this->ReadListFile(file.c_str()))
674 // The package has been found.
675 found = true;
677 else
679 // The configuration file is invalid.
680 result = false;
683 else
685 // The variable setting is wrong.
686 cmOStringStream e;
687 e << "cannot find package " << this->Name << " because "
688 << this->Variable << " is set to \"" << def << "\" "
689 << "which is not a directory containing a package configuration "
690 << "file (or it is not for the requested version). "
691 << "Please set the cache entry " << this->Variable << " "
692 << "to the correct directory, or delete it to ask CMake "
693 << "to search.";
694 this->SetError(e.str().c_str());
695 result = false;
698 else if(!this->Quiet || this->Required)
700 // The variable is not set.
701 cmOStringStream e;
702 e << "Could not find ";
703 if(!this->NoModule)
705 e << "module Find" << this->Name << ".cmake or ";
707 e << "a configuration file for package " << this->Name << ".\n";
708 if(!this->NoModule)
710 e << "Adjust CMAKE_MODULE_PATH to find Find"
711 << this->Name << ".cmake or set ";
713 else
715 e << "Set ";
717 e << this->Variable << " to the directory containing a CMake "
718 << "configuration file for " << this->Name << ". ";
719 if(this->Configs.size() == 1)
721 e << "The file will be called " << this->Configs[0];
723 else
725 e << "The file will have one of the following names:\n";
726 for(std::vector<std::string>::const_iterator ci = this->Configs.begin();
727 ci != this->Configs.end(); ++ci)
729 e << " " << *ci << "\n";
732 this->Makefile->IssueMessage(
733 this->Required? cmake::FATAL_ERROR : cmake::WARNING, e.str());
736 // Set a variable marking whether the package was found.
737 std::string foundVar = this->Name;
738 foundVar += "_FOUND";
739 this->Makefile->AddDefinition(foundVar.c_str(), found? "1":"0");
741 // Set a variable naming the configuration file that was found.
742 std::string fileVar = this->Name;
743 fileVar += "_CONFIG";
744 if(found)
746 this->Makefile->AddDefinition(fileVar.c_str(), file.c_str());
748 else
750 this->Makefile->RemoveDefinition(fileVar.c_str());
753 // Handle some ancient compatibility stuff.
754 if(this->Compatibility_1_6)
756 // Listfiles will be looking for the capitalized version of the
757 // name. Provide it.
758 this->Makefile->AddDefinition
759 (upperDir.c_str(),
760 this->Makefile->GetDefinition(this->Variable.c_str()));
761 this->Makefile->AddDefinition
762 (upperFound.c_str(),
763 this->Makefile->GetDefinition(foundVar.c_str()));
766 #ifdef CMAKE_BUILD_WITH_CMAKE
767 if(!(upperDir == this->Variable))
769 if(this->Compatibility_1_6)
771 // Listfiles may use the capitalized version of the name.
772 // Remove any previously added watch.
773 this->Makefile->GetVariableWatch()->RemoveWatch(
774 upperDir.c_str(),
775 cmFindPackageNeedBackwardsCompatibility
778 else
780 // Listfiles should not be using the capitalized version of the
781 // name. Add a watch to warn the user.
782 this->Makefile->GetVariableWatch()->AddWatch(
783 upperDir.c_str(),
784 cmFindPackageNeedBackwardsCompatibility
788 #endif
790 return result;
793 //----------------------------------------------------------------------------
794 void cmFindPackageCommand::FindConfig()
796 // Compute the set of search prefixes.
797 this->ComputePrefixes();
799 // Look for the project's configuration file.
800 bool found = false;
802 // Search for frameworks.
803 if(!found && this->SearchFrameworkFirst || this->SearchFrameworkOnly)
805 found = this->FindFrameworkConfig();
808 // Search for apps.
809 if(!found && this->SearchAppBundleFirst || this->SearchAppBundleOnly)
811 found = this->FindAppBundleConfig();
814 // Search prefixes.
815 if(!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly))
817 found = this->FindPrefixedConfig();
820 // Search for frameworks.
821 if(!found && this->SearchFrameworkLast)
823 found = this->FindFrameworkConfig();
826 // Search for apps.
827 if(!found && this->SearchAppBundleLast)
829 found = this->FindAppBundleConfig();
832 // Store the entry in the cache so it can be set by the user.
833 std::string init;
834 if(found)
836 init = cmSystemTools::GetFilenamePath(this->FileFound);
838 else
840 init = this->Variable + "-NOTFOUND";
842 std::string help =
843 "The directory containing a CMake configuration file for ";
844 help += this->Name;
845 help += ".";
846 this->Makefile->AddCacheDefinition(this->Variable.c_str(),
847 init.c_str(), help.c_str(),
848 cmCacheManager::PATH);
851 //----------------------------------------------------------------------------
852 bool cmFindPackageCommand::FindPrefixedConfig()
854 std::vector<std::string>& prefixes = this->SearchPaths;
855 for(std::vector<std::string>::const_iterator pi = prefixes.begin();
856 pi != prefixes.end(); ++pi)
858 if(this->SearchPrefix(*pi))
860 return true;
863 return false;
866 //----------------------------------------------------------------------------
867 bool cmFindPackageCommand::FindFrameworkConfig()
869 std::vector<std::string>& prefixes = this->SearchPaths;
870 for(std::vector<std::string>::const_iterator i = prefixes.begin();
871 i != prefixes.end(); ++i)
873 if(this->SearchFrameworkPrefix(*i))
875 return true;
878 return false;
881 //----------------------------------------------------------------------------
882 bool cmFindPackageCommand::FindAppBundleConfig()
884 std::vector<std::string>& prefixes = this->SearchPaths;
885 for(std::vector<std::string>::const_iterator i = prefixes.begin();
886 i != prefixes.end(); ++i)
888 if(this->SearchAppBundlePrefix(*i))
890 return true;
893 return false;
896 //----------------------------------------------------------------------------
897 bool cmFindPackageCommand::ReadListFile(const char* f)
899 if(this->Makefile->ReadListFile(this->Makefile->GetCurrentListFile(),f))
901 return true;
903 std::string e = "Error reading CMake code from \"";
904 e += f;
905 e += "\".";
906 this->SetError(e.c_str());
907 return false;
910 //----------------------------------------------------------------------------
911 void cmFindPackageCommand::AppendToProperty(const char* propertyName)
913 std::string propertyValue;
914 const char *prop =
915 this->Makefile->GetCMakeInstance()->GetProperty(propertyName);
916 if (prop && *prop)
918 propertyValue = prop;
920 std::vector<std::string> contents;
921 cmSystemTools::ExpandListArgument(propertyValue, contents, false);
923 bool alreadyInserted = false;
924 for(std::vector<std::string>::const_iterator it = contents.begin();
925 it != contents.end(); ++ it )
927 if (*it == this->Name)
929 alreadyInserted = true;
930 break;
933 if (!alreadyInserted)
935 propertyValue += ";";
936 propertyValue += this->Name;
939 else
941 propertyValue = this->Name;
943 this->Makefile->GetCMakeInstance()->SetProperty(propertyName,
944 propertyValue.c_str());
947 //----------------------------------------------------------------------------
948 void cmFindPackageCommand::AppendSuccessInformation()
950 std::string found = this->Name;
951 found += "_FOUND";
952 std::string upperFound = cmSystemTools::UpperCase(found);
954 const char* upperResult = this->Makefile->GetDefinition(upperFound.c_str());
955 const char* result = this->Makefile->GetDefinition(found.c_str());
956 if ((cmSystemTools::IsOn(result)) || (cmSystemTools::IsOn(upperResult)))
958 this->AppendToProperty("PACKAGES_FOUND");
959 if (!this->Quiet)
961 this->AppendToProperty("ENABLED_FEATURES");
964 else
966 this->AppendToProperty("PACKAGES_NOT_FOUND");
967 if (!this->Quiet)
969 this->AppendToProperty("DISABLED_FEATURES");
974 //----------------------------------------------------------------------------
975 void cmFindPackageCommand::ComputePrefixes()
977 this->AddPrefixesCMakeVariable();
978 this->AddPrefixesCMakeEnvironment();
979 this->AddPrefixesUserHints();
980 this->AddPrefixesSystemEnvironment();
981 this->AddPrefixesBuilds();
982 this->AddPrefixesCMakeSystemVariable();
983 this->AddPrefixesUserGuess();
984 this->ComputeFinalPrefixes();
987 //----------------------------------------------------------------------------
988 void cmFindPackageCommand::AddPrefixesCMakeEnvironment()
990 if(!this->NoCMakeEnvironmentPath && !this->NoDefaultPath)
992 // Check the environment variable with the same name as the cache
993 // entry.
994 std::string env;
995 if(cmSystemTools::GetEnv(this->Variable.c_str(), env) && env.length() > 0)
997 cmSystemTools::ConvertToUnixSlashes(env);
998 this->AddPathInternal(env, EnvPath);
1001 this->AddEnvPath("CMAKE_PREFIX_PATH");
1002 this->AddEnvPath("CMAKE_FRAMEWORK_PATH");
1003 this->AddEnvPath("CMAKE_APPBUNDLE_PATH");
1007 //----------------------------------------------------------------------------
1008 void cmFindPackageCommand::AddPrefixesCMakeVariable()
1010 if(!this->NoCMakePath && !this->NoDefaultPath)
1012 this->AddCMakePath("CMAKE_PREFIX_PATH");
1013 this->AddCMakePath("CMAKE_FRAMEWORK_PATH");
1014 this->AddCMakePath("CMAKE_APPBUNDLE_PATH");
1018 //----------------------------------------------------------------------------
1019 void cmFindPackageCommand::AddPrefixesSystemEnvironment()
1021 if(!this->NoSystemEnvironmentPath && !this->NoDefaultPath)
1023 // Use the system search path to generate prefixes.
1024 // Relative paths are interpreted with respect to the current
1025 // working directory.
1026 std::vector<std::string> tmp;
1027 cmSystemTools::GetPath(tmp);
1028 for(std::vector<std::string>::iterator i = tmp.begin();
1029 i != tmp.end(); ++i)
1031 std::string const& d = *i;
1033 // If the path is a PREFIX/bin case then add its parent instead.
1034 if(d.size() >= 4 && strcmp(d.c_str()+d.size()-4, "/bin") == 0 ||
1035 d.size() >= 5 && strcmp(d.c_str()+d.size()-5, "/sbin") == 0)
1037 this->AddPathInternal(cmSystemTools::GetFilenamePath(d), EnvPath);
1039 else
1041 this->AddPathInternal(d, EnvPath);
1047 //----------------------------------------------------------------------------
1048 void cmFindPackageCommand::AddPrefixesBuilds()
1050 if(!this->NoBuilds && !this->NoDefaultPath)
1052 // It is likely that CMake will have recently built the project.
1053 for(int i=1; i <= 10; ++i)
1055 cmOStringStream r;
1056 r <<
1057 "[HKEY_CURRENT_USER\\Software\\Kitware\\CMakeSetup\\"
1058 "Settings\\StartPath;WhereBuild" << i << "]";
1059 std::string f = r.str();
1060 cmSystemTools::ExpandRegistryValues(f);
1061 cmSystemTools::ConvertToUnixSlashes(f);
1062 if(cmSystemTools::FileIsFullPath(f.c_str()) &&
1063 cmSystemTools::FileIsDirectory(f.c_str()))
1065 this->AddPathInternal(f, FullPath);
1071 //----------------------------------------------------------------------------
1072 void cmFindPackageCommand::AddPrefixesCMakeSystemVariable()
1074 if(!this->NoCMakeSystemPath && !this->NoDefaultPath)
1076 this->AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
1077 this->AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
1078 this->AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
1082 //----------------------------------------------------------------------------
1083 void cmFindPackageCommand::AddPrefixesUserGuess()
1085 // Add guesses specified by the caller.
1086 this->AddPathsInternal(this->UserPaths, CMakePath);
1089 //----------------------------------------------------------------------------
1090 void cmFindPackageCommand::AddPrefixesUserHints()
1092 // Add hints specified by the caller.
1093 this->AddPathsInternal(this->UserHints, CMakePath);
1096 //----------------------------------------------------------------------------
1097 void cmFindPackageCommand::ComputeFinalPrefixes()
1099 std::vector<std::string>& prefixes = this->SearchPaths;
1101 // Construct the final set of prefixes.
1102 this->RerootPaths(prefixes);
1104 // Add a trailing slash to all prefixes to aid the search process.
1105 this->AddTrailingSlashes(prefixes);
1108 //----------------------------------------------------------------------------
1109 bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
1111 assert(!dir.empty() && dir[dir.size()-1] == '/');
1113 // Check each path suffix on this directory.
1114 for(std::vector<std::string>::const_iterator
1115 si = this->SearchPathSuffixes.begin();
1116 si != this->SearchPathSuffixes.end(); ++si)
1118 std::string d = dir;
1119 if(!si->empty())
1121 d += *si;
1122 d += "/";
1124 if(this->CheckDirectory(d))
1126 return true;
1129 return false;
1132 //----------------------------------------------------------------------------
1133 bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
1135 assert(!dir.empty() && dir[dir.size()-1] == '/');
1137 // Look for the file in this directory.
1138 std::string d = dir.substr(0, dir.size()-1);
1139 if(this->FindConfigFile(d, this->FileFound))
1141 // Remove duplicate slashes.
1142 cmSystemTools::ConvertToUnixSlashes(this->FileFound);
1143 return true;
1145 return false;
1148 //----------------------------------------------------------------------------
1149 bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
1150 std::string& file)
1152 for(std::vector<std::string>::const_iterator ci = this->Configs.begin();
1153 ci != this->Configs.end(); ++ci)
1155 file = dir;
1156 file += "/";
1157 file += *ci;
1158 if(this->DebugMode)
1160 fprintf(stderr, "Checking file [%s]\n", file.c_str());
1162 if(cmSystemTools::FileExists(file.c_str(), true) &&
1163 this->CheckVersion(file))
1165 return true;
1168 return false;
1171 //----------------------------------------------------------------------------
1172 bool cmFindPackageCommand::FindConfigFileToLoad(std::string const& dir,
1173 std::string& file)
1175 if(this->FileFound.empty())
1177 // The file location was cached. Look for the correct file.
1178 return this->FindConfigFile(dir, file);
1180 else
1182 // The file location was just found during this call.
1183 // Use the file found without searching again.
1184 file = this->FileFound;
1185 return true;
1189 //----------------------------------------------------------------------------
1190 bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
1192 // Get the filename without the .cmake extension.
1193 std::string::size_type pos = config_file.rfind('.');
1194 std::string version_file_base = config_file.substr(0, pos);
1196 // Look for foo-config-version.cmake
1197 std::string version_file = version_file_base;
1198 version_file += "-version.cmake";
1199 if(cmSystemTools::FileExists(version_file.c_str(), true))
1201 return this->CheckVersionFile(version_file);
1204 // Look for fooConfigVersion.cmake
1205 version_file = version_file_base;
1206 version_file += "Version.cmake";
1207 if(cmSystemTools::FileExists(version_file.c_str(), true))
1209 return this->CheckVersionFile(version_file);
1212 // If no version was requested a versionless package is acceptable.
1213 if(this->Version.empty())
1215 return true;
1218 // No version file found. Assume the version is incompatible.
1219 return false;
1222 //----------------------------------------------------------------------------
1223 bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file)
1225 // The version file will be loaded in an isolated scope.
1226 this->Makefile->PushScope();
1228 // Clear the output variables.
1229 this->Makefile->RemoveDefinition("PACKAGE_VERSION");
1230 this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
1231 this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
1233 // Set the input variables.
1234 this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name.c_str());
1235 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION",
1236 this->Version.c_str());
1237 char buf[64];
1238 sprintf(buf, "%u", this->VersionMajor);
1239 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MAJOR", buf);
1240 sprintf(buf, "%u", this->VersionMinor);
1241 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MINOR", buf);
1242 sprintf(buf, "%u", this->VersionPatch);
1243 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_PATCH", buf);
1244 sprintf(buf, "%u", this->VersionTweak);
1245 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_TWEAK", buf);
1246 sprintf(buf, "%u", this->VersionCount);
1247 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COUNT", buf);
1249 // Load the version check file.
1250 bool found = false;
1251 if(this->ReadListFile(version_file.c_str()))
1253 // Check the output variables.
1254 found = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
1255 if(!found && !this->VersionExact)
1257 found = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
1259 if(found || this->Version.empty())
1261 // Get the version found.
1262 this->VersionFound =
1263 this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
1265 // Try to parse the version number and store the results that were
1266 // successfully parsed.
1267 unsigned int parsed_major;
1268 unsigned int parsed_minor;
1269 unsigned int parsed_patch;
1270 unsigned int parsed_tweak;
1271 this->VersionFoundCount =
1272 sscanf(this->VersionFound.c_str(), "%u.%u.%u.%u",
1273 &parsed_major, &parsed_minor,
1274 &parsed_patch, &parsed_tweak);
1275 switch(this->VersionFoundCount)
1277 case 4: this->VersionFoundTweak = parsed_tweak; // no break!
1278 case 3: this->VersionFoundPatch = parsed_patch; // no break!
1279 case 2: this->VersionFoundMinor = parsed_minor; // no break!
1280 case 1: this->VersionFoundMajor = parsed_major; // no break!
1281 default: break;
1286 // Restore the original scope.
1287 this->Makefile->PopScope();
1289 // Succeed if the version was found or no version was requested.
1290 return found || this->Version.empty();
1293 //----------------------------------------------------------------------------
1294 void cmFindPackageCommand::StoreVersionFound()
1296 // Store the whole version string.
1297 std::string ver = this->Name;
1298 ver += "_VERSION";
1299 if(this->VersionFound.empty())
1301 this->Makefile->RemoveDefinition(ver.c_str());
1303 else
1305 this->Makefile->AddDefinition(ver.c_str(), this->VersionFound.c_str());
1308 // Store the version components.
1309 char buf[64];
1310 sprintf(buf, "%u", this->VersionFoundMajor);
1311 this->Makefile->AddDefinition((ver+"_MAJOR").c_str(), buf);
1312 sprintf(buf, "%u", this->VersionFoundMinor);
1313 this->Makefile->AddDefinition((ver+"_MINOR").c_str(), buf);
1314 sprintf(buf, "%u", this->VersionFoundPatch);
1315 this->Makefile->AddDefinition((ver+"_PATCH").c_str(), buf);
1316 sprintf(buf, "%u", this->VersionFoundTweak);
1317 this->Makefile->AddDefinition((ver+"_TWEAK").c_str(), buf);
1318 sprintf(buf, "%u", this->VersionFoundCount);
1319 this->Makefile->AddDefinition((ver+"_COUNT").c_str(), buf);
1322 //----------------------------------------------------------------------------
1323 #include <cmsys/Directory.hxx>
1324 #include <cmsys/Glob.hxx>
1325 #include <cmsys/String.h>
1326 #include <cmsys/auto_ptr.hxx>
1328 class cmFileList;
1329 class cmFileListGeneratorBase
1331 public:
1332 virtual ~cmFileListGeneratorBase() {}
1333 protected:
1334 bool Consider(std::string const& fullPath, cmFileList& listing);
1335 private:
1336 bool Search(cmFileList&);
1337 virtual bool Search(std::string const& parent, cmFileList&) = 0;
1338 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const = 0;
1339 friend class cmFileList;
1340 cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next);
1341 cmsys::auto_ptr<cmFileListGeneratorBase> Next;
1344 class cmFileList
1346 public:
1347 cmFileList(): First(), Last(0) {}
1348 virtual ~cmFileList() {}
1349 cmFileList& operator/(cmFileListGeneratorBase const& rhs)
1351 if(this->Last)
1353 this->Last = this->Last->SetNext(rhs);
1355 else
1357 this->First = rhs.Clone();
1358 this->Last = this->First.get();
1360 return *this;
1362 bool Search()
1364 if(this->First.get())
1366 return this->First->Search(*this);
1368 return false;
1370 private:
1371 virtual bool Visit(std::string const& fullPath) = 0;
1372 friend class cmFileListGeneratorBase;
1373 cmsys::auto_ptr<cmFileListGeneratorBase> First;
1374 cmFileListGeneratorBase* Last;
1377 class cmFindPackageFileList: public cmFileList
1379 public:
1380 cmFindPackageFileList(cmFindPackageCommand* fpc,
1381 bool use_suffixes = true):
1382 cmFileList(), FPC(fpc), UseSuffixes(use_suffixes) {}
1383 private:
1384 bool Visit(std::string const& fullPath)
1386 if(this->UseSuffixes)
1388 return this->FPC->SearchDirectory(fullPath);
1390 else
1392 return this->FPC->CheckDirectory(fullPath);
1395 cmFindPackageCommand* FPC;
1396 bool UseSuffixes;
1399 bool cmFileListGeneratorBase::Search(cmFileList& listing)
1401 return this->Search("", listing);
1404 cmFileListGeneratorBase*
1405 cmFileListGeneratorBase::SetNext(cmFileListGeneratorBase const& next)
1407 this->Next = next.Clone();
1408 return this->Next.get();
1411 bool cmFileListGeneratorBase::Consider(std::string const& fullPath,
1412 cmFileList& listing)
1414 if(this->Next.get())
1416 return this->Next->Search(fullPath + "/", listing);
1418 else
1420 return listing.Visit(fullPath + "/");
1424 class cmFileListGeneratorFixed: public cmFileListGeneratorBase
1426 public:
1427 cmFileListGeneratorFixed(std::string const& str):
1428 cmFileListGeneratorBase(), String(str) {}
1429 cmFileListGeneratorFixed(cmFileListGeneratorFixed const& r):
1430 cmFileListGeneratorBase(), String(r.String) {}
1431 private:
1432 std::string String;
1433 virtual bool Search(std::string const& parent, cmFileList& lister)
1435 std::string fullPath = parent + this->String;
1436 return this->Consider(fullPath, lister);
1438 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1440 cmsys::auto_ptr<cmFileListGeneratorBase>
1441 g(new cmFileListGeneratorFixed(*this));
1442 return g;
1446 class cmFileListGeneratorEnumerate: public cmFileListGeneratorBase
1448 public:
1449 cmFileListGeneratorEnumerate(std::vector<std::string> const& v):
1450 cmFileListGeneratorBase(), Vector(v) {}
1451 cmFileListGeneratorEnumerate(cmFileListGeneratorEnumerate const& r):
1452 cmFileListGeneratorBase(), Vector(r.Vector) {}
1453 private:
1454 std::vector<std::string> const& Vector;
1455 virtual bool Search(std::string const& parent, cmFileList& lister)
1457 for(std::vector<std::string>::const_iterator i = this->Vector.begin();
1458 i != this->Vector.end(); ++i)
1460 if(this->Consider(parent + *i, lister))
1462 return true;
1465 return false;
1467 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1469 cmsys::auto_ptr<cmFileListGeneratorBase>
1470 g(new cmFileListGeneratorEnumerate(*this));
1471 return g;
1475 class cmFileListGeneratorProject: public cmFileListGeneratorBase
1477 public:
1478 cmFileListGeneratorProject(std::vector<std::string> const& names):
1479 cmFileListGeneratorBase(), Names(names) {}
1480 cmFileListGeneratorProject(cmFileListGeneratorProject const& r):
1481 cmFileListGeneratorBase(), Names(r.Names) {}
1482 private:
1483 std::vector<std::string> const& Names;
1484 virtual bool Search(std::string const& parent, cmFileList& lister)
1486 // Construct a list of matches.
1487 std::vector<std::string> matches;
1488 cmsys::Directory d;
1489 d.Load(parent.c_str());
1490 for(unsigned long i=0; i < d.GetNumberOfFiles(); ++i)
1492 const char* fname = d.GetFile(i);
1493 if(strcmp(fname, ".") == 0 ||
1494 strcmp(fname, "..") == 0)
1496 continue;
1498 for(std::vector<std::string>::const_iterator ni = this->Names.begin();
1499 ni != this->Names.end(); ++ni)
1501 if(cmsysString_strncasecmp(fname, ni->c_str(),
1502 ni->length()) == 0)
1504 matches.push_back(fname);
1509 for(std::vector<std::string>::const_iterator i = matches.begin();
1510 i != matches.end(); ++i)
1512 if(this->Consider(parent + *i, lister))
1514 return true;
1517 return false;
1519 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1521 cmsys::auto_ptr<cmFileListGeneratorBase>
1522 g(new cmFileListGeneratorProject(*this));
1523 return g;
1527 class cmFileListGeneratorMacProject: public cmFileListGeneratorBase
1529 public:
1530 cmFileListGeneratorMacProject(std::vector<std::string> const& names,
1531 const char* ext):
1532 cmFileListGeneratorBase(), Names(names), Extension(ext) {}
1533 cmFileListGeneratorMacProject(cmFileListGeneratorMacProject const& r):
1534 cmFileListGeneratorBase(), Names(r.Names), Extension(r.Extension) {}
1535 private:
1536 std::vector<std::string> const& Names;
1537 std::string Extension;
1538 virtual bool Search(std::string const& parent, cmFileList& lister)
1540 // Construct a list of matches.
1541 std::vector<std::string> matches;
1542 cmsys::Directory d;
1543 d.Load(parent.c_str());
1544 for(unsigned long i=0; i < d.GetNumberOfFiles(); ++i)
1546 const char* fname = d.GetFile(i);
1547 if(strcmp(fname, ".") == 0 ||
1548 strcmp(fname, "..") == 0)
1550 continue;
1552 for(std::vector<std::string>::const_iterator ni = this->Names.begin();
1553 ni != this->Names.end(); ++ni)
1555 std::string name = *ni;
1556 name += this->Extension;
1557 if(cmsysString_strcasecmp(fname, name.c_str()) == 0)
1559 matches.push_back(fname);
1564 for(std::vector<std::string>::const_iterator i = matches.begin();
1565 i != matches.end(); ++i)
1567 if(this->Consider(parent + *i, lister))
1569 return true;
1572 return false;
1574 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1576 cmsys::auto_ptr<cmFileListGeneratorBase>
1577 g(new cmFileListGeneratorMacProject(*this));
1578 return g;
1582 class cmFileListGeneratorCaseInsensitive: public cmFileListGeneratorBase
1584 public:
1585 cmFileListGeneratorCaseInsensitive(std::string const& str):
1586 cmFileListGeneratorBase(), String(str) {}
1587 cmFileListGeneratorCaseInsensitive(
1588 cmFileListGeneratorCaseInsensitive const& r):
1589 cmFileListGeneratorBase(), String(r.String) {}
1590 private:
1591 std::string String;
1592 virtual bool Search(std::string const& parent, cmFileList& lister)
1594 // Look for matching files.
1595 std::vector<std::string> matches;
1596 cmsys::Directory d;
1597 d.Load(parent.c_str());
1598 for(unsigned long i=0; i < d.GetNumberOfFiles(); ++i)
1600 const char* fname = d.GetFile(i);
1601 if(strcmp(fname, ".") == 0 ||
1602 strcmp(fname, "..") == 0)
1604 continue;
1606 if(cmsysString_strcasecmp(fname, this->String.c_str()) == 0)
1608 if(this->Consider(parent + fname, lister))
1610 return true;
1614 return false;
1616 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1618 cmsys::auto_ptr<cmFileListGeneratorBase>
1619 g(new cmFileListGeneratorCaseInsensitive(*this));
1620 return g;
1624 class cmFileListGeneratorGlob: public cmFileListGeneratorBase
1626 public:
1627 cmFileListGeneratorGlob(std::string const& str):
1628 cmFileListGeneratorBase(), Pattern(str) {}
1629 cmFileListGeneratorGlob(cmFileListGeneratorGlob const& r):
1630 cmFileListGeneratorBase(), Pattern(r.Pattern) {}
1631 private:
1632 std::string Pattern;
1633 virtual bool Search(std::string const& parent, cmFileList& lister)
1635 // Glob the set of matching files.
1636 std::string expr = parent;
1637 expr += this->Pattern;
1638 cmsys::Glob g;
1639 if(!g.FindFiles(expr))
1641 return false;
1643 std::vector<std::string> const& files = g.GetFiles();
1645 // Look for directories among the matches.
1646 for(std::vector<std::string>::const_iterator fi = files.begin();
1647 fi != files.end(); ++fi)
1649 if(cmSystemTools::FileIsDirectory(fi->c_str()))
1651 if(this->Consider(*fi, lister))
1653 return true;
1657 return false;
1659 virtual cmsys::auto_ptr<cmFileListGeneratorBase> Clone() const
1661 cmsys::auto_ptr<cmFileListGeneratorBase>
1662 g(new cmFileListGeneratorGlob(*this));
1663 return g;
1667 //----------------------------------------------------------------------------
1668 bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
1670 assert(!prefix_in.empty() && prefix_in[prefix_in.size()-1] == '/');
1671 if(this->DebugMode)
1673 fprintf(stderr, "Checking prefix [%s]\n", prefix_in.c_str());
1676 // Skip this if the prefix does not exist.
1677 if(!cmSystemTools::FileIsDirectory(prefix_in.c_str()))
1679 return false;
1682 // PREFIX/ (useful on windows or in build trees)
1683 if(this->SearchDirectory(prefix_in))
1685 return true;
1688 // Strip the trailing slash because the path generator is about to
1689 // add one.
1690 std::string prefix = prefix_in.substr(0, prefix_in.size()-1);
1692 // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
1694 cmFindPackageFileList lister(this);
1695 lister
1696 / cmFileListGeneratorFixed(prefix)
1697 / cmFileListGeneratorCaseInsensitive("cmake");
1698 if(lister.Search())
1700 return true;
1704 // Construct list of common install locations (lib and share).
1705 std::vector<std::string> common;
1706 if(this->UseLib64Paths)
1708 common.push_back("lib64");
1710 common.push_back("lib");
1711 common.push_back("share");
1713 // PREFIX/(share|lib)/(Foo|foo|FOO).*/
1715 cmFindPackageFileList lister(this);
1716 lister
1717 / cmFileListGeneratorFixed(prefix)
1718 / cmFileListGeneratorEnumerate(common)
1719 / cmFileListGeneratorProject(this->Names);
1720 if(lister.Search())
1722 return true;
1726 // PREFIX/(share|lib)/(Foo|foo|FOO).*/(cmake|CMake)/
1728 cmFindPackageFileList lister(this);
1729 lister
1730 / cmFileListGeneratorFixed(prefix)
1731 / cmFileListGeneratorEnumerate(common)
1732 / cmFileListGeneratorProject(this->Names)
1733 / cmFileListGeneratorCaseInsensitive("cmake");
1734 if(lister.Search())
1736 return true;
1740 return false;
1743 //----------------------------------------------------------------------------
1744 bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
1746 assert(!prefix_in.empty() && prefix_in[prefix_in.size()-1] == '/');
1747 if(this->DebugMode)
1749 fprintf(stderr, "Checking framework prefix [%s]\n", prefix_in.c_str());
1752 // Strip the trailing slash because the path generator is about to
1753 // add one.
1754 std::string prefix = prefix_in.substr(0, prefix_in.size()-1);
1756 // <prefix>/Foo.framework/Resources/
1758 cmFindPackageFileList lister(this);
1759 lister
1760 / cmFileListGeneratorFixed(prefix)
1761 / cmFileListGeneratorMacProject(this->Names, ".framework")
1762 / cmFileListGeneratorFixed("Resources");
1763 if(lister.Search())
1765 return true;
1768 // <prefix>/Foo.framework/Resources/CMake/
1770 cmFindPackageFileList lister(this);
1771 lister
1772 / cmFileListGeneratorFixed(prefix)
1773 / cmFileListGeneratorMacProject(this->Names, ".framework")
1774 / cmFileListGeneratorFixed("Resources")
1775 / cmFileListGeneratorCaseInsensitive("cmake");
1776 if(lister.Search())
1778 return true;
1782 // <prefix>/Foo.framework/Versions/*/Resources/
1784 cmFindPackageFileList lister(this);
1785 lister
1786 / cmFileListGeneratorFixed(prefix)
1787 / cmFileListGeneratorMacProject(this->Names, ".framework")
1788 / cmFileListGeneratorFixed("Versions")
1789 / cmFileListGeneratorGlob("*/Resources");
1790 if(lister.Search())
1792 return true;
1796 // <prefix>/Foo.framework/Versions/*/Resources/CMake/
1798 cmFindPackageFileList lister(this);
1799 lister
1800 / cmFileListGeneratorFixed(prefix)
1801 / cmFileListGeneratorMacProject(this->Names, ".framework")
1802 / cmFileListGeneratorFixed("Versions")
1803 / cmFileListGeneratorGlob("*/Resources")
1804 / cmFileListGeneratorCaseInsensitive("cmake");
1805 if(lister.Search())
1807 return true;
1811 return false;
1814 //----------------------------------------------------------------------------
1815 bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
1817 assert(!prefix_in.empty() && prefix_in[prefix_in.size()-1] == '/');
1818 if(this->DebugMode)
1820 fprintf(stderr, "Checking bundle prefix [%s]\n", prefix_in.c_str());
1823 // Strip the trailing slash because the path generator is about to
1824 // add one.
1825 std::string prefix = prefix_in.substr(0, prefix_in.size()-1);
1827 // <prefix>/Foo.app/Contents/Resources
1829 cmFindPackageFileList lister(this);
1830 lister
1831 / cmFileListGeneratorFixed(prefix)
1832 / cmFileListGeneratorMacProject(this->Names, ".app")
1833 / cmFileListGeneratorFixed("Contents/Resources");
1834 if(lister.Search())
1836 return true;
1840 // <prefix>/Foo.app/Contents/Resources/CMake
1842 cmFindPackageFileList lister(this);
1843 lister
1844 / cmFileListGeneratorFixed(prefix)
1845 / cmFileListGeneratorMacProject(this->Names, ".app")
1846 / cmFileListGeneratorFixed("Contents/Resources")
1847 / cmFileListGeneratorCaseInsensitive("cmake");
1848 if(lister.Search())
1850 return true;
1854 return false;
1857 // TODO: Version numbers? Perhaps have a listing component class that
1858 // sorts by lexicographic and numerical ordering. Also try to match
1859 // some command argument for the version. Alternatively provide an
1860 // API that just returns a list of valid directories? Perhaps push a
1861 // scope and try loading the target file just to get its version
1862 // number? Could add a foo-version.cmake or FooVersion.cmake file
1863 // in the projects that contains just version information.
1865 // TODO: Debug cmsys::Glob double slash problem.
1867 // TODO: Add registry entries after cmake system search path?
1868 // Currently the user must specify them with the PATHS option.
1870 // [HKEY_CURRENT_USER\Software\*\Foo*;InstallDir]
1871 // [HKEY_CURRENT_USER\Software\*\*\Foo*;InstallDir]
1872 // [HKEY_LOCAL_MACHINE\Software\*\Foo*;InstallDir]
1873 // [HKEY_LOCAL_MACHINE\Software\*\*\Foo*;InstallDir]