Coverage Report

Created: 2026-04-29 07:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Source/cmSetCommand.cxx
Line
Count
Source
1
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2
   file LICENSE.rst or https://cmake.org/licensing for details.  */
3
#include "cmSetCommand.h"
4
5
#include <algorithm>
6
7
#include <cm/optional>
8
#include <cm/string_view>
9
#include <cmext/string_view>
10
11
#include "cmArgumentParser.h"
12
#include "cmArgumentParserTypes.h"
13
#include "cmDiagnostics.h"
14
#include "cmExecutionStatus.h"
15
#include "cmList.h"
16
#include "cmMakefile.h"
17
#include "cmRange.h"
18
#include "cmState.h"
19
#include "cmStateTypes.h"
20
#include "cmStringAlgorithms.h"
21
#include "cmSystemTools.h"
22
#include "cmValue.h"
23
24
namespace {
25
void setENV(std::string const& var, cm::string_view val)
26
0
{
27
#ifdef _WIN32
28
  if (val.empty()) {
29
    // FIXME(#27285): On Windows, PutEnv previously treated empty as unset.
30
    // KWSys was fixed, but we need to retain the behavior for compatibility.
31
    cmSystemTools::UnPutEnv(var);
32
    return;
33
  }
34
#endif
35
0
  cmSystemTools::PutEnv(cmStrCat(var, '=', val));
36
0
}
37
}
38
39
// cmSetCommand
40
bool cmSetCommand(std::vector<std::string> const& args,
41
                  cmExecutionStatus& status)
42
0
{
43
0
  if (args.empty()) {
44
0
    status.SetError("called with incorrect number of arguments");
45
0
    return false;
46
0
  }
47
48
0
  auto const& variable = args[0]; // VAR is always first
49
  // watch for ENV{} signature
50
0
  if (cmHasLiteralPrefix(variable, "ENV{") && variable.size() > 5) {
51
    // what is the variable name
52
0
    auto const& varName = variable.substr(4, variable.size() - 5);
53
54
    // what is the current value if any
55
0
    std::string currValue;
56
0
    bool const currValueSet = cmSystemTools::GetEnv(varName, currValue);
57
58
    // will it be set to something, then set it
59
0
    if (args.size() > 1 && !args[1].empty()) {
60
      // but only if it is different from current value
61
0
      if (!currValueSet || currValue != args[1]) {
62
0
        setENV(varName, args[1]);
63
0
      }
64
      // if there's extra arguments, warn user
65
      // that they are ignored by this command.
66
0
      if (args.size() > 2) {
67
0
        status.GetMakefile().IssueDiagnostic(
68
0
          cmDiagnostics::CMD_AUTHOR,
69
0
          cmStrCat("Only the first value argument is used when setting "
70
0
                   "an environment variable.  Argument '",
71
0
                   args[2] + "' and later are unused."));
72
0
      }
73
0
      return true;
74
0
    }
75
76
    // if it will be cleared, then clear it if it isn't already clear
77
0
    if (currValueSet) {
78
0
      setENV(varName, ""_s);
79
0
    }
80
0
    return true;
81
0
  }
82
83
  // watch for CACHE{} signature
84
0
  if (cmHasLiteralPrefix(variable, "CACHE{") && variable.size() > 7 &&
85
0
      cmHasSuffix(variable, '}')) {
86
    // what is the variable name
87
0
    auto const& varName = variable.substr(6, variable.size() - 7);
88
    // VALUE handling
89
0
    auto valueArg = std::find(args.cbegin() + 1, args.cend(), "VALUE");
90
0
    if (valueArg == args.cend()) {
91
0
      status.SetError("Required argument 'VALUE' is missing.");
92
0
      return false;
93
0
    }
94
0
    auto value = cmMakeRange(valueArg + 1, args.cend());
95
    // Handle options
96
0
    struct Arguments : public ArgumentParser::ParseResult
97
0
    {
98
0
      ArgumentParser::Continue validateTypeValue(cm::string_view type)
99
0
      {
100
0
        if (!cmState::StringToCacheEntryType(std::string{ type },
101
0
                                             this->Type)) {
102
0
          this->AddKeywordError(
103
0
            "TYPE"_s, cmStrCat("  invalid value: \""_s, type, "\"\n"_s));
104
0
        }
105
0
        return ArgumentParser::Continue::No;
106
0
      }
107
0
      cmStateEnums::CacheEntryType Type = cmStateEnums::UNINITIALIZED;
108
0
      cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>> Help;
109
0
      bool Force = false;
110
0
    };
111
0
    static auto const optionsParser =
112
0
      cmArgumentParser<Arguments>{}
113
0
        .Bind("TYPE"_s, &Arguments::validateTypeValue)
114
0
        .Bind("HELP"_s, &Arguments::Help)
115
0
        .Bind("FORCE"_s, &Arguments::Force);
116
0
    std::vector<std::string> unrecognizedArguments;
117
0
    auto parsedArgs = optionsParser.Parse(
118
0
      cmMakeRange(args.cbegin() + 1, valueArg), &unrecognizedArguments);
119
0
    if (!unrecognizedArguments.empty()) {
120
0
      status.SetError(cmStrCat("Called with unsupported argument(s): ",
121
0
                               cmJoin(unrecognizedArguments, ",  "_s), '.'));
122
0
      return false;
123
0
    }
124
0
    if (parsedArgs.MaybeReportError(status.GetMakefile())) {
125
0
      return false;
126
0
    }
127
128
    // see if this is already in the cache
129
0
    cmState* state = status.GetMakefile().GetState();
130
0
    cmValue existingValue = state->GetCacheEntryValue(varName);
131
0
    cmStateEnums::CacheEntryType existingType =
132
0
      state->GetCacheEntryType(varName);
133
0
    if (parsedArgs.Type == cmStateEnums::UNINITIALIZED) {
134
0
      parsedArgs.Type = existingType == cmStateEnums::UNINITIALIZED
135
0
        ? cmStateEnums::STRING
136
0
        : existingType;
137
0
    }
138
0
    std::string help = parsedArgs.Help
139
0
      ? cmJoin(*parsedArgs.Help, "")
140
0
      : *state->GetCacheEntryProperty(varName, "HELPSTRING");
141
0
    if (existingValue && existingType != cmStateEnums::UNINITIALIZED) {
142
      // if the set is trying to CACHE the value but the value
143
      // is already in the cache and the type is not internal
144
      // then leave now without setting any definitions in the cache
145
      // or the makefile
146
0
      if (parsedArgs.Type != cmStateEnums::INTERNAL && !parsedArgs.Force) {
147
0
        return true;
148
0
      }
149
0
    }
150
151
0
    status.GetMakefile().AddCacheDefinition(
152
0
      varName,
153
0
      valueArg == args.cend() ? *existingValue : cmList::to_string(value),
154
0
      help, parsedArgs.Type, parsedArgs.Force);
155
0
    return true;
156
0
  }
157
158
  // SET (VAR) // Removes the definition of VAR.
159
0
  if (args.size() == 1) {
160
0
    status.GetMakefile().RemoveDefinition(variable);
161
0
    return true;
162
0
  }
163
  // SET (VAR PARENT_SCOPE) // Removes the definition of VAR
164
  // in the parent scope.
165
0
  if (args.size() == 2 && args.back() == "PARENT_SCOPE") {
166
0
    status.GetMakefile().RaiseScope(variable, nullptr);
167
0
    return true;
168
0
  }
169
170
  // here are the remaining options
171
  //  SET (VAR value )
172
  //  SET (VAR value PARENT_SCOPE)
173
  //  SET (VAR CACHE TYPE "doc String" [FORCE])
174
  //  SET (VAR value CACHE TYPE "doc string" [FORCE])
175
0
  std::string value;  // optional
176
0
  bool cache = false; // optional
177
0
  bool force = false; // optional
178
0
  bool parentScope = false;
179
0
  cmStateEnums::CacheEntryType type =
180
0
    cmStateEnums::STRING; // required if cache
181
0
  cmValue docstring;      // required if cache
182
183
0
  unsigned int ignoreLastArgs = 0;
184
  // look for PARENT_SCOPE argument
185
0
  if (args.size() > 1 && args.back() == "PARENT_SCOPE") {
186
0
    parentScope = true;
187
0
    ignoreLastArgs++;
188
0
  } else {
189
    // look for FORCE argument
190
0
    if (args.size() > 4 && args.back() == "FORCE") {
191
0
      force = true;
192
0
      ignoreLastArgs++;
193
0
    }
194
195
    // check for cache signature
196
0
    if (args.size() > 3 &&
197
0
        args[args.size() - 3 - (force ? 1 : 0)] == "CACHE") {
198
0
      cache = true;
199
0
      ignoreLastArgs += 3;
200
0
    }
201
0
  }
202
203
  // collect any values into a single semi-colon separated value list
204
0
  value =
205
0
    cmList::to_string(cmMakeRange(args).advance(1).retreat(ignoreLastArgs));
206
207
0
  if (parentScope) {
208
0
    status.GetMakefile().RaiseScope(variable, value.c_str());
209
0
    return true;
210
0
  }
211
212
  // we should be nice and try to catch some simple screwups if the last or
213
  // next to last args are CACHE then they screwed up.  If they used FORCE
214
  // without CACHE they screwed up
215
0
  if (args.back() == "CACHE") {
216
0
    status.SetError(
217
0
      "given invalid arguments for CACHE mode: missing type and docstring");
218
0
    return false;
219
0
  }
220
0
  if (args.size() > 1 && args[args.size() - 2] == "CACHE") {
221
0
    status.SetError(
222
0
      "given invalid arguments for CACHE mode: missing type or docstring");
223
0
    return false;
224
0
  }
225
0
  if (force && !cache) {
226
0
    status.SetError("given invalid arguments: FORCE specified without CACHE");
227
0
    return false;
228
0
  }
229
230
0
  if (cache) {
231
0
    std::string::size_type cacheStart = args.size() - 3 - (force ? 1 : 0);
232
0
    if (!cmState::StringToCacheEntryType(args[cacheStart + 1], type)) {
233
0
      status.GetMakefile().IssueDiagnostic(cmDiagnostics::CMD_AUTHOR,
234
0
                                           cmStrCat("implicitly converting '",
235
0
                                                    args[cacheStart + 1],
236
0
                                                    "' to 'STRING' type."));
237
      // Setting this may not be required, since it's
238
      // initialized as a string. Keeping this here to
239
      // ensure that the type is actually converting to a string.
240
0
      type = cmStateEnums::STRING;
241
0
    }
242
0
    docstring = cmValue{ args[cacheStart + 2] };
243
0
  }
244
245
  // see if this is already in the cache
246
0
  cmState* state = status.GetMakefile().GetState();
247
0
  cmValue existingValue = state->GetCacheEntryValue(variable);
248
0
  if (existingValue &&
249
0
      (state->GetCacheEntryType(variable) != cmStateEnums::UNINITIALIZED)) {
250
    // if the set is trying to CACHE the value but the value
251
    // is already in the cache and the type is not internal
252
    // then leave now without setting any definitions in the cache
253
    // or the makefile
254
0
    if (cache && type != cmStateEnums::INTERNAL && !force) {
255
0
      return true;
256
0
    }
257
0
  }
258
259
  // if it is meant to be in the cache then define it in the cache
260
0
  if (cache) {
261
0
    status.GetMakefile().AddCacheDefinition(variable, cmValue{ value },
262
0
                                            docstring, type, force);
263
0
  } else {
264
    // add the definition
265
0
    status.GetMakefile().AddDefinition(variable, value);
266
0
  }
267
0
  return true;
268
0
}