/
commandline.cpp
449 lines (384 loc) · 11 KB
/
commandline.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/*
* The Doomsday Engine Project -- libdeng2
*
* Copyright (c) 2009, 2012 Jaakko Keränen <jaakko.keranen@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include "de/CommandLine"
#include "de/String"
#include "de/Log"
#include <QFile>
#include <QDir>
#include <QProcess>
#include <QDebug>
#include <fstream>
#include <sstream>
#include <cctype>
using namespace de;
struct CommandLine::Instance
{
QDir initialDir;
typedef std::vector<std::string*> Arguments;
Arguments arguments;
typedef std::vector<const char*> ArgumentPointers;
ArgumentPointers pointers;
typedef std::vector<String> ArgumentStrings;
typedef std::map<std::string, ArgumentStrings> Aliases;
Aliases aliases;
Instance()
{
initialDir = QDir::current();
}
~Instance()
{
clear();
}
void clear()
{
DENG2_FOR_EACH(i, arguments, Arguments::iterator) delete *i;
arguments.clear();
pointers.clear();
pointers.push_back(0);
}
void appendArg(const char* cStr)
{
arguments.push_back(new std::string(cStr));
if(pointers.empty())
{
pointers.push_back(arguments.back()->c_str());
pointers.push_back(0); // Keep null-terminated.
}
else
{
// Insert before the NULL.
pointers.insert(pointers.end() - 1, arguments.back()->c_str());
}
DENG2_ASSERT(pointers.back() == 0);
}
void insert(duint pos, const String& arg)
{
if(pos > arguments.size())
{
/// @throw OutOfRangeError @a pos is out of range.
throw OutOfRangeError("CommandLine::insert", "Index out of range");
}
arguments.insert(arguments.begin() + pos, new std::string(arg.toStdString()));
pointers.insert(pointers.begin() + pos, arguments[pos]->c_str());
DENG2_ASSERT(pointers.back() == 0);
}
void remove(duint pos)
{
if(pos >= arguments.size())
{
/// @throw OutOfRangeError @a pos is out of range.
throw OutOfRangeError("CommandLine::remove", "Index out of range");
}
delete arguments[pos];
arguments.erase(arguments.begin() + pos);
pointers.erase(pointers.begin() + pos);
DENG2_ASSERT(pointers.back() == 0);
}
};
CommandLine::CommandLine(int argc, char** v)
{
d = new Instance;
for(int i = 0; i < argc; ++i)
{
if(v[i][0] == '@')
{
// This is a response file or something else that requires parsing.
parseResponseFile(v[i] + 1);
}
else
{
d->appendArg(v[i]);
}
}
}
CommandLine::CommandLine(const CommandLine& other)
{
d = new Instance;
DENG2_FOR_EACH(i, other.d->arguments, Instance::Arguments::const_iterator)
{
d->appendArg((*i)->c_str());
}
}
CommandLine::~CommandLine()
{
delete d;
}
dint CommandLine::count() const
{
return d->arguments.size();
}
void CommandLine::clear()
{
d->clear();
}
void CommandLine::append(const String& arg)
{
d->appendArg(arg.toStdString().c_str());
}
void CommandLine::insert(duint pos, const String& arg)
{
d->insert(pos, arg);
}
void CommandLine::remove(duint pos)
{
d->remove(pos);
}
dint CommandLine::check(const String& arg, dint numParams) const
{
// Do a search for arg.
Instance::Arguments::const_iterator i = d->arguments.begin();
for(; i != d->arguments.end() && !matches(arg, String::fromStdString(**i)); ++i) {}
if(i == d->arguments.end())
{
// Not found.
return 0;
}
// It was found, check for the number of non-option parameters.
Instance::Arguments::const_iterator k = i;
while(numParams-- > 0)
{
if(++k == d->arguments.end() || isOption(String::fromStdString(**k)))
{
// Ran out of arguments, or encountered an option.
return 0;
}
}
return i - d->arguments.begin();
}
bool CommandLine::getParameter(const String& arg, String& param) const
{
dint pos = check(arg, 1);
if(pos > 0)
{
param = at(pos + 1);
return true;
}
return false;
}
dint CommandLine::has(const String& arg) const
{
dint howMany = 0;
DENG2_FOR_EACH(i, d->arguments, Instance::Arguments::const_iterator)
{
if(matches(arg, String::fromStdString(**i)))
{
howMany++;
}
}
return howMany;
}
bool CommandLine::isOption(duint pos) const
{
if(pos >= d->arguments.size())
{
/// @throw OutOfRangeError @a pos is out of range.
throw OutOfRangeError("CommandLine::isOption", "Index out of range");
}
DENG2_ASSERT(!d->arguments[pos]->empty());
return isOption(String::fromStdString(*d->arguments[pos]));
}
bool CommandLine::isOption(const String& arg)
{
return !(arg.empty() || arg[0] != '-');
}
const String CommandLine::at(duint pos) const
{
return String::fromStdString(*d->arguments.at(pos));
}
const char* const* CommandLine::argv() const
{
DENG2_ASSERT(*d->pointers.rbegin() == 0);
return &d->pointers[0];
}
void CommandLine::makeAbsolutePath(duint pos)
{
if(pos >= d->arguments.size())
{
/// @throw OutOfRangeError @a pos is out of range.
throw OutOfRangeError("CommandLine::makeAbsolutePath", "Index out of range");
}
std::string* arg = d->arguments[pos];
if(!isOption(pos) && !QDir::isAbsolutePath(arg->c_str()) &&
!String::fromStdString(*arg).startsWith("}"))
{
// The path expansion logic here should match the native shell's behavior.
QDir oldDir = QDir::current();
QDir::setCurrent(d->initialDir.path());
QDir dir(arg->c_str());
#ifdef UNIX
if(dir.path().startsWith("~/"))
{
dir.setPath(QDir::home().filePath(dir.path().mid(2)));
}
#endif
*arg = dir.absolutePath().toStdString();
d->pointers[pos] = arg->c_str();
LOG_DEBUG("Argument %i converted to absolute path: \"%s\"") << pos << d->pointers[pos];
// Restore previous current directory.
QDir::setCurrent(oldDir.path());
}
}
void CommandLine::parseResponseFile(const String& nativePath)
{
/// @todo Symbols like ~ should be expanded in @a nativePath.
QFile response(nativePath);
if(response.open(QFile::ReadOnly | QFile::Text))
{
parse(QString::fromUtf8(response.readAll().constData()));
}
else
{
qWarning() << "Failed to open response file:" << nativePath;
}
}
void CommandLine::parse(const String& cmdLine)
{
String::const_iterator i = cmdLine.begin();
// This is unset if we encounter a terminator token.
bool isDone = false;
// Are we currently inside quotes?
bool quote = false;
while(i != cmdLine.end() && !isDone)
{
// Skip initial whitespace.
String::skipSpace(i, cmdLine.end());
// Check for response files.
bool isResponse = false;
if(*i == '@')
{
isResponse = true;
String::skipSpace(++i, cmdLine.end());
}
String word;
while(i != cmdLine.end() && (quote || !(*i).isSpace()))
{
bool copyChar = true;
if(!quote)
{
// We're not inside quotes.
if(*i == '\"') // Quote begins.
{
quote = true;
copyChar = false;
}
}
else
{
// We're inside quotes.
if(*i == '\"') // Quote ends.
{
if(i + 1 != cmdLine.end() && *(i + 1) == '\"') // Doubles?
{
// Normal processing, but output only one quote.
i++;
}
else
{
quote = false;
copyChar = false;
}
}
}
if(copyChar)
{
word.push_back(*i);
}
i++;
}
// Word has been extracted, examine it.
if(isResponse) // Response file?
{
parseResponseFile(word);
}
else if(word == "--") // End of arguments.
{
isDone = true;
}
else if(!word.empty()) // Make sure there *is* a word.
{
d->appendArg(word.toStdString().c_str());
}
}
}
void CommandLine::alias(const String& full, const String& alias)
{
d->aliases[full.toStdString()].push_back(alias);
}
bool CommandLine::matches(const String& full, const String& fullOrAlias) const
{
if(!full.compareWithoutCase(fullOrAlias))
{
// They are, in fact, the same.
return true;
}
Instance::Aliases::const_iterator found = d->aliases.find(full.toStdString());
if(found != d->aliases.end())
{
DENG2_FOR_EACH(i, found->second, Instance::ArgumentStrings::const_iterator)
{
if(!i->compareWithoutCase(fullOrAlias))
{
// Found it among the aliases.
return true;
}
}
}
return false;
}
void CommandLine::execute(char** /*envs*/) const
{
qDebug("CommandLine: should call QProcess to execute!\n");
/*
#ifdef Q_OS_UNIX
// Fork and execute new file.
pid_t result = fork();
if(!result)
{
// Here we go in the child process.
printf("Child loads %s...\n", _pointers[0]);
execve(_pointers[0], const_cast<char* const*>(argv()), const_cast<char* const*>(envs));
}
else
{
if(result < 0)
{
perror("CommandLine::execute");
}
}
#endif
#ifdef WIN32
String quotedCmdLine;
FOR_EACH(i, _arguments, Arguments::const_iterator)
{
quotedCmdLine += "\"" + *i + "\" ";
}
STARTUPINFO startupInfo;
PROCESS_INFORMATION processInfo;
ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
ZeroMemory(&processInfo, sizeof(processInfo));
if(!CreateProcess(_pointers[0], const_cast<char*>(quotedCmdLine.c_str()),
NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo))
{
/// @throw ExecuteError The system call to start a new process failed.
throw ExecuteError("CommandLine::execute", "Could not create process");
}
#endif
*/
}