Imported Upstream version 2.8.12.2
[platform/upstream/cmake.git] / Source / cmCacheManager.cxx
1 /*============================================================================
2   CMake - Cross Platform Makefile Generator
3   Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
4
5   Distributed under the OSI-approved BSD License (the "License");
6   see accompanying file Copyright.txt for details.
7
8   This software is distributed WITHOUT ANY WARRANTY; without even the
9   implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10   See the License for more information.
11 ============================================================================*/
12
13 #include "cmCacheManager.h"
14 #include "cmSystemTools.h"
15 #include "cmCacheManager.h"
16 #include "cmGeneratedFileStream.h"
17 #include "cmMakefile.h"
18 #include "cmake.h"
19 #include "cmVersion.h"
20
21 #include <cmsys/Directory.hxx>
22 #include <cmsys/Glob.hxx>
23
24 #include <cmsys/RegularExpression.hxx>
25
26 const char* cmCacheManagerTypes[] =
27 { "BOOL",
28   "PATH",
29   "FILEPATH",
30   "STRING",
31   "INTERNAL",
32   "STATIC",
33   "UNINITIALIZED",
34   0
35 };
36
37 cmCacheManager::cmCacheManager(cmake* cm)
38 {
39   this->CacheMajorVersion = 0;
40   this->CacheMinorVersion = 0;
41   this->CMakeInstance = cm;
42 }
43
44 const char* cmCacheManager::TypeToString(cmCacheManager::CacheEntryType type)
45 {
46   if ( type > 6 )
47     {
48     return cmCacheManagerTypes[6];
49     }
50   return cmCacheManagerTypes[type];
51 }
52
53 cmCacheManager::CacheEntryType cmCacheManager::StringToType(const char* s)
54 {
55   int i = 0;
56   while(cmCacheManagerTypes[i])
57     {
58     if(strcmp(s, cmCacheManagerTypes[i]) == 0)
59       {
60       return static_cast<CacheEntryType>(i);
61       }
62     ++i;
63     }
64   return STRING;
65 }
66
67 bool cmCacheManager::IsType(const char* s)
68 {
69   for(int i=0; cmCacheManagerTypes[i]; ++i)
70     {
71     if(strcmp(s, cmCacheManagerTypes[i]) == 0)
72       {
73       return true;
74       }
75     }
76   return false;
77 }
78
79 bool cmCacheManager::LoadCache(cmMakefile* mf)
80 {
81   return this->LoadCache(mf->GetHomeOutputDirectory());
82 }
83
84
85 bool cmCacheManager::LoadCache(const char* path)
86 {
87   return this->LoadCache(path,true);
88 }
89
90 bool cmCacheManager::LoadCache(const char* path,
91                                bool internal)
92 {
93   std::set<cmStdString> emptySet;
94   return this->LoadCache(path, internal, emptySet, emptySet);
95 }
96
97 static bool ParseEntryWithoutType(const char* entry,
98                                   std::string& var,
99                                   std::string& value)
100 {
101   // input line is:         key=value
102   static cmsys::RegularExpression reg(
103     "^([^=]*)=(.*[^\r\t ]|[\r\t ]*)[\r\t ]*$");
104   // input line is:         "key"=value
105   static cmsys::RegularExpression regQuoted(
106     "^\"([^\"]*)\"=(.*[^\r\t ]|[\r\t ]*)[\r\t ]*$");
107   bool flag = false;
108   if(regQuoted.find(entry))
109     {
110     var = regQuoted.match(1);
111     value = regQuoted.match(2);
112     flag = true;
113     }
114   else if (reg.find(entry))
115     {
116     var = reg.match(1);
117     value = reg.match(2);
118     flag = true;
119     }
120
121   // if value is enclosed in single quotes ('foo') then remove them
122   // it is used to enclose trailing space or tab
123   if (flag &&
124       value.size() >= 2 &&
125       value[0] == '\'' &&
126       value[value.size() - 1] == '\'')
127     {
128     value = value.substr(1,
129                          value.size() - 2);
130     }
131
132   return flag;
133 }
134
135 bool cmCacheManager::ParseEntry(const char* entry,
136                                 std::string& var,
137                                 std::string& value,
138                                 CacheEntryType& type)
139 {
140   // input line is:         key:type=value
141   static cmsys::RegularExpression reg(
142     "^([^:]*):([^=]*)=(.*[^\r\t ]|[\r\t ]*)[\r\t ]*$");
143   // input line is:         "key":type=value
144   static cmsys::RegularExpression regQuoted(
145     "^\"([^\"]*)\":([^=]*)=(.*[^\r\t ]|[\r\t ]*)[\r\t ]*$");
146   bool flag = false;
147   if(regQuoted.find(entry))
148     {
149     var = regQuoted.match(1);
150     type = cmCacheManager::StringToType(regQuoted.match(2).c_str());
151     value = regQuoted.match(3);
152     flag = true;
153     }
154   else if (reg.find(entry))
155     {
156     var = reg.match(1);
157     type = cmCacheManager::StringToType(reg.match(2).c_str());
158     value = reg.match(3);
159     flag = true;
160     }
161
162   // if value is enclosed in single quotes ('foo') then remove them
163   // it is used to enclose trailing space or tab
164   if (flag &&
165       value.size() >= 2 &&
166       value[0] == '\'' &&
167       value[value.size() - 1] == '\'')
168     {
169     value = value.substr(1,
170                          value.size() - 2);
171     }
172
173   if (!flag)
174     {
175     return ParseEntryWithoutType(entry, var, value);
176     }
177
178   return flag;
179 }
180
181 void cmCacheManager::CleanCMakeFiles(const char* path)
182 {
183   std::string glob = path;
184   glob += cmake::GetCMakeFilesDirectory();
185   glob += "/*.cmake";
186   cmsys::Glob globIt;
187   globIt.FindFiles(glob);
188   std::vector<std::string> files = globIt.GetFiles();
189   for(std::vector<std::string>::iterator i = files.begin();
190       i != files.end(); ++i)
191     {
192     cmSystemTools::RemoveFile(i->c_str());
193     }
194 }
195
196 bool cmCacheManager::LoadCache(const char* path,
197                                bool internal,
198                                std::set<cmStdString>& excludes,
199                                std::set<cmStdString>& includes)
200 {
201   std::string cacheFile = path;
202   cacheFile += "/CMakeCache.txt";
203   // clear the old cache, if we are reading in internal values
204   if ( internal )
205     {
206     this->Cache.clear();
207     }
208   if(!cmSystemTools::FileExists(cacheFile.c_str()))
209     {
210     this->CleanCMakeFiles(path);
211     return false;
212     }
213
214   std::ifstream fin(cacheFile.c_str());
215   if(!fin)
216     {
217     return false;
218     }
219   const char *realbuffer;
220   std::string buffer;
221   std::string entryKey;
222   while(fin)
223     {
224     // Format is key:type=value
225     std::string helpString;
226     CacheEntry e;
227     e.Properties.SetCMakeInstance(this->CMakeInstance);
228     cmSystemTools::GetLineFromStream(fin, buffer);
229     realbuffer = buffer.c_str();
230     while(*realbuffer != '0' &&
231           (*realbuffer == ' ' ||
232            *realbuffer == '\t' ||
233            *realbuffer == '\r' ||
234            *realbuffer == '\n'))
235       {
236       realbuffer++;
237       }
238     // skip blank lines and comment lines
239     if(realbuffer[0] == '#' || realbuffer[0] == 0)
240       {
241       continue;
242       }
243     while(realbuffer[0] == '/' && realbuffer[1] == '/')
244       {
245       if ((realbuffer[2] == '\\') && (realbuffer[3]=='n'))
246         {
247         helpString += "\n";
248         helpString += &realbuffer[4];
249         }
250       else
251         {
252         helpString += &realbuffer[2];
253         }
254       cmSystemTools::GetLineFromStream(fin, buffer);
255       realbuffer = buffer.c_str();
256       if(!fin)
257         {
258         continue;
259         }
260       }
261     e.SetProperty("HELPSTRING", helpString.c_str());
262     if(cmCacheManager::ParseEntry(realbuffer, entryKey, e.Value, e.Type))
263       {
264       if ( excludes.find(entryKey) == excludes.end() )
265         {
266         // Load internal values if internal is set.
267         // If the entry is not internal to the cache being loaded
268         // or if it is in the list of internal entries to be
269         // imported, load it.
270         if ( internal || (e.Type != INTERNAL) ||
271              (includes.find(entryKey) != includes.end()) )
272           {
273           // If we are loading the cache from another project,
274           // make all loaded entries internal so that it is
275           // not visible in the gui
276           if (!internal)
277             {
278             e.Type = INTERNAL;
279             helpString = "DO NOT EDIT, ";
280             helpString += entryKey;
281             helpString += " loaded from external file.  "
282               "To change this value edit this file: ";
283             helpString += path;
284             helpString += "/CMakeCache.txt"   ;
285             e.SetProperty("HELPSTRING", helpString.c_str());
286             }
287           if(!this->ReadPropertyEntry(entryKey, e))
288             {
289             e.Initialized = true;
290             this->Cache[entryKey] = e;
291             }
292           }
293         }
294       }
295     else
296       {
297       cmSystemTools::Error("Parse error in cache file ", cacheFile.c_str(),
298                            ". Offending entry: ", realbuffer);
299       }
300     }
301   this->CacheMajorVersion = 0;
302   this->CacheMinorVersion = 0;
303   if(const char* cmajor = this->GetCacheValue("CMAKE_CACHE_MAJOR_VERSION"))
304     {
305     unsigned int v=0;
306     if(sscanf(cmajor, "%u", &v) == 1)
307       {
308       this->CacheMajorVersion = v;
309       }
310     if(const char* cminor = this->GetCacheValue("CMAKE_CACHE_MINOR_VERSION"))
311       {
312       if(sscanf(cminor, "%u", &v) == 1)
313         {
314         this->CacheMinorVersion = v;
315         }
316       }
317     }
318   else
319     {
320     // CMake version not found in the list file.
321     // Set as version 0.0
322     this->AddCacheEntry("CMAKE_CACHE_MINOR_VERSION", "0",
323                         "Minor version of cmake used to create the "
324                         "current loaded cache", cmCacheManager::INTERNAL);
325     this->AddCacheEntry("CMAKE_CACHE_MAJOR_VERSION", "0",
326                         "Major version of cmake used to create the "
327                         "current loaded cache", cmCacheManager::INTERNAL);
328
329     }
330   // check to make sure the cache directory has not
331   // been moved
332   if ( internal && this->GetCacheValue("CMAKE_CACHEFILE_DIR") )
333     {
334     std::string currentcwd = path;
335     std::string oldcwd = this->GetCacheValue("CMAKE_CACHEFILE_DIR");
336     cmSystemTools::ConvertToUnixSlashes(currentcwd);
337     currentcwd += "/CMakeCache.txt";
338     oldcwd += "/CMakeCache.txt";
339     if(!cmSystemTools::SameFile(oldcwd.c_str(), currentcwd.c_str()))
340       {
341       std::string message =
342         std::string("The current CMakeCache.txt directory ") +
343         currentcwd + std::string(" is different than the directory ") +
344         std::string(this->GetCacheValue("CMAKE_CACHEFILE_DIR")) +
345         std::string(" where CMakeCache.txt was created. This may result "
346                     "in binaries being created in the wrong place. If you "
347                     "are not sure, reedit the CMakeCache.txt");
348       cmSystemTools::Error(message.c_str());
349       }
350     }
351   return true;
352 }
353
354 //----------------------------------------------------------------------------
355 const char* cmCacheManager::PersistentProperties[] =
356 {
357   "ADVANCED",
358   "MODIFIED",
359   "STRINGS",
360   0
361 };
362
363 //----------------------------------------------------------------------------
364 bool cmCacheManager::ReadPropertyEntry(std::string const& entryKey,
365                                        CacheEntry& e)
366 {
367   // All property entries are internal.
368   if(e.Type != cmCacheManager::INTERNAL)
369     {
370     return false;
371     }
372
373   const char* end = entryKey.c_str() + entryKey.size();
374   for(const char** p = this->PersistentProperties; *p; ++p)
375     {
376     std::string::size_type plen = strlen(*p) + 1;
377     if(entryKey.size() > plen && *(end-plen) == '-' &&
378        strcmp(end-plen+1, *p) == 0)
379       {
380       std::string key = entryKey.substr(0, entryKey.size() - plen);
381       cmCacheManager::CacheIterator it = this->GetCacheIterator(key.c_str());
382       if(it.IsAtEnd())
383         {
384         // Create an entry and store the property.
385         CacheEntry& ne = this->Cache[key];
386         ne.Properties.SetCMakeInstance(this->CMakeInstance);
387         ne.Type = cmCacheManager::UNINITIALIZED;
388         ne.SetProperty(*p, e.Value.c_str());
389         }
390       else
391         {
392         // Store this property on its entry.
393         it.SetProperty(*p, e.Value.c_str());
394         }
395       return true;
396       }
397     }
398   return false;
399 }
400
401 //----------------------------------------------------------------------------
402 void cmCacheManager::WritePropertyEntries(std::ostream& os,
403                                           CacheIterator const& i)
404 {
405   for(const char** p = this->PersistentProperties; *p; ++p)
406     {
407     if(const char* value = i.GetProperty(*p))
408       {
409       std::string helpstring = *p;
410       helpstring += " property for variable: ";
411       helpstring += i.GetName();
412       cmCacheManager::OutputHelpString(os, helpstring);
413
414       std::string key = i.GetName();
415       key += "-";
416       key += *p;
417       this->OutputKey(os, key);
418       os << ":INTERNAL=";
419       this->OutputValue(os, value);
420       os << "\n";
421       }
422     }
423 }
424
425 bool cmCacheManager::SaveCache(cmMakefile* mf)
426 {
427   return this->SaveCache(mf->GetHomeOutputDirectory());
428 }
429
430
431 bool cmCacheManager::SaveCache(const char* path)
432 {
433   std::string cacheFile = path;
434   cacheFile += "/CMakeCache.txt";
435   cmGeneratedFileStream fout(cacheFile.c_str());
436   fout.SetCopyIfDifferent(true);
437   if(!fout)
438     {
439     cmSystemTools::Error("Unable to open cache file for save. ",
440                          cacheFile.c_str());
441     cmSystemTools::ReportLastSystemError("");
442     return false;
443     }
444   // before writing the cache, update the version numbers
445   // to the
446   char temp[1024];
447   sprintf(temp, "%d", cmVersion::GetMinorVersion());
448   this->AddCacheEntry("CMAKE_CACHE_MINOR_VERSION", temp,
449                       "Minor version of cmake used to create the "
450                       "current loaded cache", cmCacheManager::INTERNAL);
451   sprintf(temp, "%d", cmVersion::GetMajorVersion());
452   this->AddCacheEntry("CMAKE_CACHE_MAJOR_VERSION", temp,
453                       "Major version of cmake used to create the "
454                       "current loaded cache", cmCacheManager::INTERNAL);
455   sprintf(temp, "%d", cmVersion::GetPatchVersion());
456   this->AddCacheEntry("CMAKE_CACHE_PATCH_VERSION", temp,
457                       "Patch version of cmake used to create the "
458                       "current loaded cache", cmCacheManager::INTERNAL);
459
460   // Let us store the current working directory so that if somebody
461   // Copies it, he will not be surprised
462   std::string currentcwd = path;
463   if ( currentcwd[0] >= 'A' && currentcwd[0] <= 'Z' &&
464        currentcwd[1] == ':' )
465     {
466     // Cast added to avoid compiler warning. Cast is ok because
467     // value is guaranteed to fit in char by the above if...
468     currentcwd[0] = static_cast<char>(currentcwd[0] - 'A' + 'a');
469     }
470   cmSystemTools::ConvertToUnixSlashes(currentcwd);
471   this->AddCacheEntry("CMAKE_CACHEFILE_DIR", currentcwd.c_str(),
472                       "This is the directory where this CMakeCache.txt"
473                       " was created", cmCacheManager::INTERNAL);
474
475   fout << "# This is the CMakeCache file.\n"
476        << "# For build in directory: " << currentcwd << "\n";
477   cmCacheManager::CacheEntry* cmakeCacheEntry
478     = this->GetCacheEntry("CMAKE_COMMAND");
479   if ( cmakeCacheEntry )
480     {
481     fout << "# It was generated by CMake: " <<
482       cmakeCacheEntry->Value << std::endl;
483     }
484
485   fout << "# You can edit this file to change values found and used by cmake."
486        << std::endl
487        << "# If you do not want to change any of the values, simply exit the "
488        "editor." << std::endl
489        << "# If you do want to change a value, simply edit, save, and exit "
490        "the editor." << std::endl
491        << "# The syntax for the file is as follows:\n"
492        << "# KEY:TYPE=VALUE\n"
493        << "# KEY is the name of a variable in the cache.\n"
494        << "# TYPE is a hint to GUIs for the type of VALUE, DO NOT EDIT "
495        "TYPE!." << std::endl
496        << "# VALUE is the current value for the KEY.\n\n";
497
498   fout << "########################\n";
499   fout << "# EXTERNAL cache entries\n";
500   fout << "########################\n";
501   fout << "\n";
502
503   for( std::map<cmStdString, CacheEntry>::const_iterator i =
504          this->Cache.begin(); i != this->Cache.end(); ++i)
505     {
506     const CacheEntry& ce = (*i).second;
507     CacheEntryType t = ce.Type;
508     if(!ce.Initialized)
509       {
510       /*
511         // This should be added in, but is not for now.
512       cmSystemTools::Error("Cache entry \"", (*i).first.c_str(),
513                            "\" is uninitialized");
514       */
515       }
516     else if(t != INTERNAL)
517       {
518       // Format is key:type=value
519       if(const char* help = ce.GetProperty("HELPSTRING"))
520         {
521         cmCacheManager::OutputHelpString(fout, help);
522         }
523       else
524         {
525         cmCacheManager::OutputHelpString(fout, "Missing description");
526         }
527       this->OutputKey(fout, i->first);
528       fout << ":" << cmCacheManagerTypes[t] << "=";
529       this->OutputValue(fout, ce.Value);
530       fout << "\n\n";
531       }
532     }
533
534   fout << "\n";
535   fout << "########################\n";
536   fout << "# INTERNAL cache entries\n";
537   fout << "########################\n";
538   fout << "\n";
539
540   for( cmCacheManager::CacheIterator i = this->NewIterator();
541        !i.IsAtEnd(); i.Next())
542     {
543     if ( !i.Initialized() )
544       {
545       continue;
546       }
547
548     CacheEntryType t = i.GetType();
549     this->WritePropertyEntries(fout, i);
550     if(t == cmCacheManager::INTERNAL)
551       {
552       // Format is key:type=value
553       if(const char* help = i.GetProperty("HELPSTRING"))
554         {
555         this->OutputHelpString(fout, help);
556         }
557       this->OutputKey(fout, i.GetName());
558       fout << ":" << cmCacheManagerTypes[t] << "=";
559       this->OutputValue(fout, i.GetValue());
560       fout << "\n";
561       }
562     }
563   fout << "\n";
564   fout.Close();
565   std::string checkCacheFile = path;
566   checkCacheFile += cmake::GetCMakeFilesDirectory();
567   cmSystemTools::MakeDirectory(checkCacheFile.c_str());
568   checkCacheFile += "/cmake.check_cache";
569   std::ofstream checkCache(checkCacheFile.c_str());
570   if(!checkCache)
571     {
572     cmSystemTools::Error("Unable to open check cache file for write. ",
573                          checkCacheFile.c_str());
574     return false;
575     }
576   checkCache << "# This file is generated by cmake for dependency checking "
577     "of the CMakeCache.txt file\n";
578   return true;
579 }
580
581 bool cmCacheManager::DeleteCache(const char* path)
582 {
583   std::string cacheFile = path;
584   cmSystemTools::ConvertToUnixSlashes(cacheFile);
585   std::string cmakeFiles = cacheFile;
586   cacheFile += "/CMakeCache.txt";
587   if(cmSystemTools::FileExists(cacheFile.c_str()))
588     {
589     cmSystemTools::RemoveFile(cacheFile.c_str());
590     // now remove the files in the CMakeFiles directory
591     // this cleans up language cache files
592     cmakeFiles += cmake::GetCMakeFilesDirectory();
593     if(cmSystemTools::FileIsDirectory(cmakeFiles.c_str()))
594       {
595       cmSystemTools::RemoveADirectory(cmakeFiles.c_str());
596       }
597     }
598   return true;
599 }
600
601 void cmCacheManager::OutputKey(std::ostream& fout, std::string const& key)
602 {
603   // support : in key name by double quoting
604   const char* q = (key.find(':') != key.npos ||
605                    key.find("//") == 0)? "\"" : "";
606   fout << q << key << q;
607 }
608
609 void cmCacheManager::OutputValue(std::ostream& fout, std::string const& value)
610 {
611   // if value has trailing space or tab, enclose it in single quotes
612   if (value.size() &&
613       (value[value.size() - 1] == ' ' ||
614        value[value.size() - 1] == '\t'))
615     {
616     fout << '\'' << value << '\'';
617     }
618   else
619     {
620     fout << value;
621     }
622 }
623
624 void cmCacheManager::OutputHelpString(std::ostream& fout,
625                                       const std::string& helpString)
626 {
627   std::string::size_type end = helpString.size();
628   if(end == 0)
629     {
630     return;
631     }
632   std::string oneLine;
633   std::string::size_type pos = 0;
634   for (std::string::size_type i=0; i<=end; i++)
635     {
636     if ((i==end)
637         || (helpString[i]=='\n')
638         || ((i-pos >= 60) && (helpString[i]==' ')))
639       {
640       fout << "//";
641       if (helpString[pos] == '\n')
642         {
643         pos++;
644         fout << "\\n";
645         }
646       oneLine = helpString.substr(pos, i - pos);
647       fout << oneLine.c_str() << "\n";
648       pos = i;
649       }
650     }
651 }
652
653 void cmCacheManager::RemoveCacheEntry(const char* key)
654 {
655   CacheEntryMap::iterator i = this->Cache.find(key);
656   if(i != this->Cache.end())
657     {
658     this->Cache.erase(i);
659     }
660 }
661
662
663 cmCacheManager::CacheEntry *cmCacheManager::GetCacheEntry(const char* key)
664 {
665   CacheEntryMap::iterator i = this->Cache.find(key);
666   if(i != this->Cache.end())
667     {
668     return &i->second;
669     }
670   return 0;
671 }
672
673 cmCacheManager::CacheIterator cmCacheManager::GetCacheIterator(
674   const char *key)
675 {
676   return CacheIterator(*this, key);
677 }
678
679 const char* cmCacheManager::GetCacheValue(const char* key) const
680 {
681   CacheEntryMap::const_iterator i = this->Cache.find(key);
682   if(i != this->Cache.end() &&
683     i->second.Initialized)
684     {
685     return i->second.Value.c_str();
686     }
687   return 0;
688 }
689
690
691 void cmCacheManager::PrintCache(std::ostream& out) const
692 {
693   out << "=================================================" << std::endl;
694   out << "CMakeCache Contents:" << std::endl;
695   for(std::map<cmStdString, CacheEntry>::const_iterator i =
696         this->Cache.begin(); i != this->Cache.end(); ++i)
697     {
698     if((*i).second.Type != INTERNAL)
699       {
700       out << (*i).first.c_str() << " = " << (*i).second.Value.c_str()
701           << std::endl;
702       }
703     }
704   out << "\n\n";
705   out << "To change values in the CMakeCache, "
706     << std::endl << "edit CMakeCache.txt in your output directory.\n";
707   out << "=================================================" << std::endl;
708 }
709
710
711 void cmCacheManager::AddCacheEntry(const char* key,
712                                    const char* value,
713                                    const char* helpString,
714                                    CacheEntryType type)
715 {
716   CacheEntry& e = this->Cache[key];
717   e.Properties.SetCMakeInstance(this->CMakeInstance);
718   if ( value )
719     {
720     e.Value = value;
721     e.Initialized = true;
722     }
723   else
724     {
725     e.Value = "";
726     }
727   e.Type = type;
728   // make sure we only use unix style paths
729   if(type == FILEPATH || type == PATH)
730     {
731     if(e.Value.find(';') != e.Value.npos)
732       {
733       std::vector<std::string> paths;
734       cmSystemTools::ExpandListArgument(e.Value, paths);
735       const char* sep = "";
736       e.Value = "";
737       for(std::vector<std::string>::iterator i = paths.begin();
738           i != paths.end(); ++i)
739         {
740         cmSystemTools::ConvertToUnixSlashes(*i);
741         e.Value += sep;
742         e.Value += *i;
743         sep = ";";
744         }
745       }
746     else
747       {
748       cmSystemTools::ConvertToUnixSlashes(e.Value);
749       }
750     }
751   e.SetProperty("HELPSTRING", helpString? helpString :
752                 "(This variable does not exist and should not be used)");
753   if (this->Cache[key].Value == e.Value)
754     {
755     this->CMakeInstance->UnwatchUnusedCli(key);
756     }
757   this->Cache[key] = e;
758 }
759
760 bool cmCacheManager::CacheIterator::IsAtEnd() const
761 {
762   return this->Position == this->Container.Cache.end();
763 }
764
765 void cmCacheManager::CacheIterator::Begin()
766 {
767   this->Position = this->Container.Cache.begin();
768 }
769
770 bool cmCacheManager::CacheIterator::Find(const char* key)
771 {
772   this->Position = this->Container.Cache.find(key);
773   return !this->IsAtEnd();
774 }
775
776 void cmCacheManager::CacheIterator::Next()
777 {
778   if (!this->IsAtEnd())
779     {
780     ++this->Position;
781     }
782 }
783
784 void cmCacheManager::CacheIterator::SetValue(const char* value)
785 {
786   if (this->IsAtEnd())
787     {
788     return;
789     }
790   CacheEntry* entry = &this->GetEntry();
791   if ( value )
792     {
793     entry->Value = value;
794     entry->Initialized = true;
795     }
796   else
797     {
798     entry->Value = "";
799     }
800 }
801
802 //----------------------------------------------------------------------------
803 bool cmCacheManager::CacheIterator::GetValueAsBool() const
804 {
805   return cmSystemTools::IsOn(this->GetEntry().Value.c_str());
806 }
807
808 //----------------------------------------------------------------------------
809 const char*
810 cmCacheManager::CacheEntry::GetProperty(const char* prop) const
811 {
812   if(strcmp(prop, "TYPE") == 0)
813     {
814     return cmCacheManagerTypes[this->Type];
815     }
816   else if(strcmp(prop, "VALUE") == 0)
817     {
818     return this->Value.c_str();
819     }
820   bool c = false;
821   return
822     this->Properties.GetPropertyValue(prop, cmProperty::CACHE, c);
823 }
824
825 //----------------------------------------------------------------------------
826 void cmCacheManager::CacheEntry::SetProperty(const char* prop,
827                                              const char* value)
828 {
829   if(strcmp(prop, "TYPE") == 0)
830     {
831     this->Type = cmCacheManager::StringToType(value? value : "STRING");
832     }
833   else if(strcmp(prop, "VALUE") == 0)
834     {
835     this->Value = value? value : "";
836     }
837   else
838     {
839     this->Properties.SetProperty(prop, value, cmProperty::CACHE);
840     }
841 }
842
843 //----------------------------------------------------------------------------
844 void cmCacheManager::CacheEntry::AppendProperty(const char* prop,
845                                                 const char* value,
846                                                 bool asString)
847 {
848   if(strcmp(prop, "TYPE") == 0)
849     {
850     this->Type = cmCacheManager::StringToType(value? value : "STRING");
851     }
852   else if(strcmp(prop, "VALUE") == 0)
853     {
854     if(value)
855       {
856       if(!this->Value.empty() && *value && !asString)
857         {
858         this->Value += ";";
859         }
860       this->Value += value;
861       }
862     }
863   else
864     {
865     this->Properties.AppendProperty(prop, value, cmProperty::CACHE, asString);
866     }
867 }
868
869 //----------------------------------------------------------------------------
870 const char* cmCacheManager::CacheIterator::GetProperty(const char* prop) const
871 {
872   if(!this->IsAtEnd())
873     {
874     return this->GetEntry().GetProperty(prop);
875     }
876   return 0;
877 }
878
879 //----------------------------------------------------------------------------
880 void cmCacheManager::CacheIterator::SetProperty(const char* p, const char* v)
881 {
882   if(!this->IsAtEnd())
883     {
884     this->GetEntry().SetProperty(p, v);
885     }
886 }
887
888 //----------------------------------------------------------------------------
889 void cmCacheManager::CacheIterator::AppendProperty(const char* p,
890                                                    const char* v,
891                                                    bool asString)
892 {
893   if(!this->IsAtEnd())
894     {
895     this->GetEntry().AppendProperty(p, v, asString);
896     }
897 }
898
899 //----------------------------------------------------------------------------
900 bool cmCacheManager::CacheIterator::GetPropertyAsBool(const char* prop) const
901 {
902   if(const char* value = this->GetProperty(prop))
903     {
904     return cmSystemTools::IsOn(value);
905     }
906   return false;
907 }
908
909 //----------------------------------------------------------------------------
910 void cmCacheManager::CacheIterator::SetProperty(const char* p, bool v)
911 {
912   this->SetProperty(p, v ? "ON" : "OFF");
913 }
914
915 //----------------------------------------------------------------------------
916 bool cmCacheManager::CacheIterator::PropertyExists(const char* prop) const
917 {
918   return this->GetProperty(prop)? true:false;
919 }
920
921 //----------------------------------------------------------------------------
922 bool cmCacheManager::NeedCacheCompatibility(int major, int minor)
923 {
924   // Compatibility is not needed if the cache version is zero because
925   // the cache was created or modified by the user.
926   if(this->CacheMajorVersion == 0)
927     {
928     return false;
929     }
930
931   // Compatibility is needed if the cache version is equal to or lower
932   // than the given version.
933   unsigned int actual_compat =
934     CMake_VERSION_ENCODE(this->CacheMajorVersion, this->CacheMinorVersion, 0);
935   return (actual_compat &&
936           actual_compat <= CMake_VERSION_ENCODE(major, minor, 0));
937 }
938
939 //----------------------------------------------------------------------------
940 void cmCacheManager::DefineProperties(cmake *cm)
941 {
942   cm->DefineProperty
943     ("ADVANCED", cmProperty::CACHE,
944      "True if entry should be hidden by default in GUIs.",
945      "This is a boolean value indicating whether the entry is considered "
946      "interesting only for advanced configuration.  "
947      "The mark_as_advanced() command modifies this property."
948       );
949
950   cm->DefineProperty
951     ("HELPSTRING", cmProperty::CACHE,
952      "Help associated with entry in GUIs.",
953      "This string summarizes the purpose of an entry to help users set it "
954      "through a CMake GUI."
955       );
956
957   cm->DefineProperty
958     ("TYPE", cmProperty::CACHE,
959      "Widget type for entry in GUIs.",
960      "Cache entry values are always strings, but CMake GUIs present widgets "
961      "to help users set values.  "
962      "The GUIs use this property as a hint to determine the widget type.  "
963      "Valid TYPE values are:\n"
964      "  BOOL          = Boolean ON/OFF value.\n"
965      "  PATH          = Path to a directory.\n"
966      "  FILEPATH      = Path to a file.\n"
967      "  STRING        = Generic string value.\n"
968      "  INTERNAL      = Do not present in GUI at all.\n"
969      "  STATIC        = Value managed by CMake, do not change.\n"
970      "  UNINITIALIZED = Type not yet specified.\n"
971      "Generally the TYPE of a cache entry should be set by the command "
972      "which creates it (set, option, find_library, etc.)."
973       );
974
975   cm->DefineProperty
976     ("MODIFIED", cmProperty::CACHE,
977      "Internal management property.  Do not set or get.",
978      "This is an internal cache entry property managed by CMake to "
979      "track interactive user modification of entries.  Ignore it."
980       );
981
982   cm->DefineProperty
983     ("STRINGS", cmProperty::CACHE,
984      "Enumerate possible STRING entry values for GUI selection.",
985      "For cache entries with type STRING, this enumerates a set of values.  "
986      "CMake GUIs may use this to provide a selection widget instead of a "
987      "generic string entry field.  "
988      "This is for convenience only.  "
989      "CMake does not enforce that the value matches one of those listed."
990       );
991
992   cm->DefineProperty
993     ("VALUE", cmProperty::CACHE,
994      "Value of a cache entry.",
995      "This property maps to the actual value of a cache entry.  "
996      "Setting this property always sets the value without checking, so "
997      "use with care."
998       );
999 }