packaging: Initial packaging
[platform/upstream/cmake.git] / Source / cmExportFileGenerator.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 #include "cmExportFileGenerator.h"
13
14 #include "cmExportSet.h"
15 #include "cmGeneratedFileStream.h"
16 #include "cmGlobalGenerator.h"
17 #include "cmInstallExportGenerator.h"
18 #include "cmLocalGenerator.h"
19 #include "cmMakefile.h"
20 #include "cmSystemTools.h"
21 #include "cmTarget.h"
22 #include "cmTargetExport.h"
23 #include "cmVersion.h"
24 #include "cmComputeLinkInformation.h"
25
26 #include <cmsys/auto_ptr.hxx>
27 #include <assert.h>
28
29 //----------------------------------------------------------------------------
30 cmExportFileGenerator::cmExportFileGenerator()
31 {
32   this->AppendMode = false;
33   this->ExportOld = false;
34 }
35
36 //----------------------------------------------------------------------------
37 void cmExportFileGenerator::AddConfiguration(const char* config)
38 {
39   this->Configurations.push_back(config);
40 }
41
42 //----------------------------------------------------------------------------
43 void cmExportFileGenerator::SetExportFile(const char* mainFile)
44 {
45   this->MainImportFile = mainFile;
46   this->FileDir =
47     cmSystemTools::GetFilenamePath(this->MainImportFile);
48   this->FileBase =
49     cmSystemTools::GetFilenameWithoutLastExtension(this->MainImportFile);
50   this->FileExt =
51     cmSystemTools::GetFilenameLastExtension(this->MainImportFile);
52 }
53
54 //----------------------------------------------------------------------------
55 bool cmExportFileGenerator::GenerateImportFile()
56 {
57   // Open the output file to generate it.
58   cmsys::auto_ptr<std::ofstream> foutPtr;
59   if(this->AppendMode)
60     {
61     // Open for append.
62     cmsys::auto_ptr<std::ofstream>
63       ap(new std::ofstream(this->MainImportFile.c_str(), std::ios::app));
64     foutPtr = ap;
65     }
66   else
67     {
68     // Generate atomically and with copy-if-different.
69     cmsys::auto_ptr<cmGeneratedFileStream>
70       ap(new cmGeneratedFileStream(this->MainImportFile.c_str(), true));
71     ap->SetCopyIfDifferent(true);
72     foutPtr = ap;
73     }
74   if(!foutPtr.get() || !*foutPtr)
75     {
76     std::string se = cmSystemTools::GetLastSystemError();
77     cmOStringStream e;
78     e << "cannot write to file \"" << this->MainImportFile
79       << "\": " << se;
80     cmSystemTools::Error(e.str().c_str());
81     return false;
82     }
83   std::ostream& os = *foutPtr;
84
85   // Protect that file against use with older CMake versions.
86   os << "# Generated by CMake " << cmVersion::GetCMakeVersion() << "\n\n";
87   os << "if(\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" LESS 2.5)\n"
88      << "   message(FATAL_ERROR \"CMake >= 2.6.0 required\")\n"
89      << "endif()\n";
90
91   // Isolate the file policy level.
92   // We use 2.6 here instead of the current version because newer
93   // versions of CMake should be able to export files imported by 2.6
94   // until the import format changes.
95   os << "cmake_policy(PUSH)\n"
96      << "cmake_policy(VERSION 2.6)\n";
97
98   // Start with the import file header.
99   this->GenerateImportHeaderCode(os);
100
101   // Create all the imported targets.
102   bool result = this->GenerateMainFile(os);
103
104   // End with the import file footer.
105   this->GenerateImportFooterCode(os);
106   os << "cmake_policy(POP)\n";
107
108   return result;
109 }
110
111 //----------------------------------------------------------------------------
112 void cmExportFileGenerator::GenerateImportConfig(std::ostream& os,
113                                     const char* config,
114                                     std::vector<std::string> &missingTargets)
115 {
116   // Construct the property configuration suffix.
117   std::string suffix = "_";
118   if(config && *config)
119     {
120     suffix += cmSystemTools::UpperCase(config);
121     }
122   else
123     {
124     suffix += "NOCONFIG";
125     }
126
127   // Generate the per-config target information.
128   this->GenerateImportTargetsConfig(os, config, suffix, missingTargets);
129 }
130
131 //----------------------------------------------------------------------------
132 void cmExportFileGenerator::PopulateInterfaceProperty(const char *propName,
133                                               cmTarget *target,
134                                               ImportPropertyMap &properties)
135 {
136   const char *input = target->GetProperty(propName);
137   if (input)
138     {
139     properties[propName] = input;
140     }
141 }
142
143 //----------------------------------------------------------------------------
144 void cmExportFileGenerator::PopulateInterfaceProperty(const char *propName,
145                       const char *outputName,
146                       cmTarget *target,
147                       cmGeneratorExpression::PreprocessContext preprocessRule,
148                       ImportPropertyMap &properties,
149                       std::vector<std::string> &missingTargets)
150 {
151   const char *input = target->GetProperty(propName);
152   if (input)
153     {
154     if (!*input)
155       {
156       // Set to empty
157       properties[outputName] = "";
158       return;
159       }
160
161     std::string prepro = cmGeneratorExpression::Preprocess(input,
162                                                            preprocessRule);
163     if (!prepro.empty())
164       {
165       this->ResolveTargetsInGeneratorExpressions(prepro, target,
166                                                  missingTargets);
167       properties[outputName] = prepro;
168       }
169     }
170 }
171
172 void cmExportFileGenerator::GenerateRequiredCMakeVersion(std::ostream& os,
173                                                     const char *versionString)
174 {
175   os << "if(CMAKE_VERSION VERSION_LESS " << versionString << ")\n"
176         "  message(FATAL_ERROR \"This file relies on consumers using "
177         "CMake " << versionString << " or greater.\")\n"
178         "endif()\n\n";
179 }
180
181 //----------------------------------------------------------------------------
182 bool cmExportFileGenerator::PopulateInterfaceLinkLibrariesProperty(
183                       cmTarget *target,
184                       cmGeneratorExpression::PreprocessContext preprocessRule,
185                       ImportPropertyMap &properties,
186                       std::vector<std::string> &missingTargets)
187 {
188   if(!target->IsLinkable())
189     {
190     return false;
191     }
192   const char *input = target->GetProperty("INTERFACE_LINK_LIBRARIES");
193   if (input)
194     {
195     std::string prepro = cmGeneratorExpression::Preprocess(input,
196                                                            preprocessRule);
197     if (!prepro.empty())
198       {
199       this->ResolveTargetsInGeneratorExpressions(prepro, target,
200                                                  missingTargets,
201                                                  ReplaceFreeTargets);
202       properties["INTERFACE_LINK_LIBRARIES"] = prepro;
203       return true;
204       }
205     }
206   return false;
207 }
208
209 //----------------------------------------------------------------------------
210 static bool isSubDirectory(const char* a, const char* b)
211 {
212   return (cmSystemTools::ComparePath(a, b) ||
213           cmSystemTools::IsSubDirectory(a, b));
214 }
215
216 //----------------------------------------------------------------------------
217 static bool checkInterfaceDirs(const std::string &prepro,
218                       cmTarget *target)
219 {
220   const char* installDir =
221             target->GetMakefile()->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
222   const char* topSourceDir = target->GetMakefile()->GetHomeDirectory();
223   const char* topBinaryDir = target->GetMakefile()->GetHomeOutputDirectory();
224
225   std::vector<std::string> parts;
226   cmGeneratorExpression::Split(prepro, parts);
227
228   const bool inSourceBuild = strcmp(topSourceDir, topBinaryDir) == 0;
229
230   for(std::vector<std::string>::iterator li = parts.begin();
231       li != parts.end(); ++li)
232     {
233     if (cmGeneratorExpression::Find(*li) != std::string::npos)
234       {
235       continue;
236       }
237     if (strncmp(li->c_str(), "${_IMPORT_PREFIX}", 17) == 0)
238       {
239       continue;
240       }
241     if (!cmSystemTools::FileIsFullPath(li->c_str()))
242       {
243       cmOStringStream e;
244       e << "Target \"" << target->GetName() << "\" "
245            "INTERFACE_INCLUDE_DIRECTORIES property contains relative path:\n"
246            "  \"" << *li << "\"";
247       target->GetMakefile()->IssueMessage(cmake::FATAL_ERROR,
248                                           e.str().c_str());
249       return false;
250       }
251     if (isSubDirectory(li->c_str(), installDir))
252       {
253       continue;
254       }
255     if (isSubDirectory(li->c_str(), topBinaryDir))
256       {
257       cmOStringStream e;
258       e << "Target \"" << target->GetName() << "\" "
259            "INTERFACE_INCLUDE_DIRECTORIES property contains path:\n"
260            "  \"" << *li << "\"\nwhich is prefixed in the build directory.";
261       target->GetMakefile()->IssueMessage(cmake::FATAL_ERROR,
262                                           e.str().c_str());
263       return false;
264       }
265     if (!inSourceBuild)
266       {
267       if (isSubDirectory(li->c_str(), topSourceDir))
268         {
269         cmOStringStream e;
270         e << "Target \"" << target->GetName() << "\" "
271             "INTERFACE_INCLUDE_DIRECTORIES property contains path:\n"
272             "  \"" << *li << "\"\nwhich is prefixed in the source directory.";
273         target->GetMakefile()->IssueMessage(cmake::FATAL_ERROR,
274                                             e.str().c_str());
275         return false;
276         }
277       }
278     }
279   return true;
280 }
281
282 //----------------------------------------------------------------------------
283 void cmExportFileGenerator::PopulateIncludeDirectoriesInterface(
284                       cmTargetExport *tei,
285                       cmGeneratorExpression::PreprocessContext preprocessRule,
286                       ImportPropertyMap &properties,
287                       std::vector<std::string> &missingTargets)
288 {
289   cmTarget *target = tei->Target;
290   assert(preprocessRule == cmGeneratorExpression::InstallInterface);
291
292   const char *propName = "INTERFACE_INCLUDE_DIRECTORIES";
293   const char *input = target->GetProperty(propName);
294
295   cmListFileBacktrace lfbt;
296   cmGeneratorExpression ge(lfbt);
297
298   std::string dirs = tei->InterfaceIncludeDirectories;
299   this->ReplaceInstallPrefix(dirs);
300   cmsys::auto_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(dirs);
301   std::string exportDirs = cge->Evaluate(target->GetMakefile(), 0,
302                                          false, target);
303
304   if (cge->GetHadContextSensitiveCondition())
305     {
306     cmMakefile* mf = target->GetMakefile();
307     cmOStringStream e;
308     e << "Target \"" << target->GetName() << "\" is installed with "
309     "INCLUDES DESTINATION set to a context sensitive path.  Paths which "
310     "depend on the configuration, policy values or the link interface are "
311     "not supported.  Consider using target_include_directories instead.";
312     mf->IssueMessage(cmake::FATAL_ERROR, e.str());
313     return;
314     }
315
316   if (!input && exportDirs.empty())
317     {
318     return;
319     }
320   if ((input && !*input) && exportDirs.empty())
321     {
322     // Set to empty
323     properties[propName] = "";
324     return;
325     }
326
327   std::string includes = (input?input:"");
328   const char* sep = input ? ";" : "";
329   includes += sep + exportDirs;
330   std::string prepro = cmGeneratorExpression::Preprocess(includes,
331                                                          preprocessRule,
332                                                          true);
333   if (!prepro.empty())
334     {
335     this->ResolveTargetsInGeneratorExpressions(prepro, target,
336                                                 missingTargets);
337
338     if (!checkInterfaceDirs(prepro, target))
339       {
340       return;
341       }
342     properties[propName] = prepro;
343     }
344 }
345
346 //----------------------------------------------------------------------------
347 void cmExportFileGenerator::PopulateInterfaceProperty(const char *propName,
348                       cmTarget *target,
349                       cmGeneratorExpression::PreprocessContext preprocessRule,
350                       ImportPropertyMap &properties,
351                       std::vector<std::string> &missingTargets)
352 {
353   this->PopulateInterfaceProperty(propName, propName, target, preprocessRule,
354                             properties, missingTargets);
355 }
356
357
358 //----------------------------------------------------------------------------
359 void getPropertyContents(cmTarget *tgt, const char *prop,
360          std::set<std::string> &ifaceProperties)
361 {
362   const char *p = tgt->GetProperty(prop);
363   if (!p)
364     {
365     return;
366     }
367   std::vector<std::string> content;
368   cmSystemTools::ExpandListArgument(p, content);
369   for (std::vector<std::string>::const_iterator ci = content.begin();
370     ci != content.end(); ++ci)
371     {
372     ifaceProperties.insert(*ci);
373     }
374 }
375
376 //----------------------------------------------------------------------------
377 void getCompatibleInterfaceProperties(cmTarget *target,
378                                       std::set<std::string> &ifaceProperties,
379                                       const char *config)
380 {
381   cmComputeLinkInformation *info = target->GetLinkInformation(config);
382
383   if (!info)
384     {
385     cmMakefile* mf = target->GetMakefile();
386     cmOStringStream e;
387     e << "Exporting the target \"" << target->GetName() << "\" is not "
388          "allowed since its linker language cannot be determined";
389     mf->IssueMessage(cmake::FATAL_ERROR, e.str());
390     return;
391     }
392
393   const cmComputeLinkInformation::ItemVector &deps = info->GetItems();
394
395   for(cmComputeLinkInformation::ItemVector::const_iterator li =
396       deps.begin();
397       li != deps.end(); ++li)
398     {
399     if (!li->Target)
400       {
401       continue;
402       }
403     getPropertyContents(li->Target,
404                         "COMPATIBLE_INTERFACE_BOOL",
405                         ifaceProperties);
406     getPropertyContents(li->Target,
407                         "COMPATIBLE_INTERFACE_STRING",
408                         ifaceProperties);
409     }
410 }
411
412 //----------------------------------------------------------------------------
413 void cmExportFileGenerator::PopulateCompatibleInterfaceProperties(
414                                 cmTarget *target,
415                                 ImportPropertyMap &properties)
416 {
417   this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_BOOL",
418                                 target, properties);
419   this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_STRING",
420                                 target, properties);
421
422   std::set<std::string> ifaceProperties;
423
424   getPropertyContents(target, "COMPATIBLE_INTERFACE_BOOL", ifaceProperties);
425   getPropertyContents(target, "COMPATIBLE_INTERFACE_STRING", ifaceProperties);
426
427   getCompatibleInterfaceProperties(target, ifaceProperties, 0);
428
429   std::vector<std::string> configNames;
430   target->GetMakefile()->GetConfigurations(configNames);
431
432   for (std::vector<std::string>::const_iterator ci = configNames.begin();
433     ci != configNames.end(); ++ci)
434     {
435     getCompatibleInterfaceProperties(target, ifaceProperties, ci->c_str());
436     }
437
438   for (std::set<std::string>::const_iterator it = ifaceProperties.begin();
439     it != ifaceProperties.end(); ++it)
440     {
441     this->PopulateInterfaceProperty(("INTERFACE_" + *it).c_str(),
442                                     target, properties);
443     }
444 }
445
446 //----------------------------------------------------------------------------
447 void cmExportFileGenerator::GenerateInterfaceProperties(cmTarget *target,
448                                         std::ostream& os,
449                                         const ImportPropertyMap &properties)
450 {
451   if (!properties.empty())
452     {
453     std::string targetName = this->Namespace;
454     targetName += target->GetExportName();
455     os << "set_target_properties(" << targetName << " PROPERTIES\n";
456     for(ImportPropertyMap::const_iterator pi = properties.begin();
457         pi != properties.end(); ++pi)
458       {
459       os << "  " << pi->first << " \"" << pi->second << "\"\n";
460       }
461     os << ")\n\n";
462     }
463 }
464
465 //----------------------------------------------------------------------------
466 bool
467 cmExportFileGenerator::AddTargetNamespace(std::string &input,
468                                     cmTarget* target,
469                                     std::vector<std::string> &missingTargets)
470 {
471   cmMakefile *mf = target->GetMakefile();
472
473   cmTarget *tgt = mf->FindTargetToUse(input.c_str());
474   if (!tgt)
475     {
476     return false;
477     }
478
479   if(tgt->IsImported())
480     {
481     return true;
482     }
483   if(this->ExportedTargets.find(tgt) != this->ExportedTargets.end())
484     {
485     input = this->Namespace + tgt->GetExportName();
486     }
487   else
488     {
489     std::string namespacedTarget;
490     this->HandleMissingTarget(namespacedTarget, missingTargets,
491                               mf, target, tgt);
492     if (!namespacedTarget.empty())
493       {
494       input = namespacedTarget;
495       }
496     }
497   return true;
498 }
499
500 //----------------------------------------------------------------------------
501 void
502 cmExportFileGenerator::ResolveTargetsInGeneratorExpressions(
503                                     std::string &input,
504                                     cmTarget* target,
505                                     std::vector<std::string> &missingTargets,
506                                     FreeTargetsReplace replace)
507 {
508   if (replace == NoReplaceFreeTargets)
509     {
510     this->ResolveTargetsInGeneratorExpression(input, target, missingTargets);
511     return;
512     }
513   std::vector<std::string> parts;
514   cmGeneratorExpression::Split(input, parts);
515
516   std::string sep;
517   input = "";
518   for(std::vector<std::string>::iterator li = parts.begin();
519       li != parts.end(); ++li)
520     {
521     if (cmGeneratorExpression::Find(*li) == std::string::npos)
522       {
523       this->AddTargetNamespace(*li, target, missingTargets);
524       }
525     else
526       {
527       this->ResolveTargetsInGeneratorExpression(
528                                     *li,
529                                     target,
530                                     missingTargets);
531       }
532     input += sep + *li;
533     sep = ";";
534     }
535 }
536
537 //----------------------------------------------------------------------------
538 void
539 cmExportFileGenerator::ResolveTargetsInGeneratorExpression(
540                                     std::string &input,
541                                     cmTarget* target,
542                                     std::vector<std::string> &missingTargets)
543 {
544   std::string::size_type pos = 0;
545   std::string::size_type lastPos = pos;
546
547   cmMakefile *mf = target->GetMakefile();
548
549   while((pos = input.find("$<TARGET_PROPERTY:", lastPos)) != input.npos)
550     {
551     std::string::size_type nameStartPos = pos +
552                                             sizeof("$<TARGET_PROPERTY:") - 1;
553     std::string::size_type closePos = input.find(">", nameStartPos);
554     std::string::size_type commaPos = input.find(",", nameStartPos);
555     std::string::size_type nextOpenPos = input.find("$<", nameStartPos);
556     if (commaPos == input.npos // Implied 'this' target
557         || closePos == input.npos // Imcomplete expression.
558         || closePos < commaPos // Implied 'this' target
559         || nextOpenPos < commaPos) // Non-literal
560       {
561       lastPos = nameStartPos;
562       continue;
563       }
564
565     std::string targetName = input.substr(nameStartPos,
566                                                 commaPos - nameStartPos);
567
568     if (this->AddTargetNamespace(targetName, target, missingTargets))
569       {
570       input.replace(nameStartPos, commaPos - nameStartPos, targetName);
571       }
572     lastPos = nameStartPos + targetName.size() + 1;
573     }
574
575   std::string errorString;
576   pos = 0;
577   lastPos = pos;
578   while((pos = input.find("$<TARGET_NAME:", lastPos)) != input.npos)
579     {
580     std::string::size_type nameStartPos = pos + sizeof("$<TARGET_NAME:") - 1;
581     std::string::size_type endPos = input.find(">", nameStartPos);
582     if (endPos == input.npos)
583       {
584       errorString = "$<TARGET_NAME:...> expression incomplete";
585       break;
586       }
587     std::string targetName = input.substr(nameStartPos,
588                                                 endPos - nameStartPos);
589     if(targetName.find("$<") != input.npos)
590       {
591       errorString = "$<TARGET_NAME:...> requires its parameter to be a "
592                     "literal.";
593       break;
594       }
595     if (!this->AddTargetNamespace(targetName, target, missingTargets))
596       {
597       errorString = "$<TARGET_NAME:...> requires its parameter to be a "
598                     "reachable target.";
599       break;
600       }
601     input.replace(pos, endPos - pos + 1, targetName);
602     lastPos = endPos;
603     }
604
605   this->ReplaceInstallPrefix(input);
606
607   if (!errorString.empty())
608     {
609     mf->IssueMessage(cmake::FATAL_ERROR, errorString);
610     }
611 }
612
613 //----------------------------------------------------------------------------
614 void
615 cmExportFileGenerator::ReplaceInstallPrefix(std::string &)
616 {
617   // Do nothing
618 }
619
620 //----------------------------------------------------------------------------
621 void
622 cmExportFileGenerator
623 ::SetImportLinkInterface(const char* config, std::string const& suffix,
624                     cmGeneratorExpression::PreprocessContext preprocessRule,
625                     cmTarget* target, ImportPropertyMap& properties,
626                     std::vector<std::string>& missingTargets)
627 {
628   // Add the transitive link dependencies for this configuration.
629   cmTarget::LinkInterface const* iface = target->GetLinkInterface(config,
630                                                                   target);
631   if (!iface)
632     {
633     return;
634     }
635
636   if (iface->ImplementationIsInterface)
637     {
638     // Policy CMP0022 must not be NEW.
639     this->SetImportLinkProperty(suffix, target,
640                                 "IMPORTED_LINK_INTERFACE_LIBRARIES",
641                                 iface->Libraries, properties, missingTargets);
642     return;
643     }
644
645   const char *propContent;
646
647   if (const char *prop_suffixed = target->GetProperty(
648                     ("LINK_INTERFACE_LIBRARIES" + suffix).c_str()))
649     {
650     propContent = prop_suffixed;
651     }
652   else if (const char *prop = target->GetProperty(
653                     "LINK_INTERFACE_LIBRARIES"))
654     {
655     propContent = prop;
656     }
657   else
658     {
659     return;
660     }
661
662   const bool newCMP0022Behavior =
663                         target->GetPolicyStatusCMP0022() != cmPolicies::WARN
664                      && target->GetPolicyStatusCMP0022() != cmPolicies::OLD;
665
666   if(newCMP0022Behavior && !this->ExportOld)
667     {
668     cmMakefile *mf = target->GetMakefile();
669     cmOStringStream e;
670     e << "Target \"" << target->GetName() << "\" has policy CMP0022 enabled, "
671          "but also has old-style LINK_INTERFACE_LIBRARIES properties "
672          "populated, but it was exported without the "
673          "EXPORT_LINK_INTERFACE_LIBRARIES to export the old-style properties";
674     mf->IssueMessage(cmake::FATAL_ERROR, e.str());
675     return;
676     }
677
678   if (!*propContent)
679     {
680     properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix] = "";
681     return;
682     }
683
684   std::string prepro = cmGeneratorExpression::Preprocess(propContent,
685                                                          preprocessRule);
686   if (!prepro.empty())
687     {
688     this->ResolveTargetsInGeneratorExpressions(prepro, target,
689                                                missingTargets,
690                                                ReplaceFreeTargets);
691     properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix] = prepro;
692     }
693 }
694
695 //----------------------------------------------------------------------------
696 void
697 cmExportFileGenerator
698 ::SetImportDetailProperties(const char* config, std::string const& suffix,
699                             cmTarget* target, ImportPropertyMap& properties,
700                             std::vector<std::string>& missingTargets
701                            )
702 {
703   // Get the makefile in which to lookup target information.
704   cmMakefile* mf = target->GetMakefile();
705
706   // Add the soname for unix shared libraries.
707   if(target->GetType() == cmTarget::SHARED_LIBRARY ||
708      target->GetType() == cmTarget::MODULE_LIBRARY)
709     {
710     // Check whether this is a DLL platform.
711     bool dll_platform =
712       (mf->IsOn("WIN32") || mf->IsOn("CYGWIN") || mf->IsOn("MINGW"));
713     if(!dll_platform)
714       {
715       std::string prop;
716       std::string value;
717       if(target->HasSOName(config))
718         {
719         if(mf->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME"))
720           {
721           value = this->InstallNameDir(target, config);
722           }
723         prop = "IMPORTED_SONAME";
724         value += target->GetSOName(config);
725         }
726       else
727         {
728         prop = "IMPORTED_NO_SONAME";
729         value = "TRUE";
730         }
731       prop += suffix;
732       properties[prop] = value;
733       }
734     }
735
736   // Add the transitive link dependencies for this configuration.
737   if(cmTarget::LinkInterface const* iface = target->GetLinkInterface(config,
738                                                                      target))
739     {
740     this->SetImportLinkProperty(suffix, target,
741                                 "IMPORTED_LINK_INTERFACE_LANGUAGES",
742                                 iface->Languages, properties, missingTargets);
743
744     this->SetImportLinkProperty(suffix, target,
745                                 "IMPORTED_LINK_DEPENDENT_LIBRARIES",
746                                 iface->SharedDeps, properties, missingTargets);
747     if(iface->Multiplicity > 0)
748       {
749       std::string prop = "IMPORTED_LINK_INTERFACE_MULTIPLICITY";
750       prop += suffix;
751       cmOStringStream m;
752       m << iface->Multiplicity;
753       properties[prop] = m.str();
754       }
755     }
756 }
757
758 //----------------------------------------------------------------------------
759 void
760 cmExportFileGenerator
761 ::SetImportLinkProperty(std::string const& suffix,
762                         cmTarget* target,
763                         const char* propName,
764                         std::vector<std::string> const& libs,
765                         ImportPropertyMap& properties,
766                         std::vector<std::string>& missingTargets
767                        )
768 {
769   // Skip the property if there are no libraries.
770   if(libs.empty())
771     {
772     return;
773     }
774
775   // Construct the property value.
776   std::string link_libs;
777   const char* sep = "";
778   for(std::vector<std::string>::const_iterator li = libs.begin();
779       li != libs.end(); ++li)
780     {
781     // Separate this from the previous entry.
782     link_libs += sep;
783     sep = ";";
784
785     std::string temp = *li;
786     this->AddTargetNamespace(temp, target, missingTargets);
787     link_libs += temp;
788     }
789
790   // Store the property.
791   std::string prop = propName;
792   prop += suffix;
793   properties[prop] = link_libs;
794 }
795
796
797 //----------------------------------------------------------------------------
798 void cmExportFileGenerator::GenerateImportHeaderCode(std::ostream& os,
799                                                      const char* config)
800 {
801   os << "#----------------------------------------------------------------\n"
802      << "# Generated CMake target import file";
803   if(config)
804     {
805     os << " for configuration \"" << config << "\".\n";
806     }
807   else
808     {
809     os << ".\n";
810     }
811   os << "#----------------------------------------------------------------\n"
812      << "\n";
813   this->GenerateImportVersionCode(os);
814 }
815
816 //----------------------------------------------------------------------------
817 void cmExportFileGenerator::GenerateImportFooterCode(std::ostream& os)
818 {
819   os << "# Commands beyond this point should not need to know the version.\n"
820      << "set(CMAKE_IMPORT_FILE_VERSION)\n";
821 }
822
823 //----------------------------------------------------------------------------
824 void cmExportFileGenerator::GenerateImportVersionCode(std::ostream& os)
825 {
826   // Store an import file format version.  This will let us change the
827   // format later while still allowing old import files to work.
828   os << "# Commands may need to know the format version.\n"
829      << "set(CMAKE_IMPORT_FILE_VERSION 1)\n"
830      << "\n";
831 }
832
833 //----------------------------------------------------------------------------
834 void cmExportFileGenerator::GenerateExpectedTargetsCode(std::ostream& os,
835                                             const std::string &expectedTargets)
836 {
837   os << "# Protect against multiple inclusion, which would fail when already "
838         "imported targets are added once more.\n"
839         "set(_targetsDefined)\n"
840         "set(_targetsNotDefined)\n"
841         "set(_expectedTargets)\n"
842         "foreach(_expectedTarget " << expectedTargets << ")\n"
843         "  list(APPEND _expectedTargets ${_expectedTarget})\n"
844         "  if(NOT TARGET ${_expectedTarget})\n"
845         "    list(APPEND _targetsNotDefined ${_expectedTarget})\n"
846         "  endif()\n"
847         "  if(TARGET ${_expectedTarget})\n"
848         "    list(APPEND _targetsDefined ${_expectedTarget})\n"
849         "  endif()\n"
850         "endforeach()\n"
851         "if(\"${_targetsDefined}\" STREQUAL \"${_expectedTargets}\")\n"
852         "  set(CMAKE_IMPORT_FILE_VERSION)\n"
853         "  cmake_policy(POP)\n"
854         "  return()\n"
855         "endif()\n"
856         "if(NOT \"${_targetsDefined}\" STREQUAL \"\")\n"
857         "  message(FATAL_ERROR \"Some (but not all) targets in this export "
858         "set were already defined.\\nTargets Defined: ${_targetsDefined}\\n"
859         "Targets not yet defined: ${_targetsNotDefined}\\n\")\n"
860         "endif()\n"
861         "unset(_targetsDefined)\n"
862         "unset(_targetsNotDefined)\n"
863         "unset(_expectedTargets)\n"
864         "\n\n";
865 }
866 //----------------------------------------------------------------------------
867 void
868 cmExportFileGenerator
869 ::GenerateImportTargetCode(std::ostream& os, cmTarget* target)
870 {
871   // Construct the imported target name.
872   std::string targetName = this->Namespace;
873
874   targetName += target->GetExportName();
875
876   // Create the imported target.
877   os << "# Create imported target " << targetName << "\n";
878   switch(target->GetType())
879     {
880     case cmTarget::EXECUTABLE:
881       os << "add_executable(" << targetName << " IMPORTED)\n";
882       break;
883     case cmTarget::STATIC_LIBRARY:
884       os << "add_library(" << targetName << " STATIC IMPORTED)\n";
885       break;
886     case cmTarget::SHARED_LIBRARY:
887       os << "add_library(" << targetName << " SHARED IMPORTED)\n";
888       break;
889     case cmTarget::MODULE_LIBRARY:
890       os << "add_library(" << targetName << " MODULE IMPORTED)\n";
891       break;
892     case cmTarget::UNKNOWN_LIBRARY:
893       os << "add_library(" << targetName << " UNKNOWN IMPORTED)\n";
894       break;
895     default:  // should never happen
896       break;
897     }
898
899   // Mark the imported executable if it has exports.
900   if(target->IsExecutableWithExports())
901     {
902     os << "set_property(TARGET " << targetName
903        << " PROPERTY ENABLE_EXPORTS 1)\n";
904     }
905
906   // Mark the imported library if it is a framework.
907   if(target->IsFrameworkOnApple())
908     {
909     os << "set_property(TARGET " << targetName
910        << " PROPERTY FRAMEWORK 1)\n";
911     }
912
913   // Mark the imported executable if it is an application bundle.
914   if(target->IsAppBundleOnApple())
915     {
916     os << "set_property(TARGET " << targetName
917        << " PROPERTY MACOSX_BUNDLE 1)\n";
918     }
919
920   if (target->IsCFBundleOnApple())
921     {
922     os << "set_property(TARGET " << targetName
923        << " PROPERTY BUNDLE 1)\n";
924     }
925   os << "\n";
926 }
927
928 //----------------------------------------------------------------------------
929 void
930 cmExportFileGenerator
931 ::GenerateImportPropertyCode(std::ostream& os, const char* config,
932                              cmTarget* target,
933                              ImportPropertyMap const& properties)
934 {
935   // Construct the imported target name.
936   std::string targetName = this->Namespace;
937
938   targetName += target->GetExportName();
939
940   // Set the import properties.
941   os << "# Import target \"" << targetName << "\" for configuration \""
942      << config << "\"\n";
943   os << "set_property(TARGET " << targetName
944      << " APPEND PROPERTY IMPORTED_CONFIGURATIONS ";
945   if(config && *config)
946     {
947     os << cmSystemTools::UpperCase(config);
948     }
949   else
950     {
951     os << "NOCONFIG";
952     }
953   os << ")\n";
954   os << "set_target_properties(" << targetName << " PROPERTIES\n";
955   for(ImportPropertyMap::const_iterator pi = properties.begin();
956       pi != properties.end(); ++pi)
957     {
958     os << "  " << pi->first << " \"" << pi->second << "\"\n";
959     }
960   os << "  )\n"
961      << "\n";
962 }
963
964
965 //----------------------------------------------------------------------------
966 void cmExportFileGenerator::GenerateMissingTargetsCheckCode(std::ostream& os,
967                                 const std::vector<std::string>& missingTargets)
968 {
969   if (missingTargets.empty())
970     {
971     os << "# This file does not depend on other imported targets which have\n"
972           "# been exported from the same project but in a separate "
973             "export set.\n\n";
974     return;
975     }
976   os << "# Make sure the targets which have been exported in some other \n"
977         "# export set exist.\n"
978         "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
979         "foreach(_target ";
980   std::set<std::string> emitted;
981   for(unsigned int i=0; i<missingTargets.size(); ++i)
982     {
983     if (emitted.insert(missingTargets[i]).second)
984       {
985       os << "\"" << missingTargets[i] <<  "\" ";
986       }
987     }
988   os << ")\n"
989         "  if(NOT TARGET \"${_target}\" )\n"
990         "    set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets \""
991         "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets} ${_target}\")"
992         "\n"
993         "  endif()\n"
994         "endforeach()\n"
995         "\n"
996         "if(DEFINED ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
997         "  if(CMAKE_FIND_PACKAGE_NAME)\n"
998         "    set( ${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)\n"
999         "    set( ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE "
1000         "\"The following imported targets are "
1001         "referenced, but are missing: "
1002                  "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
1003         "  else()\n"
1004         "    message(FATAL_ERROR \"The following imported targets are "
1005         "referenced, but are missing: "
1006                 "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
1007         "  endif()\n"
1008         "endif()\n"
1009         "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
1010         "\n";
1011 }
1012
1013
1014 //----------------------------------------------------------------------------
1015 void
1016 cmExportFileGenerator::GenerateImportedFileCheckLoop(std::ostream& os)
1017 {
1018   // Add code which verifies at cmake time that the file which is being
1019   // imported actually exists on disk. This should in theory always be theory
1020   // case, but still when packages are split into normal and development
1021   // packages this might get broken (e.g. the Config.cmake could be part of
1022   // the non-development package, something similar happened to me without
1023   // on SUSE with a mysql pkg-config file, which claimed everything is fine,
1024   // but the development package was not installed.).
1025   os << "# Loop over all imported files and verify that they actually exist\n"
1026         "foreach(target ${_IMPORT_CHECK_TARGETS} )\n"
1027         "  foreach(file ${_IMPORT_CHECK_FILES_FOR_${target}} )\n"
1028         "    if(NOT EXISTS \"${file}\" )\n"
1029         "      message(FATAL_ERROR \"The imported target \\\"${target}\\\""
1030         " references the file\n"
1031         "   \\\"${file}\\\"\n"
1032         "but this file does not exist.  Possible reasons include:\n"
1033         "* The file was deleted, renamed, or moved to another location.\n"
1034         "* An install or uninstall procedure did not complete successfully.\n"
1035         "* The installation package was faulty and contained\n"
1036         "   \\\"${CMAKE_CURRENT_LIST_FILE}\\\"\n"
1037         "but not all the files it references.\n"
1038         "\")\n"
1039         "    endif()\n"
1040         "  endforeach()\n"
1041         "  unset(_IMPORT_CHECK_FILES_FOR_${target})\n"
1042         "endforeach()\n"
1043         "unset(_IMPORT_CHECK_TARGETS)\n"
1044         "\n";
1045 }
1046
1047
1048 //----------------------------------------------------------------------------
1049 void
1050 cmExportFileGenerator
1051 ::GenerateImportedFileChecksCode(std::ostream& os, cmTarget* target,
1052                                  ImportPropertyMap const& properties,
1053                                 const std::set<std::string>& importedLocations)
1054 {
1055   // Construct the imported target name.
1056   std::string targetName = this->Namespace;
1057   targetName += target->GetExportName();
1058
1059   os << "list(APPEND _IMPORT_CHECK_TARGETS " << targetName << " )\n"
1060         "list(APPEND _IMPORT_CHECK_FILES_FOR_" << targetName << " ";
1061
1062   for(std::set<std::string>::const_iterator li = importedLocations.begin();
1063       li != importedLocations.end();
1064       ++li)
1065     {
1066     ImportPropertyMap::const_iterator pi = properties.find(*li);
1067     if (pi != properties.end())
1068       {
1069       os << "\"" << pi->second << "\" ";
1070       }
1071     }
1072
1073   os << ")\n\n";
1074 }