resolve cyclic dependency with zstd
[platform/upstream/cmake.git] / Source / cmGeneratorExpressionEvaluationFile.cxx
1 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2    file Copyright.txt or https://cmake.org/licensing for details.  */
3 #include "cmGeneratorExpressionEvaluationFile.h"
4
5 #include <memory>
6 #include <sstream>
7 #include <utility>
8
9 #include "cmsys/FStream.hxx"
10
11 #include "cmGeneratedFileStream.h"
12 #include "cmGlobalGenerator.h"
13 #include "cmListFileCache.h"
14 #include "cmLocalGenerator.h"
15 #include "cmMakefile.h"
16 #include "cmMessageType.h"
17 #include "cmSourceFile.h"
18 #include "cmSystemTools.h"
19
20 cmGeneratorExpressionEvaluationFile::cmGeneratorExpressionEvaluationFile(
21   std::string input, std::string target,
22   std::unique_ptr<cmCompiledGeneratorExpression> outputFileExpr,
23   std::unique_ptr<cmCompiledGeneratorExpression> condition,
24   bool inputIsContent, std::string newLineCharacter, mode_t permissions,
25   cmPolicies::PolicyStatus policyStatusCMP0070)
26   : Input(std::move(input))
27   , Target(std::move(target))
28   , OutputFileExpr(std::move(outputFileExpr))
29   , Condition(std::move(condition))
30   , InputIsContent(inputIsContent)
31   , NewLineCharacter(std::move(newLineCharacter))
32   , PolicyStatusCMP0070(policyStatusCMP0070)
33   , Permissions(permissions)
34 {
35 }
36
37 void cmGeneratorExpressionEvaluationFile::Generate(
38   cmLocalGenerator* lg, const std::string& config, const std::string& lang,
39   cmCompiledGeneratorExpression* inputExpression,
40   std::map<std::string, std::string>& outputFiles, mode_t perm)
41 {
42   std::string rawCondition = this->Condition->GetInput();
43   cmGeneratorTarget* target = lg->FindGeneratorTargetToUse(this->Target);
44   if (!rawCondition.empty()) {
45     std::string condResult =
46       this->Condition->Evaluate(lg, config, target, nullptr, nullptr, lang);
47     if (condResult == "0") {
48       return;
49     }
50     if (condResult != "1") {
51       std::ostringstream e;
52       e << "Evaluation file condition \"" << rawCondition
53         << "\" did "
54            "not evaluate to valid content. Got \""
55         << condResult << "\".";
56       lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
57       return;
58     }
59   }
60
61   const std::string outputFileName =
62     this->GetOutputFileName(lg, target, config, lang);
63   const std::string& outputContent =
64     inputExpression->Evaluate(lg, config, target, nullptr, nullptr, lang);
65
66   auto it = outputFiles.find(outputFileName);
67
68   if (it != outputFiles.end()) {
69     if (it->second == outputContent) {
70       return;
71     }
72     std::ostringstream e;
73     e << "Evaluation file to be written multiple times with different "
74          "content. "
75          "This is generally caused by the content evaluating the "
76          "configuration type, language, or location of object files:\n "
77       << outputFileName;
78     lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
79     return;
80   }
81
82   lg->GetMakefile()->AddCMakeOutputFile(outputFileName);
83   this->Files.push_back(outputFileName);
84   outputFiles[outputFileName] = outputContent;
85
86   bool openWithBinaryFlag = false;
87   if (!this->NewLineCharacter.empty()) {
88     openWithBinaryFlag = true;
89   }
90   cmGeneratedFileStream fout;
91   fout.Open(outputFileName, false, openWithBinaryFlag);
92   if (!fout) {
93     lg->IssueMessage(MessageType::FATAL_ERROR,
94                      "Could not open file for write in copy operation " +
95                        outputFileName);
96     return;
97   }
98   fout.SetCopyIfDifferent(true);
99   std::istringstream iss(outputContent);
100   std::string line;
101   bool hasNewLine = false;
102   while (cmSystemTools::GetLineFromStream(iss, line, &hasNewLine)) {
103     fout << line;
104     if (!this->NewLineCharacter.empty()) {
105       fout << this->NewLineCharacter;
106     } else if (hasNewLine) {
107       // if new line character is not specified, the file will be opened in
108       // text mode. So, "\n" will be translated to the correct newline
109       // ending based on the platform.
110       fout << "\n";
111     }
112   }
113   if (fout.Close() && perm) {
114     cmSystemTools::SetPermissions(outputFileName.c_str(), perm);
115   }
116 }
117
118 void cmGeneratorExpressionEvaluationFile::CreateOutputFile(
119   cmLocalGenerator* lg, std::string const& config)
120 {
121   std::vector<std::string> enabledLanguages;
122   cmGlobalGenerator* gg = lg->GetGlobalGenerator();
123   cmGeneratorTarget* target = lg->FindGeneratorTargetToUse(this->Target);
124   gg->GetEnabledLanguages(enabledLanguages);
125
126   for (std::string const& le : enabledLanguages) {
127     std::string const name = this->GetOutputFileName(lg, target, config, le);
128     cmSourceFile* sf = lg->GetMakefile()->GetOrCreateGeneratedSource(name);
129
130     // Tell the build system generators that there is no build rule
131     // to generate the file.
132     sf->SetProperty("__CMAKE_GENERATED_BY_CMAKE", "1");
133
134     gg->SetFilenameTargetDepends(
135       sf, this->OutputFileExpr->GetSourceSensitiveTargets());
136   }
137 }
138
139 void cmGeneratorExpressionEvaluationFile::Generate(cmLocalGenerator* lg)
140 {
141   std::string inputContent;
142   if (this->InputIsContent) {
143     inputContent = this->Input;
144   } else {
145     const std::string inputFileName = this->GetInputFileName(lg);
146     lg->GetMakefile()->AddCMakeDependFile(inputFileName);
147     if (!this->Permissions) {
148       cmSystemTools::GetPermissions(inputFileName.c_str(), this->Permissions);
149     }
150     cmsys::ifstream fin(inputFileName.c_str());
151     if (!fin) {
152       std::ostringstream e;
153       e << "Evaluation file \"" << inputFileName << "\" cannot be read.";
154       lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
155       return;
156     }
157
158     std::string line;
159     std::string sep;
160     while (cmSystemTools::GetLineFromStream(fin, line)) {
161       inputContent += sep + line;
162       sep = "\n";
163     }
164     inputContent += sep;
165   }
166
167   cmListFileBacktrace lfbt = this->OutputFileExpr->GetBacktrace();
168   cmGeneratorExpression contentGE(lfbt);
169   std::unique_ptr<cmCompiledGeneratorExpression> inputExpression =
170     contentGE.Parse(inputContent);
171
172   std::map<std::string, std::string> outputFiles;
173
174   std::vector<std::string> allConfigs =
175     lg->GetMakefile()->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
176
177   std::vector<std::string> enabledLanguages;
178   cmGlobalGenerator* gg = lg->GetGlobalGenerator();
179   gg->GetEnabledLanguages(enabledLanguages);
180
181   for (std::string const& le : enabledLanguages) {
182     for (std::string const& li : allConfigs) {
183       this->Generate(lg, li, le, inputExpression.get(), outputFiles,
184                      this->Permissions);
185       if (cmSystemTools::GetFatalErrorOccurred()) {
186         return;
187       }
188     }
189   }
190 }
191
192 std::string cmGeneratorExpressionEvaluationFile::GetInputFileName(
193   cmLocalGenerator* lg)
194 {
195   std::string inputFileName = this->Input;
196
197   if (cmSystemTools::FileIsFullPath(inputFileName)) {
198     inputFileName = cmSystemTools::CollapseFullPath(inputFileName);
199   } else {
200     inputFileName = this->FixRelativePath(inputFileName, PathForInput, lg);
201   }
202
203   return inputFileName;
204 }
205
206 std::string cmGeneratorExpressionEvaluationFile::GetOutputFileName(
207   cmLocalGenerator* lg, cmGeneratorTarget* target, const std::string& config,
208   const std::string& lang)
209 {
210   std::string outputFileName =
211     this->OutputFileExpr->Evaluate(lg, config, target, nullptr, nullptr, lang);
212
213   if (cmSystemTools::FileIsFullPath(outputFileName)) {
214     outputFileName = cmSystemTools::CollapseFullPath(outputFileName);
215   } else {
216     outputFileName = this->FixRelativePath(outputFileName, PathForOutput, lg);
217   }
218
219   return outputFileName;
220 }
221
222 std::string cmGeneratorExpressionEvaluationFile::FixRelativePath(
223   std::string const& relativePath, PathRole role, cmLocalGenerator* lg)
224 {
225   std::string resultPath;
226   switch (this->PolicyStatusCMP0070) {
227     case cmPolicies::WARN: {
228       std::string arg;
229       switch (role) {
230         case PathForInput:
231           arg = "INPUT";
232           break;
233         case PathForOutput:
234           arg = "OUTPUT";
235           break;
236       }
237       std::ostringstream w;
238       /* clang-format off */
239       w <<
240         cmPolicies::GetPolicyWarning(cmPolicies::CMP0070) << "\n"
241         "file(GENERATE) given relative " << arg << " path:\n"
242         "  " << relativePath << "\n"
243         "This is not defined behavior unless CMP0070 is set to NEW.  "
244         "For compatibility with older versions of CMake, the previous "
245         "undefined behavior will be used."
246         ;
247       /* clang-format on */
248       lg->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
249     }
250       CM_FALLTHROUGH;
251     case cmPolicies::OLD:
252       // OLD behavior is to use the relative path unchanged,
253       // which ends up being used relative to the working dir.
254       resultPath = relativePath;
255       break;
256     case cmPolicies::REQUIRED_IF_USED:
257     case cmPolicies::REQUIRED_ALWAYS:
258     case cmPolicies::NEW:
259       // NEW behavior is to interpret the relative path with respect
260       // to the current source or binary directory.
261       switch (role) {
262         case PathForInput:
263           resultPath = cmSystemTools::CollapseFullPath(
264             relativePath, lg->GetCurrentSourceDirectory());
265           break;
266         case PathForOutput:
267           resultPath = cmSystemTools::CollapseFullPath(
268             relativePath, lg->GetCurrentBinaryDirectory());
269           break;
270       }
271       break;
272   }
273   return resultPath;
274 }