Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: GDAL
4 : * Purpose: GDALAlgorithm class
5 : * Author: Even Rouault <even dot rouault at spatialys.com>
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 2024, Even Rouault <even dot rouault at spatialys.com>
9 : *
10 : * SPDX-License-Identifier: MIT
11 : ****************************************************************************/
12 :
13 : #include "cpl_port.h"
14 : #include "cpl_conv.h"
15 : #include "cpl_enumerate.h"
16 : #include "cpl_error.h"
17 : #include "cpl_error_internal.h"
18 : #include "cpl_json.h"
19 : #include "cpl_levenshtein.h"
20 : #include "cpl_minixml.h"
21 : #include "cpl_multiproc.h"
22 :
23 : #include "gdalalgorithm.h"
24 : #include "gdalalg_abstract_pipeline.h"
25 : #include "gdal_priv.h"
26 : #include "gdal_thread_pool.h"
27 : #include "memdataset.h"
28 : #include "ogrsf_frmts.h"
29 : #include "ogr_p.h"
30 : #include "ogr_spatialref.h"
31 : #include "vrtdataset.h"
32 :
33 : #include <algorithm>
34 : #include <cassert>
35 : #include <cerrno>
36 : #include <cmath>
37 : #include <cstdlib>
38 : #include <limits>
39 : #include <map>
40 : #include <type_traits>
41 : #include <string_view>
42 : #include <regex>
43 :
44 : #ifndef _
45 : #define _(x) (x)
46 : #endif
47 :
48 : constexpr const char *GDAL_ARG_NAME_OUTPUT_DATA_TYPE = "output-data-type";
49 :
50 : constexpr const char *GDAL_ARG_NAME_OUTPUT_OPEN_OPTION = "output-open-option";
51 :
52 : constexpr const char *GDAL_ARG_NAME_BAND = "band";
53 :
54 : //! @cond Doxygen_Suppress
55 : struct GDALAlgorithmArgHS
56 : {
57 : GDALAlgorithmArg *ptr = nullptr;
58 :
59 361150 : explicit GDALAlgorithmArgHS(GDALAlgorithmArg *arg) : ptr(arg)
60 : {
61 361150 : }
62 : };
63 :
64 : //! @endcond
65 :
66 : //! @cond Doxygen_Suppress
67 : struct GDALArgDatasetValueHS
68 : {
69 : GDALArgDatasetValue val{};
70 : GDALArgDatasetValue *ptr = nullptr;
71 :
72 1 : GDALArgDatasetValueHS() : ptr(&val)
73 : {
74 1 : }
75 :
76 3412 : explicit GDALArgDatasetValueHS(GDALArgDatasetValue *arg) : ptr(arg)
77 : {
78 3412 : }
79 :
80 : GDALArgDatasetValueHS(const GDALArgDatasetValueHS &) = delete;
81 : GDALArgDatasetValueHS &operator=(const GDALArgDatasetValueHS &) = delete;
82 : };
83 :
84 : //! @endcond
85 :
86 : /************************************************************************/
87 : /* GDALAlgorithmArgTypeIsList() */
88 : /************************************************************************/
89 :
90 462811 : bool GDALAlgorithmArgTypeIsList(GDALAlgorithmArgType type)
91 : {
92 462811 : switch (type)
93 : {
94 304770 : case GAAT_BOOLEAN:
95 : case GAAT_STRING:
96 : case GAAT_INTEGER:
97 : case GAAT_REAL:
98 : case GAAT_DATASET:
99 304770 : break;
100 :
101 158041 : case GAAT_STRING_LIST:
102 : case GAAT_INTEGER_LIST:
103 : case GAAT_REAL_LIST:
104 : case GAAT_DATASET_LIST:
105 158041 : return true;
106 : }
107 :
108 304770 : return false;
109 : }
110 :
111 : /************************************************************************/
112 : /* GDALAlgorithmArgTypeName() */
113 : /************************************************************************/
114 :
115 5703 : const char *GDALAlgorithmArgTypeName(GDALAlgorithmArgType type)
116 : {
117 5703 : switch (type)
118 : {
119 1389 : case GAAT_BOOLEAN:
120 1389 : break;
121 1564 : case GAAT_STRING:
122 1564 : return "string";
123 392 : case GAAT_INTEGER:
124 392 : return "integer";
125 477 : case GAAT_REAL:
126 477 : return "real";
127 266 : case GAAT_DATASET:
128 266 : return "dataset";
129 1093 : case GAAT_STRING_LIST:
130 1093 : return "string_list";
131 85 : case GAAT_INTEGER_LIST:
132 85 : return "integer_list";
133 221 : case GAAT_REAL_LIST:
134 221 : return "real_list";
135 216 : case GAAT_DATASET_LIST:
136 216 : return "dataset_list";
137 : }
138 :
139 1389 : return "boolean";
140 : }
141 :
142 : /************************************************************************/
143 : /* GDALAlgorithmArgDatasetTypeName() */
144 : /************************************************************************/
145 :
146 29153 : std::string GDALAlgorithmArgDatasetTypeName(GDALArgDatasetType type)
147 : {
148 29153 : std::string ret;
149 29153 : if ((type & GDAL_OF_RASTER) != 0)
150 17415 : ret = "raster";
151 29153 : if ((type & GDAL_OF_VECTOR) != 0)
152 : {
153 12432 : if (!ret.empty())
154 : {
155 1806 : if ((type & GDAL_OF_MULTIDIM_RASTER) != 0)
156 294 : ret += ", ";
157 : else
158 1512 : ret += " or ";
159 : }
160 12432 : ret += "vector";
161 : }
162 29153 : if ((type & GDAL_OF_MULTIDIM_RASTER) != 0)
163 : {
164 1331 : if (!ret.empty())
165 : {
166 436 : ret += " or ";
167 : }
168 1331 : ret += "multidimensional raster";
169 : }
170 29153 : return ret;
171 : }
172 :
173 : /************************************************************************/
174 : /* GDALAlgorithmArgDecl() */
175 : /************************************************************************/
176 :
177 : // cppcheck-suppress uninitMemberVar
178 371013 : GDALAlgorithmArgDecl::GDALAlgorithmArgDecl(const std::string &longName,
179 : char chShortName,
180 : const std::string &description,
181 371013 : GDALAlgorithmArgType type)
182 : : m_longName(longName),
183 371013 : m_shortName(chShortName ? std::string(&chShortName, 1) : std::string()),
184 : m_description(description), m_type(type),
185 742026 : m_metaVar(CPLString(m_type == GAAT_BOOLEAN ? std::string() : longName)
186 371013 : .toupper()),
187 1113040 : m_maxCount(GDALAlgorithmArgTypeIsList(type) ? UNBOUNDED : 1)
188 : {
189 371013 : if (m_type == GAAT_BOOLEAN)
190 : {
191 157316 : m_defaultValue = false;
192 : }
193 371013 : }
194 :
195 : /************************************************************************/
196 : /* GDALAlgorithmArgDecl::SetMinCount() */
197 : /************************************************************************/
198 :
199 20413 : GDALAlgorithmArgDecl &GDALAlgorithmArgDecl::SetMinCount(int count)
200 : {
201 20413 : if (!GDALAlgorithmArgTypeIsList(m_type))
202 : {
203 1 : CPLError(CE_Failure, CPLE_NotSupported,
204 : "SetMinCount() illegal on scalar argument '%s'",
205 1 : GetName().c_str());
206 : }
207 : else
208 : {
209 20412 : m_minCount = count;
210 : }
211 20413 : return *this;
212 : }
213 :
214 : /************************************************************************/
215 : /* GDALAlgorithmArgDecl::SetMaxCount() */
216 : /************************************************************************/
217 :
218 19588 : GDALAlgorithmArgDecl &GDALAlgorithmArgDecl::SetMaxCount(int count)
219 : {
220 19588 : if (!GDALAlgorithmArgTypeIsList(m_type))
221 : {
222 1 : CPLError(CE_Failure, CPLE_NotSupported,
223 : "SetMaxCount() illegal on scalar argument '%s'",
224 1 : GetName().c_str());
225 : }
226 : else
227 : {
228 19587 : m_maxCount = count;
229 : }
230 19588 : return *this;
231 : }
232 :
233 : /************************************************************************/
234 : /* GDALAlgorithmArg::~GDALAlgorithmArg() */
235 : /************************************************************************/
236 :
237 : GDALAlgorithmArg::~GDALAlgorithmArg() = default;
238 :
239 : /************************************************************************/
240 : /* GDALAlgorithmArg::Set() */
241 : /************************************************************************/
242 :
243 1310 : bool GDALAlgorithmArg::Set(bool value)
244 : {
245 1310 : if (m_decl.GetType() != GAAT_BOOLEAN)
246 : {
247 14 : CPLError(
248 : CE_Failure, CPLE_AppDefined,
249 : "Calling Set(bool) on argument '%s' of type %s is not supported",
250 7 : GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
251 7 : return false;
252 : }
253 1303 : return SetInternal(value);
254 : }
255 :
256 4485 : bool GDALAlgorithmArg::ProcessString(std::string &value) const
257 : {
258 4536 : if (m_decl.IsReadFromFileAtSyntaxAllowed() && !value.empty() &&
259 51 : value.front() == '@')
260 : {
261 2 : GByte *pabyData = nullptr;
262 2 : if (VSIIngestFile(nullptr, value.c_str() + 1, &pabyData, nullptr,
263 2 : 10 * 1024 * 1024))
264 : {
265 : // Remove UTF-8 BOM
266 1 : size_t offset = 0;
267 1 : if (pabyData[0] == 0xEF && pabyData[1] == 0xBB &&
268 1 : pabyData[2] == 0xBF)
269 : {
270 1 : offset = 3;
271 : }
272 1 : value = reinterpret_cast<const char *>(pabyData + offset);
273 1 : VSIFree(pabyData);
274 : }
275 : else
276 : {
277 1 : return false;
278 : }
279 : }
280 :
281 4484 : if (m_decl.IsRemoveSQLCommentsEnabled())
282 50 : value = CPLRemoveSQLComments(value);
283 :
284 4484 : return true;
285 : }
286 :
287 4521 : bool GDALAlgorithmArg::Set(const std::string &value)
288 : {
289 4521 : switch (m_decl.GetType())
290 : {
291 9 : case GAAT_BOOLEAN:
292 17 : if (EQUAL(value.c_str(), "1") || EQUAL(value.c_str(), "TRUE") ||
293 17 : EQUAL(value.c_str(), "YES") || EQUAL(value.c_str(), "ON"))
294 : {
295 4 : return Set(true);
296 : }
297 5 : else if (EQUAL(value.c_str(), "0") ||
298 4 : EQUAL(value.c_str(), "FALSE") ||
299 9 : EQUAL(value.c_str(), "NO") || EQUAL(value.c_str(), "OFF"))
300 : {
301 4 : return Set(false);
302 : }
303 1 : break;
304 :
305 8 : case GAAT_INTEGER:
306 : case GAAT_INTEGER_LIST:
307 : {
308 8 : errno = 0;
309 8 : char *endptr = nullptr;
310 8 : const auto v = std::strtoll(value.c_str(), &endptr, 10);
311 13 : if (errno == 0 && v >= INT_MIN && v <= INT_MAX &&
312 5 : endptr == value.c_str() + value.size())
313 : {
314 3 : if (m_decl.GetType() == GAAT_INTEGER)
315 3 : return Set(static_cast<int>(v));
316 : else
317 1 : return Set(std::vector<int>{static_cast<int>(v)});
318 : }
319 5 : break;
320 : }
321 :
322 5 : case GAAT_REAL:
323 : case GAAT_REAL_LIST:
324 : {
325 5 : char *endptr = nullptr;
326 5 : const double v = CPLStrtod(value.c_str(), &endptr);
327 5 : if (endptr == value.c_str() + value.size())
328 : {
329 3 : if (m_decl.GetType() == GAAT_REAL)
330 3 : return Set(v);
331 : else
332 1 : return Set(std::vector<double>{v});
333 : }
334 2 : break;
335 : }
336 :
337 4463 : case GAAT_STRING:
338 4463 : break;
339 :
340 8 : case GAAT_STRING_LIST:
341 16 : return Set(std::vector<std::string>{value});
342 :
343 28 : case GAAT_DATASET:
344 28 : return SetDatasetName(value);
345 :
346 0 : case GAAT_DATASET_LIST:
347 : {
348 0 : std::vector<GDALArgDatasetValue> v;
349 0 : v.resize(1);
350 0 : v[0].Set(value);
351 0 : return Set(std::move(v));
352 : }
353 : }
354 :
355 4471 : if (m_decl.GetType() != GAAT_STRING)
356 : {
357 16 : CPLError(CE_Failure, CPLE_AppDefined,
358 : "Calling Set(std::string) on argument '%s' of type %s is not "
359 : "supported",
360 8 : GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
361 8 : return false;
362 : }
363 :
364 4463 : std::string newValue(value);
365 4463 : return ProcessString(newValue) && SetInternal(newValue);
366 : }
367 :
368 892 : bool GDALAlgorithmArg::Set(int value)
369 : {
370 892 : if (m_decl.GetType() == GAAT_BOOLEAN)
371 : {
372 3 : if (value == 1)
373 1 : return Set(true);
374 2 : else if (value == 0)
375 1 : return Set(false);
376 : }
377 889 : else if (m_decl.GetType() == GAAT_REAL)
378 : {
379 3 : return Set(static_cast<double>(value));
380 : }
381 886 : else if (m_decl.GetType() == GAAT_STRING)
382 : {
383 2 : return Set(std::to_string(value));
384 : }
385 884 : else if (m_decl.GetType() == GAAT_INTEGER_LIST)
386 : {
387 1 : return Set(std::vector<int>{value});
388 : }
389 883 : else if (m_decl.GetType() == GAAT_REAL_LIST)
390 : {
391 1 : return Set(std::vector<double>{static_cast<double>(value)});
392 : }
393 882 : else if (m_decl.GetType() == GAAT_STRING_LIST)
394 : {
395 2 : return Set(std::vector<std::string>{std::to_string(value)});
396 : }
397 :
398 882 : if (m_decl.GetType() != GAAT_INTEGER)
399 : {
400 2 : CPLError(
401 : CE_Failure, CPLE_AppDefined,
402 : "Calling Set(int) on argument '%s' of type %s is not supported",
403 1 : GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
404 1 : return false;
405 : }
406 881 : return SetInternal(value);
407 : }
408 :
409 315 : bool GDALAlgorithmArg::Set(double value)
410 : {
411 318 : if (m_decl.GetType() == GAAT_INTEGER && value >= INT_MIN &&
412 318 : value <= INT_MAX && static_cast<int>(value) == value)
413 : {
414 2 : return Set(static_cast<int>(value));
415 : }
416 313 : else if (m_decl.GetType() == GAAT_STRING)
417 : {
418 2 : return Set(std::to_string(value));
419 : }
420 313 : else if (m_decl.GetType() == GAAT_INTEGER_LIST && value >= INT_MIN &&
421 313 : value <= INT_MAX && static_cast<int>(value) == value)
422 : {
423 1 : return Set(std::vector<int>{static_cast<int>(value)});
424 : }
425 310 : else if (m_decl.GetType() == GAAT_REAL_LIST)
426 : {
427 0 : return Set(std::vector<double>{value});
428 : }
429 310 : else if (m_decl.GetType() == GAAT_STRING_LIST)
430 : {
431 2 : return Set(std::vector<std::string>{std::to_string(value)});
432 : }
433 309 : else if (m_decl.GetType() != GAAT_REAL)
434 : {
435 6 : CPLError(
436 : CE_Failure, CPLE_AppDefined,
437 : "Calling Set(double) on argument '%s' of type %s is not supported",
438 3 : GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
439 3 : return false;
440 : }
441 306 : return SetInternal(value);
442 : }
443 :
444 6062 : static bool CheckCanSetDatasetObject(const GDALAlgorithmArg *arg)
445 : {
446 6065 : if (arg->IsOutput() && arg->GetDatasetInputFlags() == GADV_NAME &&
447 3 : arg->GetDatasetOutputFlags() == GADV_OBJECT)
448 : {
449 3 : CPLError(
450 : CE_Failure, CPLE_AppDefined,
451 : "Dataset object '%s' is created by algorithm and cannot be set "
452 : "as an input.",
453 3 : arg->GetName().c_str());
454 3 : return false;
455 : }
456 6059 : else if ((arg->GetDatasetInputFlags() & GADV_OBJECT) == 0)
457 : {
458 8 : CPLError(CE_Failure, CPLE_AppDefined,
459 : "Dataset%s '%s' must be provided by name, not as object.",
460 8 : arg->GetMaxCount() > 1 ? "s" : "", arg->GetName().c_str());
461 4 : return false;
462 : }
463 :
464 6055 : return true;
465 : }
466 :
467 33 : bool GDALAlgorithmArg::Set(GDALDataset *ds)
468 : {
469 58 : if (m_decl.GetType() != GAAT_DATASET &&
470 25 : m_decl.GetType() != GAAT_DATASET_LIST)
471 : {
472 2 : CPLError(CE_Failure, CPLE_AppDefined,
473 : "Calling Set(GDALDataset*, bool) on argument '%s' of type %s "
474 : "is not supported",
475 1 : GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
476 1 : return false;
477 : }
478 32 : if (!CheckCanSetDatasetObject(this))
479 2 : return false;
480 30 : m_explicitlySet = true;
481 30 : if (m_decl.GetType() == GAAT_DATASET)
482 : {
483 6 : auto &val = *std::get<GDALArgDatasetValue *>(m_value);
484 6 : val.Set(ds);
485 : }
486 : else
487 : {
488 24 : CPLAssert(m_decl.GetType() == GAAT_DATASET_LIST);
489 24 : auto &val = *std::get<std::vector<GDALArgDatasetValue> *>(m_value);
490 24 : val.resize(1);
491 24 : val[0].Set(ds);
492 : }
493 30 : return RunAllActions();
494 : }
495 :
496 3 : bool GDALAlgorithmArg::Set(std::unique_ptr<GDALDataset> ds)
497 : {
498 3 : if (m_decl.GetType() != GAAT_DATASET)
499 : {
500 2 : CPLError(CE_Failure, CPLE_AppDefined,
501 : "Calling Set(GDALDataset*, bool) on argument '%s' of type %s "
502 : "is not supported",
503 1 : GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
504 1 : return false;
505 : }
506 2 : if (!CheckCanSetDatasetObject(this))
507 1 : return false;
508 1 : m_explicitlySet = true;
509 1 : auto &val = *std::get<GDALArgDatasetValue *>(m_value);
510 1 : val.Set(std::move(ds));
511 1 : return RunAllActions();
512 : }
513 :
514 646 : bool GDALAlgorithmArg::SetDatasetName(const std::string &name)
515 : {
516 646 : if (m_decl.GetType() != GAAT_DATASET)
517 : {
518 2 : CPLError(CE_Failure, CPLE_AppDefined,
519 : "Calling SetDatasetName() on argument '%s' of type %s is "
520 : "not supported",
521 1 : GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
522 1 : return false;
523 : }
524 645 : m_explicitlySet = true;
525 645 : std::get<GDALArgDatasetValue *>(m_value)->Set(name);
526 645 : return RunAllActions();
527 : }
528 :
529 1110 : bool GDALAlgorithmArg::SetFrom(const GDALArgDatasetValue &other)
530 : {
531 1110 : if (m_decl.GetType() != GAAT_DATASET)
532 : {
533 2 : CPLError(CE_Failure, CPLE_AppDefined,
534 : "Calling SetFrom() on argument '%s' of type %s is "
535 : "not supported",
536 1 : GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
537 1 : return false;
538 : }
539 1109 : if (other.GetDatasetRef() && !CheckCanSetDatasetObject(this))
540 1 : return false;
541 1108 : m_explicitlySet = true;
542 1108 : std::get<GDALArgDatasetValue *>(m_value)->SetFrom(other);
543 1108 : return RunAllActions();
544 : }
545 :
546 1285 : bool GDALAlgorithmArg::Set(const std::vector<std::string> &value)
547 : {
548 1285 : if (m_decl.GetType() == GAAT_INTEGER_LIST)
549 : {
550 3 : std::vector<int> v_i;
551 4 : for (const std::string &s : value)
552 : {
553 3 : errno = 0;
554 3 : char *endptr = nullptr;
555 3 : const auto v = std::strtoll(s.c_str(), &endptr, 10);
556 5 : if (errno == 0 && v >= INT_MIN && v <= INT_MAX &&
557 2 : endptr == s.c_str() + s.size())
558 : {
559 1 : v_i.push_back(static_cast<int>(v));
560 : }
561 : else
562 : {
563 2 : break;
564 : }
565 : }
566 3 : if (v_i.size() == value.size())
567 1 : return Set(v_i);
568 : }
569 1282 : else if (m_decl.GetType() == GAAT_REAL_LIST)
570 : {
571 2 : std::vector<double> v_d;
572 3 : for (const std::string &s : value)
573 : {
574 2 : char *endptr = nullptr;
575 2 : const double v = CPLStrtod(s.c_str(), &endptr);
576 2 : if (endptr == s.c_str() + s.size())
577 : {
578 1 : v_d.push_back(v);
579 : }
580 : else
581 : {
582 1 : break;
583 : }
584 : }
585 2 : if (v_d.size() == value.size())
586 1 : return Set(v_d);
587 : }
588 2558 : else if ((m_decl.GetType() == GAAT_INTEGER ||
589 2555 : m_decl.GetType() == GAAT_REAL ||
590 3837 : m_decl.GetType() == GAAT_STRING) &&
591 5 : value.size() == 1)
592 : {
593 4 : return Set(value[0]);
594 : }
595 1276 : else if (m_decl.GetType() == GAAT_DATASET_LIST)
596 : {
597 30 : std::vector<GDALArgDatasetValue> dsVector;
598 46 : for (const std::string &s : value)
599 31 : dsVector.emplace_back(s);
600 15 : return Set(std::move(dsVector));
601 : }
602 :
603 1264 : if (m_decl.GetType() != GAAT_STRING_LIST)
604 : {
605 10 : CPLError(CE_Failure, CPLE_AppDefined,
606 : "Calling Set(const std::vector<std::string> &) on argument "
607 : "'%s' of type %s is not supported",
608 5 : GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
609 5 : return false;
610 : }
611 :
612 2499 : if (m_decl.IsReadFromFileAtSyntaxAllowed() ||
613 1240 : m_decl.IsRemoveSQLCommentsEnabled())
614 : {
615 38 : std::vector<std::string> newValue(value);
616 41 : for (auto &s : newValue)
617 : {
618 22 : if (!ProcessString(s))
619 0 : return false;
620 : }
621 19 : return SetInternal(newValue);
622 : }
623 : else
624 : {
625 1240 : return SetInternal(value);
626 : }
627 : }
628 :
629 135 : bool GDALAlgorithmArg::Set(const std::vector<int> &value)
630 : {
631 135 : if (m_decl.GetType() == GAAT_REAL_LIST)
632 : {
633 2 : std::vector<double> v_d;
634 2 : for (int i : value)
635 1 : v_d.push_back(i);
636 1 : return Set(v_d);
637 : }
638 134 : else if (m_decl.GetType() == GAAT_STRING_LIST)
639 : {
640 2 : std::vector<std::string> v_s;
641 3 : for (int i : value)
642 2 : v_s.push_back(std::to_string(i));
643 1 : return Set(v_s);
644 : }
645 264 : else if ((m_decl.GetType() == GAAT_INTEGER ||
646 260 : m_decl.GetType() == GAAT_REAL ||
647 395 : m_decl.GetType() == GAAT_STRING) &&
648 5 : value.size() == 1)
649 : {
650 3 : return Set(value[0]);
651 : }
652 :
653 130 : if (m_decl.GetType() != GAAT_INTEGER_LIST)
654 : {
655 6 : CPLError(CE_Failure, CPLE_AppDefined,
656 : "Calling Set(const std::vector<int> &) on argument '%s' of "
657 : "type %s is not supported",
658 3 : GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
659 3 : return false;
660 : }
661 127 : return SetInternal(value);
662 : }
663 :
664 361 : bool GDALAlgorithmArg::Set(const std::vector<double> &value)
665 : {
666 361 : if (m_decl.GetType() == GAAT_INTEGER_LIST)
667 : {
668 2 : std::vector<int> v_i;
669 3 : for (double d : value)
670 : {
671 2 : if (d >= INT_MIN && d <= INT_MAX && static_cast<int>(d) == d)
672 : {
673 1 : v_i.push_back(static_cast<int>(d));
674 : }
675 : else
676 : {
677 : break;
678 : }
679 : }
680 2 : if (v_i.size() == value.size())
681 1 : return Set(v_i);
682 : }
683 359 : else if (m_decl.GetType() == GAAT_STRING_LIST)
684 : {
685 2 : std::vector<std::string> v_s;
686 3 : for (double d : value)
687 2 : v_s.push_back(std::to_string(d));
688 1 : return Set(v_s);
689 : }
690 715 : else if ((m_decl.GetType() == GAAT_INTEGER ||
691 713 : m_decl.GetType() == GAAT_REAL ||
692 1072 : m_decl.GetType() == GAAT_STRING) &&
693 3 : value.size() == 1)
694 : {
695 3 : return Set(value[0]);
696 : }
697 :
698 356 : if (m_decl.GetType() != GAAT_REAL_LIST)
699 : {
700 4 : CPLError(CE_Failure, CPLE_AppDefined,
701 : "Calling Set(const std::vector<double> &) on argument '%s' of "
702 : "type %s is not supported",
703 2 : GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
704 2 : return false;
705 : }
706 354 : return SetInternal(value);
707 : }
708 :
709 3885 : bool GDALAlgorithmArg::Set(std::vector<GDALArgDatasetValue> &&value)
710 : {
711 3885 : if (m_decl.GetType() != GAAT_DATASET_LIST)
712 : {
713 2 : CPLError(CE_Failure, CPLE_AppDefined,
714 : "Calling Set(const std::vector<GDALArgDatasetValue> &&) on "
715 : "argument '%s' of type %s is not supported",
716 1 : GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
717 1 : return false;
718 : }
719 3884 : m_explicitlySet = true;
720 3884 : *std::get<std::vector<GDALArgDatasetValue> *>(m_value) = std::move(value);
721 3884 : return RunAllActions();
722 : }
723 :
724 : GDALAlgorithmArg &
725 0 : GDALAlgorithmArg::operator=(std::unique_ptr<GDALDataset> value)
726 : {
727 0 : Set(std::move(value));
728 0 : return *this;
729 : }
730 :
731 1 : bool GDALAlgorithmArg::Set(const OGRSpatialReference &value)
732 : {
733 1 : const char *const apszOptions[] = {"FORMAT=WKT2_2019", nullptr};
734 1 : return Set(value.exportToWkt(apszOptions));
735 : }
736 :
737 4766 : bool GDALAlgorithmArg::SetFrom(const GDALAlgorithmArg &other)
738 : {
739 4766 : if (m_decl.GetType() != other.GetType())
740 : {
741 2 : CPLError(CE_Failure, CPLE_AppDefined,
742 : "Calling SetFrom() on argument '%s' of type %s whereas "
743 : "other argument type is %s is not supported",
744 1 : GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()),
745 : GDALAlgorithmArgTypeName(other.GetType()));
746 1 : return false;
747 : }
748 :
749 4765 : switch (m_decl.GetType())
750 : {
751 98 : case GAAT_BOOLEAN:
752 98 : *std::get<bool *>(m_value) = *std::get<bool *>(other.m_value);
753 98 : break;
754 890 : case GAAT_STRING:
755 1780 : *std::get<std::string *>(m_value) =
756 890 : *std::get<std::string *>(other.m_value);
757 890 : break;
758 7 : case GAAT_INTEGER:
759 7 : *std::get<int *>(m_value) = *std::get<int *>(other.m_value);
760 7 : break;
761 1 : case GAAT_REAL:
762 1 : *std::get<double *>(m_value) = *std::get<double *>(other.m_value);
763 1 : break;
764 1104 : case GAAT_DATASET:
765 1104 : return SetFrom(other.Get<GDALArgDatasetValue>());
766 60 : case GAAT_STRING_LIST:
767 120 : *std::get<std::vector<std::string> *>(m_value) =
768 60 : *std::get<std::vector<std::string> *>(other.m_value);
769 60 : break;
770 1 : case GAAT_INTEGER_LIST:
771 2 : *std::get<std::vector<int> *>(m_value) =
772 1 : *std::get<std::vector<int> *>(other.m_value);
773 1 : break;
774 1 : case GAAT_REAL_LIST:
775 2 : *std::get<std::vector<double> *>(m_value) =
776 1 : *std::get<std::vector<double> *>(other.m_value);
777 1 : break;
778 2603 : case GAAT_DATASET_LIST:
779 : {
780 2603 : std::get<std::vector<GDALArgDatasetValue> *>(m_value)->clear();
781 2609 : for (const auto &val :
782 7821 : *std::get<std::vector<GDALArgDatasetValue> *>(other.m_value))
783 : {
784 5218 : GDALArgDatasetValue v;
785 2609 : v.SetFrom(val);
786 2609 : std::get<std::vector<GDALArgDatasetValue> *>(m_value)
787 2609 : ->push_back(std::move(v));
788 : }
789 2603 : break;
790 : }
791 : }
792 3661 : m_explicitlySet = true;
793 3661 : return RunAllActions();
794 : }
795 :
796 : /************************************************************************/
797 : /* GDALAlgorithmArg::RunAllActions() */
798 : /************************************************************************/
799 :
800 18021 : bool GDALAlgorithmArg::RunAllActions()
801 : {
802 18021 : if (!RunValidationActions())
803 149 : return false;
804 17872 : RunActions();
805 17872 : return true;
806 : }
807 :
808 : /************************************************************************/
809 : /* GDALAlgorithmArg::RunActions() */
810 : /************************************************************************/
811 :
812 17873 : void GDALAlgorithmArg::RunActions()
813 : {
814 18189 : for (const auto &f : m_actions)
815 316 : f();
816 17873 : }
817 :
818 : /************************************************************************/
819 : /* GDALAlgorithmArg::ValidateChoice() */
820 : /************************************************************************/
821 :
822 : // Returns the canonical value if matching a valid choice, or empty string
823 : // otherwise.
824 2775 : std::string GDALAlgorithmArg::ValidateChoice(const std::string &value) const
825 : {
826 15878 : for (const std::string &choice : GetChoices())
827 : {
828 15757 : if (EQUAL(value.c_str(), choice.c_str()))
829 : {
830 2654 : return choice;
831 : }
832 : }
833 :
834 193 : for (const std::string &choice : GetHiddenChoices())
835 : {
836 175 : if (EQUAL(value.c_str(), choice.c_str()))
837 : {
838 103 : return choice;
839 : }
840 : }
841 :
842 36 : std::string expected;
843 222 : for (const auto &choice : GetChoices())
844 : {
845 204 : if (!expected.empty())
846 186 : expected += ", ";
847 204 : expected += '\'';
848 204 : expected += choice;
849 204 : expected += '\'';
850 : }
851 18 : if (m_owner && m_owner->IsCalledFromCommandLine() && value == "?")
852 : {
853 6 : return "?";
854 : }
855 24 : CPLError(CE_Failure, CPLE_IllegalArg,
856 : "Invalid value '%s' for string argument '%s'. Should be "
857 : "one among %s.",
858 12 : value.c_str(), GetName().c_str(), expected.c_str());
859 12 : return std::string();
860 : }
861 :
862 : /************************************************************************/
863 : /* GDALAlgorithmArg::ValidateIntRange() */
864 : /************************************************************************/
865 :
866 2621 : bool GDALAlgorithmArg::ValidateIntRange(int val) const
867 : {
868 2621 : bool ret = true;
869 :
870 2621 : const auto [minVal, minValIsIncluded] = GetMinValue();
871 2621 : if (!std::isnan(minVal))
872 : {
873 1941 : if (minValIsIncluded && val < minVal)
874 : {
875 3 : CPLError(CE_Failure, CPLE_IllegalArg,
876 : "Value of argument '%s' is %d, but should be >= %d",
877 3 : GetName().c_str(), val, static_cast<int>(minVal));
878 3 : ret = false;
879 : }
880 1938 : else if (!minValIsIncluded && val <= minVal)
881 : {
882 1 : CPLError(CE_Failure, CPLE_IllegalArg,
883 : "Value of argument '%s' is %d, but should be > %d",
884 1 : GetName().c_str(), val, static_cast<int>(minVal));
885 1 : ret = false;
886 : }
887 : }
888 :
889 2621 : const auto [maxVal, maxValIsIncluded] = GetMaxValue();
890 2621 : if (!std::isnan(maxVal))
891 : {
892 :
893 430 : if (maxValIsIncluded && val > maxVal)
894 : {
895 1 : CPLError(CE_Failure, CPLE_IllegalArg,
896 : "Value of argument '%s' is %d, but should be <= %d",
897 1 : GetName().c_str(), val, static_cast<int>(maxVal));
898 1 : ret = false;
899 : }
900 429 : else if (!maxValIsIncluded && val >= maxVal)
901 : {
902 1 : CPLError(CE_Failure, CPLE_IllegalArg,
903 : "Value of argument '%s' is %d, but should be < %d",
904 1 : GetName().c_str(), val, static_cast<int>(maxVal));
905 1 : ret = false;
906 : }
907 : }
908 :
909 2621 : return ret;
910 : }
911 :
912 : /************************************************************************/
913 : /* GDALAlgorithmArg::ValidateRealRange() */
914 : /************************************************************************/
915 :
916 2691 : bool GDALAlgorithmArg::ValidateRealRange(double val) const
917 : {
918 2691 : bool ret = true;
919 :
920 2691 : const auto [minVal, minValIsIncluded] = GetMinValue();
921 2691 : if (!std::isnan(minVal))
922 : {
923 216 : if (minValIsIncluded && !(val >= minVal))
924 : {
925 11 : CPLError(CE_Failure, CPLE_IllegalArg,
926 : "Value of argument '%s' is %g, but should be >= %g",
927 11 : GetName().c_str(), val, minVal);
928 11 : ret = false;
929 : }
930 205 : else if (!minValIsIncluded && !(val > minVal))
931 : {
932 4 : CPLError(CE_Failure, CPLE_IllegalArg,
933 : "Value of argument '%s' is %g, but should be > %g",
934 4 : GetName().c_str(), val, minVal);
935 4 : ret = false;
936 : }
937 : }
938 :
939 2691 : const auto [maxVal, maxValIsIncluded] = GetMaxValue();
940 2691 : if (!std::isnan(maxVal))
941 : {
942 :
943 58 : if (maxValIsIncluded && !(val <= maxVal))
944 : {
945 2 : CPLError(CE_Failure, CPLE_IllegalArg,
946 : "Value of argument '%s' is %g, but should be <= %g",
947 2 : GetName().c_str(), val, maxVal);
948 2 : ret = false;
949 : }
950 56 : else if (!maxValIsIncluded && !(val < maxVal))
951 : {
952 1 : CPLError(CE_Failure, CPLE_IllegalArg,
953 : "Value of argument '%s' is %g, but should be < %g",
954 1 : GetName().c_str(), val, maxVal);
955 1 : ret = false;
956 : }
957 : }
958 :
959 2691 : return ret;
960 : }
961 :
962 : /************************************************************************/
963 : /* CheckDuplicateValues() */
964 : /************************************************************************/
965 :
966 : template <class T>
967 178 : static bool CheckDuplicateValues(const GDALAlgorithmArg *arg,
968 : const std::vector<T> &values)
969 : {
970 356 : auto tmpValues = values;
971 178 : bool bHasDupValues = false;
972 : if constexpr (std::is_floating_point_v<T>)
973 : {
974 : // Avoid undefined behavior with NaN values
975 4 : std::sort(tmpValues.begin(), tmpValues.end(),
976 21 : [](T a, T b)
977 : {
978 21 : if (std::isnan(a) && !std::isnan(b))
979 3 : return true;
980 18 : if (std::isnan(b))
981 10 : return false;
982 8 : return a < b;
983 : });
984 :
985 : bHasDupValues =
986 4 : std::adjacent_find(tmpValues.begin(), tmpValues.end(),
987 6 : [](T a, T b)
988 : {
989 6 : if (std::isnan(a) && std::isnan(b))
990 1 : return true;
991 5 : return a == b;
992 8 : }) != tmpValues.end();
993 : }
994 : else
995 : {
996 174 : std::sort(tmpValues.begin(), tmpValues.end());
997 174 : bHasDupValues = std::adjacent_find(tmpValues.begin(),
998 348 : tmpValues.end()) != tmpValues.end();
999 : }
1000 178 : if (bHasDupValues)
1001 : {
1002 10 : CPLError(CE_Failure, CPLE_AppDefined,
1003 : "'%s' must be a list of unique values.",
1004 10 : arg->GetName().c_str());
1005 10 : return false;
1006 : }
1007 168 : return true;
1008 : }
1009 :
1010 : /************************************************************************/
1011 : /* GDALAlgorithmArg::RunValidationActions() */
1012 : /************************************************************************/
1013 :
1014 39923 : bool GDALAlgorithmArg::RunValidationActions()
1015 : {
1016 39923 : bool ret = true;
1017 :
1018 39923 : if (GetType() == GAAT_STRING && !GetChoices().empty())
1019 : {
1020 1838 : auto &val = Get<std::string>();
1021 3676 : std::string validVal = ValidateChoice(val);
1022 1838 : if (validVal.empty())
1023 7 : ret = false;
1024 : else
1025 1831 : val = std::move(validVal);
1026 : }
1027 38085 : else if (GetType() == GAAT_STRING_LIST && !GetChoices().empty())
1028 : {
1029 677 : auto &values = Get<std::vector<std::string>>();
1030 1614 : for (std::string &val : values)
1031 : {
1032 1874 : std::string validVal = ValidateChoice(val);
1033 937 : if (validVal.empty())
1034 5 : ret = false;
1035 : else
1036 932 : val = std::move(validVal);
1037 : }
1038 : }
1039 :
1040 : const auto CheckMinCharCount =
1041 1143 : [this, &ret](const std::string &val, int nMinCharCount)
1042 : {
1043 1131 : if (val.size() < static_cast<size_t>(nMinCharCount))
1044 : {
1045 12 : CPLError(CE_Failure, CPLE_IllegalArg,
1046 : "Value of argument '%s' is '%s', but should have at least "
1047 : "%d character%s",
1048 6 : GetName().c_str(), val.c_str(), nMinCharCount,
1049 : nMinCharCount > 1 ? "s" : "");
1050 6 : ret = false;
1051 : }
1052 41054 : };
1053 :
1054 : const auto CheckMaxCharCount =
1055 14614 : [this, &ret](const std::string &val, int nMaxCharCount)
1056 : {
1057 14612 : if (val.size() > static_cast<size_t>(nMaxCharCount))
1058 : {
1059 2 : CPLError(
1060 : CE_Failure, CPLE_IllegalArg,
1061 : "Value of argument '%s' is '%s', but should have no more than "
1062 : "%d character%s",
1063 1 : GetName().c_str(), val.c_str(), nMaxCharCount,
1064 : nMaxCharCount > 1 ? "s" : "");
1065 1 : ret = false;
1066 : }
1067 54535 : };
1068 :
1069 39923 : switch (GetType())
1070 : {
1071 2943 : case GAAT_BOOLEAN:
1072 2943 : break;
1073 :
1074 11141 : case GAAT_STRING:
1075 : {
1076 11141 : const auto &val = Get<std::string>();
1077 11141 : const int nMinCharCount = GetMinCharCount();
1078 11141 : if (nMinCharCount > 0)
1079 : {
1080 1049 : CheckMinCharCount(val, nMinCharCount);
1081 : }
1082 :
1083 11141 : const int nMaxCharCount = GetMaxCharCount();
1084 11141 : CheckMaxCharCount(val, nMaxCharCount);
1085 11141 : break;
1086 : }
1087 :
1088 2762 : case GAAT_STRING_LIST:
1089 : {
1090 2762 : const int nMinCharCount = GetMinCharCount();
1091 2762 : const int nMaxCharCount = GetMaxCharCount();
1092 2762 : const auto &values = Get<std::vector<std::string>>();
1093 6233 : for (const auto &val : values)
1094 : {
1095 3471 : if (nMinCharCount > 0)
1096 82 : CheckMinCharCount(val, nMinCharCount);
1097 3471 : CheckMaxCharCount(val, nMaxCharCount);
1098 : }
1099 :
1100 2922 : if (!GetDuplicateValuesAllowed() &&
1101 160 : !CheckDuplicateValues(this, values))
1102 2 : ret = false;
1103 2762 : break;
1104 : }
1105 :
1106 2073 : case GAAT_INTEGER:
1107 : {
1108 2073 : ret = ValidateIntRange(Get<int>()) && ret;
1109 2073 : break;
1110 : }
1111 :
1112 270 : case GAAT_INTEGER_LIST:
1113 : {
1114 270 : const auto &values = Get<std::vector<int>>();
1115 818 : for (int v : values)
1116 548 : ret = ValidateIntRange(v) && ret;
1117 :
1118 273 : if (!GetDuplicateValuesAllowed() &&
1119 3 : !CheckDuplicateValues(this, values))
1120 1 : ret = false;
1121 270 : break;
1122 : }
1123 :
1124 601 : case GAAT_REAL:
1125 : {
1126 601 : ret = ValidateRealRange(Get<double>()) && ret;
1127 601 : break;
1128 : }
1129 :
1130 767 : case GAAT_REAL_LIST:
1131 : {
1132 767 : const auto &values = Get<std::vector<double>>();
1133 2857 : for (double v : values)
1134 2090 : ret = ValidateRealRange(v) && ret;
1135 :
1136 771 : if (!GetDuplicateValuesAllowed() &&
1137 4 : !CheckDuplicateValues(this, values))
1138 2 : ret = false;
1139 767 : break;
1140 : }
1141 :
1142 6438 : case GAAT_DATASET:
1143 6438 : break;
1144 :
1145 12928 : case GAAT_DATASET_LIST:
1146 : {
1147 12928 : if (!GetDuplicateValuesAllowed())
1148 : {
1149 11 : const auto &values = Get<std::vector<GDALArgDatasetValue>>();
1150 22 : std::vector<std::string> aosValues;
1151 34 : for (const auto &v : values)
1152 : {
1153 23 : const GDALDataset *poDS = v.GetDatasetRef();
1154 23 : if (poDS)
1155 : {
1156 16 : auto poDriver = poDS->GetDriver();
1157 : // The dataset name for a MEM driver is not relevant,
1158 : // so use the pointer address
1159 32 : if ((poDriver &&
1160 24 : EQUAL(poDriver->GetDescription(), "MEM")) ||
1161 8 : poDS->GetDescription()[0] == 0)
1162 : {
1163 8 : aosValues.push_back(CPLSPrintf("%p", poDS));
1164 : }
1165 : else
1166 : {
1167 8 : aosValues.push_back(poDS->GetDescription());
1168 : }
1169 : }
1170 : else
1171 : {
1172 7 : aosValues.push_back(v.GetName());
1173 : }
1174 : }
1175 11 : if (!CheckDuplicateValues(this, aosValues))
1176 5 : ret = false;
1177 : }
1178 12928 : break;
1179 : }
1180 : }
1181 :
1182 39923 : if (GDALAlgorithmArgTypeIsList(GetType()))
1183 : {
1184 16727 : int valueCount = 0;
1185 16727 : if (GetType() == GAAT_STRING_LIST)
1186 : {
1187 2762 : valueCount =
1188 2762 : static_cast<int>(Get<std::vector<std::string>>().size());
1189 : }
1190 13965 : else if (GetType() == GAAT_INTEGER_LIST)
1191 : {
1192 270 : valueCount = static_cast<int>(Get<std::vector<int>>().size());
1193 : }
1194 13695 : else if (GetType() == GAAT_REAL_LIST)
1195 : {
1196 767 : valueCount = static_cast<int>(Get<std::vector<double>>().size());
1197 : }
1198 12928 : else if (GetType() == GAAT_DATASET_LIST)
1199 : {
1200 12928 : valueCount = static_cast<int>(
1201 12928 : Get<std::vector<GDALArgDatasetValue>>().size());
1202 : }
1203 :
1204 16727 : if (valueCount != GetMinCount() && GetMinCount() == GetMaxCount())
1205 : {
1206 14 : ReportError(CE_Failure, CPLE_AppDefined,
1207 : "%d value%s been specified for argument '%s', "
1208 : "whereas exactly %d %s expected.",
1209 : valueCount, valueCount > 1 ? "s have" : " has",
1210 7 : GetName().c_str(), GetMinCount(),
1211 7 : GetMinCount() > 1 ? "were" : "was");
1212 7 : ret = false;
1213 : }
1214 16720 : else if (valueCount < GetMinCount())
1215 : {
1216 6 : ReportError(CE_Failure, CPLE_AppDefined,
1217 : "Only %d value%s been specified for argument '%s', "
1218 : "whereas at least %d %s expected.",
1219 : valueCount, valueCount > 1 ? "s have" : " has",
1220 3 : GetName().c_str(), GetMinCount(),
1221 3 : GetMinCount() > 1 ? "were" : "was");
1222 3 : ret = false;
1223 : }
1224 16717 : else if (valueCount > GetMaxCount())
1225 : {
1226 2 : ReportError(CE_Failure, CPLE_AppDefined,
1227 : "%d value%s been specified for argument '%s', "
1228 : "whereas at most %d %s expected.",
1229 : valueCount, valueCount > 1 ? "s have" : " has",
1230 1 : GetName().c_str(), GetMaxCount(),
1231 1 : GetMaxCount() > 1 ? "were" : "was");
1232 1 : ret = false;
1233 : }
1234 : }
1235 :
1236 39923 : if (ret)
1237 : {
1238 47750 : for (const auto &f : m_validationActions)
1239 : {
1240 7891 : if (!f())
1241 94 : ret = false;
1242 : }
1243 : }
1244 :
1245 39923 : return ret;
1246 : }
1247 :
1248 : /************************************************************************/
1249 : /* GDALAlgorithmArg::ReportError() */
1250 : /************************************************************************/
1251 :
1252 11 : void GDALAlgorithmArg::ReportError(CPLErr eErrClass, CPLErrorNum err_no,
1253 : const char *fmt, ...) const
1254 : {
1255 : va_list args;
1256 11 : va_start(args, fmt);
1257 11 : if (m_owner)
1258 : {
1259 11 : m_owner->ReportError(eErrClass, err_no, "%s",
1260 22 : CPLString().vPrintf(fmt, args).c_str());
1261 : }
1262 : else
1263 : {
1264 0 : CPLError(eErrClass, err_no, "%s",
1265 0 : CPLString().vPrintf(fmt, args).c_str());
1266 : }
1267 11 : va_end(args);
1268 11 : }
1269 :
1270 : /************************************************************************/
1271 : /* GDALAlgorithmArg::GetEscapedString() */
1272 : /************************************************************************/
1273 :
1274 : /* static */
1275 197 : std::string GDALAlgorithmArg::GetEscapedString(const std::string &s)
1276 : {
1277 215 : if (s.find_first_of("\" \\,") != std::string::npos &&
1278 9 : !(s.size() > 4 &&
1279 9 : s[0] == GDALAbstractPipelineAlgorithm::OPEN_NESTED_PIPELINE[0] &&
1280 2 : s[1] == ' ' && s[s.size() - 2] == ' ' &&
1281 2 : s.back() == GDALAbstractPipelineAlgorithm::CLOSE_NESTED_PIPELINE[0]))
1282 : {
1283 14 : return std::string("\"")
1284 : .append(
1285 14 : CPLString(s).replaceAll('\\', "\\\\").replaceAll('"', "\\\""))
1286 7 : .append("\"");
1287 : }
1288 : else
1289 : {
1290 190 : return s;
1291 : }
1292 : }
1293 :
1294 : /************************************************************************/
1295 : /* GDALAlgorithmArg::Serialize() */
1296 : /************************************************************************/
1297 :
1298 43 : bool GDALAlgorithmArg::Serialize(std::string &serializedArg,
1299 : bool absolutePath) const
1300 : {
1301 43 : serializedArg.clear();
1302 :
1303 43 : if (!IsExplicitlySet())
1304 : {
1305 0 : return false;
1306 : }
1307 :
1308 86 : std::string ret = "--";
1309 43 : ret += GetName();
1310 43 : if (GetType() == GAAT_BOOLEAN)
1311 : {
1312 0 : serializedArg = std::move(ret);
1313 0 : return true;
1314 : }
1315 :
1316 7 : const auto AddListValueSeparator = [this, &ret]()
1317 : {
1318 2 : if (GetPackedValuesAllowed())
1319 : {
1320 1 : ret += ',';
1321 : }
1322 : else
1323 : {
1324 1 : ret += " --";
1325 1 : ret += GetName();
1326 1 : ret += ' ';
1327 : }
1328 45 : };
1329 :
1330 0 : const auto MakeAbsolutePath = [](const std::string &filename)
1331 : {
1332 : VSIStatBufL sStat;
1333 0 : if (VSIStatL(filename.c_str(), &sStat) != 0 ||
1334 0 : !CPLIsFilenameRelative(filename.c_str()))
1335 0 : return filename;
1336 0 : char *pszCWD = CPLGetCurrentDir();
1337 0 : if (!pszCWD)
1338 0 : return filename;
1339 : const auto absPath =
1340 0 : CPLFormFilenameSafe(pszCWD, filename.c_str(), nullptr);
1341 0 : CPLFree(pszCWD);
1342 0 : return absPath;
1343 : };
1344 :
1345 43 : ret += ' ';
1346 43 : switch (GetType())
1347 : {
1348 0 : case GAAT_BOOLEAN:
1349 0 : break;
1350 8 : case GAAT_STRING:
1351 : {
1352 8 : const auto &val = Get<std::string>();
1353 8 : ret += GetEscapedString(val);
1354 8 : break;
1355 : }
1356 1 : case GAAT_INTEGER:
1357 : {
1358 1 : ret += CPLSPrintf("%d", Get<int>());
1359 1 : break;
1360 : }
1361 0 : case GAAT_REAL:
1362 : {
1363 0 : ret += CPLSPrintf("%.17g", Get<double>());
1364 0 : break;
1365 : }
1366 2 : case GAAT_DATASET:
1367 : {
1368 2 : const auto &val = Get<GDALArgDatasetValue>();
1369 2 : const auto &str = val.GetName();
1370 2 : if (str.empty())
1371 : {
1372 0 : return false;
1373 : }
1374 2 : ret += GetEscapedString(absolutePath ? MakeAbsolutePath(str) : str);
1375 2 : break;
1376 : }
1377 5 : case GAAT_STRING_LIST:
1378 : {
1379 5 : const auto &vals = Get<std::vector<std::string>>();
1380 11 : for (size_t i = 0; i < vals.size(); ++i)
1381 : {
1382 6 : if (i > 0)
1383 2 : AddListValueSeparator();
1384 6 : ret += GetEscapedString(vals[i]);
1385 : }
1386 5 : break;
1387 : }
1388 0 : case GAAT_INTEGER_LIST:
1389 : {
1390 0 : const auto &vals = Get<std::vector<int>>();
1391 0 : for (size_t i = 0; i < vals.size(); ++i)
1392 : {
1393 0 : if (i > 0)
1394 0 : AddListValueSeparator();
1395 0 : ret += CPLSPrintf("%d", vals[i]);
1396 : }
1397 0 : break;
1398 : }
1399 0 : case GAAT_REAL_LIST:
1400 : {
1401 0 : const auto &vals = Get<std::vector<double>>();
1402 0 : for (size_t i = 0; i < vals.size(); ++i)
1403 : {
1404 0 : if (i > 0)
1405 0 : AddListValueSeparator();
1406 0 : ret += CPLSPrintf("%.17g", vals[i]);
1407 : }
1408 0 : break;
1409 : }
1410 27 : case GAAT_DATASET_LIST:
1411 : {
1412 27 : const auto &vals = Get<std::vector<GDALArgDatasetValue>>();
1413 53 : for (size_t i = 0; i < vals.size(); ++i)
1414 : {
1415 27 : if (i > 0)
1416 0 : AddListValueSeparator();
1417 27 : const auto &val = vals[i];
1418 27 : const auto &str = val.GetName();
1419 27 : if (str.empty())
1420 : {
1421 1 : return false;
1422 : }
1423 52 : ret += GetEscapedString(absolutePath ? MakeAbsolutePath(str)
1424 26 : : str);
1425 : }
1426 26 : break;
1427 : }
1428 : }
1429 :
1430 42 : serializedArg = std::move(ret);
1431 42 : return true;
1432 : }
1433 :
1434 : /************************************************************************/
1435 : /* ~GDALInConstructionAlgorithmArg() */
1436 : /************************************************************************/
1437 :
1438 : GDALInConstructionAlgorithmArg::~GDALInConstructionAlgorithmArg() = default;
1439 :
1440 : /************************************************************************/
1441 : /* GDALInConstructionAlgorithmArg::AddAlias() */
1442 : /************************************************************************/
1443 :
1444 : GDALInConstructionAlgorithmArg &
1445 68801 : GDALInConstructionAlgorithmArg::AddAlias(const std::string &alias)
1446 : {
1447 68801 : m_decl.AddAlias(alias);
1448 68801 : if (m_owner)
1449 68801 : m_owner->AddAliasFor(this, alias);
1450 68801 : return *this;
1451 : }
1452 :
1453 : /************************************************************************/
1454 : /* GDALInConstructionAlgorithmArg::AddHiddenAlias() */
1455 : /************************************************************************/
1456 :
1457 : GDALInConstructionAlgorithmArg &
1458 18616 : GDALInConstructionAlgorithmArg::AddHiddenAlias(const std::string &alias)
1459 : {
1460 18616 : m_decl.AddHiddenAlias(alias);
1461 18616 : if (m_owner)
1462 18616 : m_owner->AddAliasFor(this, alias);
1463 18616 : return *this;
1464 : }
1465 :
1466 : /************************************************************************/
1467 : /* GDALInConstructionAlgorithmArg::AddShortNameAlias() */
1468 : /************************************************************************/
1469 :
1470 : GDALInConstructionAlgorithmArg &
1471 50 : GDALInConstructionAlgorithmArg::AddShortNameAlias(char shortNameAlias)
1472 : {
1473 50 : m_decl.AddShortNameAlias(shortNameAlias);
1474 50 : if (m_owner)
1475 50 : m_owner->AddShortNameAliasFor(this, shortNameAlias);
1476 50 : return *this;
1477 : }
1478 :
1479 : /************************************************************************/
1480 : /* GDALInConstructionAlgorithmArg::SetPositional() */
1481 : /************************************************************************/
1482 :
1483 23872 : GDALInConstructionAlgorithmArg &GDALInConstructionAlgorithmArg::SetPositional()
1484 : {
1485 23872 : m_decl.SetPositional();
1486 23872 : if (m_owner)
1487 23872 : m_owner->SetPositional(this);
1488 23872 : return *this;
1489 : }
1490 :
1491 : /************************************************************************/
1492 : /* GDALArgDatasetValue::GDALArgDatasetValue() */
1493 : /************************************************************************/
1494 :
1495 1443 : GDALArgDatasetValue::GDALArgDatasetValue(GDALDataset *poDS)
1496 2886 : : m_poDS(poDS), m_name(m_poDS ? m_poDS->GetDescription() : std::string()),
1497 1443 : m_nameSet(true)
1498 : {
1499 1443 : if (m_poDS)
1500 1443 : m_poDS->Reference();
1501 1443 : }
1502 :
1503 : /************************************************************************/
1504 : /* GDALArgDatasetValue::Set() */
1505 : /************************************************************************/
1506 :
1507 2505 : void GDALArgDatasetValue::Set(const std::string &name)
1508 : {
1509 2505 : Close();
1510 2505 : m_name = name;
1511 2505 : m_nameSet = true;
1512 2505 : if (m_ownerArg)
1513 2499 : m_ownerArg->NotifyValueSet();
1514 2505 : }
1515 :
1516 : /************************************************************************/
1517 : /* GDALArgDatasetValue::Set() */
1518 : /************************************************************************/
1519 :
1520 2320 : void GDALArgDatasetValue::Set(std::unique_ptr<GDALDataset> poDS)
1521 : {
1522 2320 : Close();
1523 2320 : m_poDS = poDS.release();
1524 2320 : m_name = m_poDS ? m_poDS->GetDescription() : std::string();
1525 2320 : m_nameSet = true;
1526 2320 : if (m_ownerArg)
1527 2110 : m_ownerArg->NotifyValueSet();
1528 2320 : }
1529 :
1530 : /************************************************************************/
1531 : /* GDALArgDatasetValue::Set() */
1532 : /************************************************************************/
1533 :
1534 9064 : void GDALArgDatasetValue::Set(GDALDataset *poDS)
1535 : {
1536 9064 : Close();
1537 9064 : m_poDS = poDS;
1538 9064 : if (m_poDS)
1539 8085 : m_poDS->Reference();
1540 9064 : m_name = m_poDS ? m_poDS->GetDescription() : std::string();
1541 9064 : m_nameSet = true;
1542 9064 : if (m_ownerArg)
1543 3630 : m_ownerArg->NotifyValueSet();
1544 9064 : }
1545 :
1546 : /************************************************************************/
1547 : /* GDALArgDatasetValue::SetFrom() */
1548 : /************************************************************************/
1549 :
1550 3717 : void GDALArgDatasetValue::SetFrom(const GDALArgDatasetValue &other)
1551 : {
1552 3717 : Close();
1553 3717 : m_name = other.m_name;
1554 3717 : m_nameSet = other.m_nameSet;
1555 3717 : m_poDS = other.m_poDS;
1556 3717 : if (m_poDS)
1557 2589 : m_poDS->Reference();
1558 3717 : }
1559 :
1560 : /************************************************************************/
1561 : /* GDALArgDatasetValue::~GDALArgDatasetValue() */
1562 : /************************************************************************/
1563 :
1564 35167 : GDALArgDatasetValue::~GDALArgDatasetValue()
1565 : {
1566 35167 : Close();
1567 35167 : }
1568 :
1569 : /************************************************************************/
1570 : /* GDALArgDatasetValue::Close() */
1571 : /************************************************************************/
1572 :
1573 58895 : bool GDALArgDatasetValue::Close()
1574 : {
1575 58895 : bool ret = true;
1576 58895 : if (m_poDS && m_poDS->Dereference() == 0)
1577 : {
1578 3775 : ret = m_poDS->Close() == CE_None;
1579 3775 : delete m_poDS;
1580 : }
1581 58895 : m_poDS = nullptr;
1582 58895 : return ret;
1583 : }
1584 :
1585 : /************************************************************************/
1586 : /* GDALArgDatasetValue::operator=() */
1587 : /************************************************************************/
1588 :
1589 2 : GDALArgDatasetValue &GDALArgDatasetValue::operator=(GDALArgDatasetValue &&other)
1590 : {
1591 2 : Close();
1592 2 : m_poDS = other.m_poDS;
1593 2 : m_name = other.m_name;
1594 2 : m_nameSet = other.m_nameSet;
1595 2 : other.m_poDS = nullptr;
1596 2 : other.m_name.clear();
1597 2 : other.m_nameSet = false;
1598 2 : return *this;
1599 : }
1600 :
1601 : /************************************************************************/
1602 : /* GDALArgDatasetValue::GetDataset() */
1603 : /************************************************************************/
1604 :
1605 1209 : GDALDataset *GDALArgDatasetValue::GetDatasetIncreaseRefCount()
1606 : {
1607 1209 : if (m_poDS)
1608 1204 : m_poDS->Reference();
1609 1209 : return m_poDS;
1610 : }
1611 :
1612 : /************************************************************************/
1613 : /* GDALArgDatasetValue(GDALArgDatasetValue &&other) */
1614 : /************************************************************************/
1615 :
1616 3555 : GDALArgDatasetValue::GDALArgDatasetValue(GDALArgDatasetValue &&other)
1617 3555 : : m_poDS(other.m_poDS), m_name(other.m_name), m_nameSet(other.m_nameSet)
1618 : {
1619 3555 : other.m_poDS = nullptr;
1620 3555 : other.m_name.clear();
1621 3555 : }
1622 :
1623 : /************************************************************************/
1624 : /* GDALInConstructionAlgorithmArg::SetIsCRSArg() */
1625 : /************************************************************************/
1626 :
1627 3814 : GDALInConstructionAlgorithmArg &GDALInConstructionAlgorithmArg::SetIsCRSArg(
1628 : bool noneAllowed, const std::vector<std::string> &specialValues)
1629 : {
1630 3814 : if (GetType() != GAAT_STRING)
1631 : {
1632 1 : CPLError(CE_Failure, CPLE_AppDefined,
1633 : "SetIsCRSArg() can only be called on a String argument");
1634 1 : return *this;
1635 : }
1636 : AddValidationAction(
1637 913 : [this, noneAllowed, specialValues]()
1638 : {
1639 : const std::string &osVal =
1640 : static_cast<const GDALInConstructionAlgorithmArg *>(this)
1641 453 : ->Get<std::string>();
1642 453 : if (osVal == "?" && m_owner && m_owner->IsCalledFromCommandLine())
1643 0 : return true;
1644 :
1645 893 : if ((!noneAllowed || (osVal != "none" && osVal != "null")) &&
1646 440 : std::find(specialValues.begin(), specialValues.end(), osVal) ==
1647 893 : specialValues.end())
1648 : {
1649 432 : OGRSpatialReference oSRS;
1650 432 : if (oSRS.SetFromUserInput(osVal.c_str()) != OGRERR_NONE)
1651 : {
1652 7 : m_owner->ReportError(CE_Failure, CPLE_AppDefined,
1653 : "Invalid value for '%s' argument",
1654 7 : GetName().c_str());
1655 7 : return false;
1656 : }
1657 : }
1658 446 : return true;
1659 3813 : });
1660 :
1661 : SetAutoCompleteFunction(
1662 44 : [this, noneAllowed, specialValues](const std::string ¤tValue)
1663 : {
1664 11 : bool bIsRaster = false;
1665 11 : OGREnvelope sDatasetLongLatEnv;
1666 22 : std::string osCelestialBodyName;
1667 11 : if (GetName() == GDAL_ARG_NAME_OUTPUT_CRS)
1668 : {
1669 11 : auto inputArg = m_owner->GetArg(GDAL_ARG_NAME_INPUT);
1670 11 : if (inputArg && inputArg->GetType() == GAAT_DATASET_LIST)
1671 : {
1672 : auto &val =
1673 11 : inputArg->Get<std::vector<GDALArgDatasetValue>>();
1674 11 : if (val.size() == 1)
1675 : {
1676 4 : CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
1677 : auto poDS = std::unique_ptr<GDALDataset>(
1678 4 : GDALDataset::Open(val[0].GetName().c_str()));
1679 2 : if (poDS)
1680 : {
1681 2 : bIsRaster = poDS->GetRasterCount() != 0;
1682 2 : if (auto poCRS = poDS->GetSpatialRef())
1683 : {
1684 : const char *pszCelestialBodyName =
1685 2 : poCRS->GetCelestialBodyName();
1686 2 : if (pszCelestialBodyName)
1687 2 : osCelestialBodyName = pszCelestialBodyName;
1688 :
1689 2 : if (!pszCelestialBodyName ||
1690 2 : !EQUAL(pszCelestialBodyName, "Earth"))
1691 : {
1692 0 : OGRSpatialReference oLongLat;
1693 0 : oLongLat.CopyGeogCSFrom(poCRS);
1694 0 : oLongLat.SetAxisMappingStrategy(
1695 : OAMS_TRADITIONAL_GIS_ORDER);
1696 0 : poDS->GetExtent(&sDatasetLongLatEnv,
1697 0 : &oLongLat);
1698 : }
1699 : else
1700 : {
1701 2 : poDS->GetExtentWGS84LongLat(
1702 2 : &sDatasetLongLatEnv);
1703 : }
1704 : }
1705 : }
1706 : }
1707 : }
1708 : }
1709 :
1710 : const auto IsCRSCompatible =
1711 42959 : [bIsRaster, &sDatasetLongLatEnv,
1712 73695 : &osCelestialBodyName](const OSRCRSInfo *crsInfo)
1713 : {
1714 42959 : if (!sDatasetLongLatEnv.IsInit())
1715 30685 : return true;
1716 24108 : return crsInfo->eType != OSR_CRS_TYPE_VERTICAL &&
1717 11834 : !(bIsRaster &&
1718 5917 : crsInfo->eType == OSR_CRS_TYPE_GEOCENTRIC) &&
1719 11652 : crsInfo->dfWestLongitudeDeg <
1720 11652 : crsInfo->dfEastLongitudeDeg &&
1721 11517 : sDatasetLongLatEnv.MinX < crsInfo->dfEastLongitudeDeg &&
1722 5618 : sDatasetLongLatEnv.MaxX > crsInfo->dfWestLongitudeDeg &&
1723 615 : sDatasetLongLatEnv.MinY < crsInfo->dfNorthLatitudeDeg &&
1724 24437 : sDatasetLongLatEnv.MaxY > crsInfo->dfSouthLatitudeDeg &&
1725 329 : ((!osCelestialBodyName.empty() &&
1726 658 : crsInfo->pszCelestialBodyName &&
1727 329 : osCelestialBodyName ==
1728 329 : crsInfo->pszCelestialBodyName) ||
1729 0 : (osCelestialBodyName.empty() &&
1730 12274 : !crsInfo->pszCelestialBodyName));
1731 11 : };
1732 :
1733 11 : std::vector<std::string> oRet;
1734 11 : if (noneAllowed)
1735 0 : oRet.push_back("none");
1736 11 : oRet.insert(oRet.end(), specialValues.begin(), specialValues.end());
1737 11 : if (!currentValue.empty())
1738 : {
1739 : const CPLStringList aosTokens(
1740 14 : CSLTokenizeString2(currentValue.c_str(), ":", 0));
1741 7 : int nCount = 0;
1742 : std::unique_ptr<OSRCRSInfo *, decltype(&OSRDestroyCRSInfoList)>
1743 : pCRSList(OSRGetCRSInfoListFromDatabase(aosTokens[0],
1744 : nullptr, &nCount),
1745 14 : OSRDestroyCRSInfoList);
1746 14 : std::string osCode;
1747 :
1748 14 : std::vector<const OSRCRSInfo *> candidates;
1749 46270 : for (int i = 0; i < nCount; ++i)
1750 : {
1751 46263 : const auto *entry = (pCRSList.get())[i];
1752 46263 : if (!entry->bDeprecated && IsCRSCompatible(entry))
1753 : {
1754 49425 : if (aosTokens.size() == 1 ||
1755 18411 : STARTS_WITH(entry->pszCode, aosTokens[1]))
1756 : {
1757 12666 : if (candidates.empty())
1758 7 : osCode = entry->pszCode;
1759 12666 : candidates.push_back(entry);
1760 : }
1761 : }
1762 : }
1763 7 : if (candidates.size() == 1)
1764 : {
1765 1 : oRet.push_back(std::move(osCode));
1766 : }
1767 : else
1768 : {
1769 6 : if (sDatasetLongLatEnv.IsInit())
1770 : {
1771 2 : std::sort(
1772 : candidates.begin(), candidates.end(),
1773 2999 : [](const OSRCRSInfo *a, const OSRCRSInfo *b)
1774 : {
1775 2999 : const double dfXa =
1776 2999 : a->dfWestLongitudeDeg >
1777 2999 : a->dfEastLongitudeDeg
1778 2999 : ? a->dfWestLongitudeDeg -
1779 0 : a->dfEastLongitudeDeg
1780 2999 : : (180 - a->dfWestLongitudeDeg) +
1781 2999 : (a->dfEastLongitudeDeg - -180);
1782 2999 : const double dfYa = a->dfNorthLatitudeDeg -
1783 2999 : a->dfSouthLatitudeDeg;
1784 2999 : const double dfXb =
1785 2999 : b->dfWestLongitudeDeg >
1786 2999 : b->dfEastLongitudeDeg
1787 2999 : ? b->dfWestLongitudeDeg -
1788 0 : b->dfEastLongitudeDeg
1789 2999 : : (180 - b->dfWestLongitudeDeg) +
1790 2999 : (b->dfEastLongitudeDeg - -180);
1791 2999 : const double dfYb = b->dfNorthLatitudeDeg -
1792 2999 : b->dfSouthLatitudeDeg;
1793 2999 : const double diffArea =
1794 2999 : dfXa * dfYa - dfXb * dfYb;
1795 2999 : if (diffArea < 0)
1796 279 : return true;
1797 2720 : if (diffArea == 0)
1798 : {
1799 2506 : if (std::string_view(a->pszName) ==
1800 2506 : b->pszName)
1801 : {
1802 57 : if (a->eType ==
1803 13 : OSR_CRS_TYPE_GEOGRAPHIC_2D &&
1804 13 : b->eType !=
1805 : OSR_CRS_TYPE_GEOGRAPHIC_2D)
1806 13 : return true;
1807 44 : if (a->eType ==
1808 32 : OSR_CRS_TYPE_GEOGRAPHIC_3D &&
1809 32 : b->eType == OSR_CRS_TYPE_GEOCENTRIC)
1810 9 : return true;
1811 35 : return false;
1812 : }
1813 4898 : return std::string_view(a->pszCode) <
1814 4898 : b->pszCode;
1815 : }
1816 214 : return false;
1817 : });
1818 : }
1819 :
1820 12671 : for (const auto *entry : candidates)
1821 : {
1822 25330 : std::string val = std::string(entry->pszCode)
1823 12665 : .append(" -- ")
1824 25330 : .append(entry->pszName);
1825 12665 : if (entry->eType == OSR_CRS_TYPE_GEOGRAPHIC_2D)
1826 1294 : val.append(" (geographic 2D)");
1827 11371 : else if (entry->eType == OSR_CRS_TYPE_GEOGRAPHIC_3D)
1828 446 : val.append(" (geographic 3D)");
1829 10925 : else if (entry->eType == OSR_CRS_TYPE_GEOCENTRIC)
1830 397 : val.append(" (geocentric)");
1831 12665 : oRet.push_back(std::move(val));
1832 : }
1833 : }
1834 : }
1835 11 : if (currentValue.empty() || oRet.empty())
1836 : {
1837 : const CPLStringList aosAuthorities(
1838 8 : OSRGetAuthorityListFromDatabase());
1839 24 : for (const char *pszAuth : cpl::Iterate(aosAuthorities))
1840 : {
1841 20 : int nCount = 0;
1842 20 : OSRDestroyCRSInfoList(OSRGetCRSInfoListFromDatabase(
1843 : pszAuth, nullptr, &nCount));
1844 20 : if (nCount)
1845 16 : oRet.push_back(std::string(pszAuth).append(":"));
1846 : }
1847 : }
1848 22 : return oRet;
1849 3813 : });
1850 :
1851 3813 : return *this;
1852 : }
1853 :
1854 : /************************************************************************/
1855 : /* GDALAlgorithm::GDALAlgorithm() */
1856 : /************************************************************************/
1857 :
1858 24538 : GDALAlgorithm::GDALAlgorithm(const std::string &name,
1859 : const std::string &description,
1860 24538 : const std::string &helpURL)
1861 : : m_name(name), m_description(description), m_helpURL(helpURL),
1862 48486 : m_helpFullURL(!m_helpURL.empty() && m_helpURL[0] == '/'
1863 24538 : ? "https://gdal.org" + m_helpURL
1864 72768 : : m_helpURL)
1865 : {
1866 : auto &helpArg =
1867 : AddArg("help", 'h', _("Display help message and exit"),
1868 49076 : &m_helpRequested)
1869 24538 : .SetHiddenForAPI()
1870 49076 : .SetCategory(GAAC_COMMON)
1871 14 : .AddAction([this]()
1872 24538 : { m_specialActionRequested = m_calledFromCommandLine; });
1873 : auto &helpDocArg =
1874 : AddArg("help-doc", 0,
1875 : _("Display help message for use by documentation"),
1876 49076 : &m_helpDocRequested)
1877 24538 : .SetHidden()
1878 16 : .AddAction([this]()
1879 24538 : { m_specialActionRequested = m_calledFromCommandLine; });
1880 : auto &jsonUsageArg =
1881 : AddArg("json-usage", 0, _("Display usage as JSON document and exit"),
1882 49076 : &m_JSONUsageRequested)
1883 24538 : .SetHiddenForAPI()
1884 49076 : .SetCategory(GAAC_COMMON)
1885 4 : .AddAction([this]()
1886 24538 : { m_specialActionRequested = m_calledFromCommandLine; });
1887 49076 : AddArg("config", 0, _("Configuration option"), &m_dummyConfigOptions)
1888 49076 : .SetMetaVar("<KEY>=<VALUE>")
1889 24538 : .SetHiddenForAPI()
1890 49076 : .SetCategory(GAAC_COMMON)
1891 : .AddAction(
1892 2 : [this]()
1893 : {
1894 2 : ReportError(
1895 : CE_Warning, CPLE_AppDefined,
1896 : "Configuration options passed with the 'config' argument "
1897 : "are ignored");
1898 24538 : });
1899 :
1900 24538 : AddValidationAction(
1901 15338 : [this, &helpArg, &helpDocArg, &jsonUsageArg]()
1902 : {
1903 7893 : if (!m_calledFromCommandLine && m_specialActionRequested)
1904 : {
1905 0 : for (auto &arg : {&helpArg, &helpDocArg, &jsonUsageArg})
1906 : {
1907 0 : if (arg->IsExplicitlySet())
1908 : {
1909 0 : ReportError(CE_Failure, CPLE_AppDefined,
1910 : "'%s' argument only available when called "
1911 : "from command line",
1912 0 : arg->GetName().c_str());
1913 0 : return false;
1914 : }
1915 : }
1916 : }
1917 7893 : return true;
1918 : });
1919 24538 : }
1920 :
1921 : /************************************************************************/
1922 : /* GDALAlgorithm::~GDALAlgorithm() */
1923 : /************************************************************************/
1924 :
1925 : GDALAlgorithm::~GDALAlgorithm() = default;
1926 :
1927 : /************************************************************************/
1928 : /* GDALAlgorithm::ParseArgument() */
1929 : /************************************************************************/
1930 :
1931 3459 : bool GDALAlgorithm::ParseArgument(
1932 : GDALAlgorithmArg *arg, const std::string &name, const std::string &value,
1933 : std::map<
1934 : GDALAlgorithmArg *,
1935 : std::variant<std::vector<std::string>, std::vector<int>,
1936 : std::vector<double>, std::vector<GDALArgDatasetValue>>>
1937 : &inConstructionValues)
1938 : {
1939 : const bool isListArg =
1940 3459 : GDALAlgorithmArgTypeIsList(arg->GetType()) && arg->GetMaxCount() > 1;
1941 3459 : if (arg->IsExplicitlySet() && !isListArg)
1942 : {
1943 : // Hack for "gdal info" to be able to pass an opened raster dataset
1944 : // by "gdal raster info" to the "gdal vector info" algorithm.
1945 4 : if (arg->SkipIfAlreadySet())
1946 : {
1947 1 : arg->SetSkipIfAlreadySet(false);
1948 1 : return true;
1949 : }
1950 :
1951 3 : ReportError(CE_Failure, CPLE_IllegalArg,
1952 : "Argument '%s' has already been specified.", name.c_str());
1953 3 : return false;
1954 : }
1955 :
1956 3529 : if (!arg->GetRepeatedArgAllowed() &&
1957 74 : cpl::contains(inConstructionValues, arg))
1958 : {
1959 1 : ReportError(CE_Failure, CPLE_IllegalArg,
1960 : "Argument '%s' has already been specified.", name.c_str());
1961 1 : return false;
1962 : }
1963 :
1964 3454 : switch (arg->GetType())
1965 : {
1966 336 : case GAAT_BOOLEAN:
1967 : {
1968 336 : if (value.empty() || value == "true")
1969 334 : return arg->Set(true);
1970 2 : else if (value == "false")
1971 1 : return arg->Set(false);
1972 : else
1973 : {
1974 1 : ReportError(
1975 : CE_Failure, CPLE_IllegalArg,
1976 : "Invalid value '%s' for boolean argument '%s'. Should be "
1977 : "'true' or 'false'.",
1978 : value.c_str(), name.c_str());
1979 1 : return false;
1980 : }
1981 : }
1982 :
1983 869 : case GAAT_STRING:
1984 : {
1985 869 : return arg->Set(value);
1986 : }
1987 :
1988 359 : case GAAT_INTEGER:
1989 : {
1990 359 : errno = 0;
1991 359 : char *endptr = nullptr;
1992 359 : const auto val = std::strtol(value.c_str(), &endptr, 10);
1993 358 : if (errno == 0 && endptr &&
1994 717 : endptr == value.c_str() + value.size() && val >= INT_MIN &&
1995 : val <= INT_MAX)
1996 : {
1997 356 : return arg->Set(static_cast<int>(val));
1998 : }
1999 : else
2000 : {
2001 3 : ReportError(CE_Failure, CPLE_IllegalArg,
2002 : "Expected integer value for argument '%s', "
2003 : "but got '%s'.",
2004 : name.c_str(), value.c_str());
2005 3 : return false;
2006 : }
2007 : }
2008 :
2009 36 : case GAAT_REAL:
2010 : {
2011 36 : char *endptr = nullptr;
2012 36 : double dfValue = CPLStrtod(value.c_str(), &endptr);
2013 36 : if (endptr != value.c_str() + value.size())
2014 : {
2015 1 : ReportError(
2016 : CE_Failure, CPLE_IllegalArg,
2017 : "Expected real value for argument '%s', but got '%s'.",
2018 : name.c_str(), value.c_str());
2019 1 : return false;
2020 : }
2021 35 : return arg->Set(dfValue);
2022 : }
2023 :
2024 616 : case GAAT_DATASET:
2025 : {
2026 616 : return arg->SetDatasetName(value);
2027 : }
2028 :
2029 271 : case GAAT_STRING_LIST:
2030 : {
2031 : const CPLStringList aosTokens(
2032 271 : arg->GetPackedValuesAllowed()
2033 181 : ? CSLTokenizeString2(value.c_str(), ",",
2034 : CSLT_HONOURSTRINGS |
2035 : CSLT_PRESERVEQUOTES)
2036 452 : : CSLAddString(nullptr, value.c_str()));
2037 271 : if (!cpl::contains(inConstructionValues, arg))
2038 : {
2039 246 : inConstructionValues[arg] = std::vector<std::string>();
2040 : }
2041 : auto &valueVector =
2042 271 : std::get<std::vector<std::string>>(inConstructionValues[arg]);
2043 575 : for (const char *v : aosTokens)
2044 : {
2045 304 : valueVector.push_back(v);
2046 : }
2047 271 : if (arg->GetMaxCount() == 1)
2048 : {
2049 4 : bool ret = arg->Set(std::move(valueVector));
2050 4 : inConstructionValues.erase(inConstructionValues.find(arg));
2051 4 : return ret;
2052 : }
2053 :
2054 267 : break;
2055 : }
2056 :
2057 63 : case GAAT_INTEGER_LIST:
2058 : {
2059 : const CPLStringList aosTokens(
2060 63 : arg->GetPackedValuesAllowed()
2061 63 : ? CSLTokenizeString2(
2062 : value.c_str(), ",",
2063 : CSLT_HONOURSTRINGS | CSLT_STRIPLEADSPACES |
2064 : CSLT_STRIPENDSPACES | CSLT_ALLOWEMPTYTOKENS)
2065 126 : : CSLAddString(nullptr, value.c_str()));
2066 63 : if (!cpl::contains(inConstructionValues, arg))
2067 : {
2068 59 : inConstructionValues[arg] = std::vector<int>();
2069 : }
2070 : auto &valueVector =
2071 63 : std::get<std::vector<int>>(inConstructionValues[arg]);
2072 191 : for (const char *v : aosTokens)
2073 : {
2074 134 : errno = 0;
2075 134 : char *endptr = nullptr;
2076 134 : const auto val = std::strtol(v, &endptr, 10);
2077 134 : if (errno == 0 && endptr && endptr == v + strlen(v) &&
2078 130 : val >= INT_MIN && val <= INT_MAX && strlen(v) > 0)
2079 : {
2080 128 : valueVector.push_back(static_cast<int>(val));
2081 : }
2082 : else
2083 : {
2084 6 : ReportError(
2085 : CE_Failure, CPLE_IllegalArg,
2086 : "Expected list of integer value for argument '%s', "
2087 : "but got '%s'.",
2088 : name.c_str(), value.c_str());
2089 6 : return false;
2090 : }
2091 : }
2092 57 : if (arg->GetMaxCount() == 1)
2093 : {
2094 2 : bool ret = arg->Set(std::move(valueVector));
2095 2 : inConstructionValues.erase(inConstructionValues.find(arg));
2096 2 : return ret;
2097 : }
2098 :
2099 55 : break;
2100 : }
2101 :
2102 109 : case GAAT_REAL_LIST:
2103 : {
2104 : const CPLStringList aosTokens(
2105 109 : arg->GetPackedValuesAllowed()
2106 109 : ? CSLTokenizeString2(
2107 : value.c_str(), ",",
2108 : CSLT_HONOURSTRINGS | CSLT_STRIPLEADSPACES |
2109 : CSLT_STRIPENDSPACES | CSLT_ALLOWEMPTYTOKENS)
2110 218 : : CSLAddString(nullptr, value.c_str()));
2111 109 : if (!cpl::contains(inConstructionValues, arg))
2112 : {
2113 107 : inConstructionValues[arg] = std::vector<double>();
2114 : }
2115 : auto &valueVector =
2116 109 : std::get<std::vector<double>>(inConstructionValues[arg]);
2117 442 : for (const char *v : aosTokens)
2118 : {
2119 337 : char *endptr = nullptr;
2120 337 : double dfValue = CPLStrtod(v, &endptr);
2121 337 : if (strlen(v) == 0 || endptr != v + strlen(v))
2122 : {
2123 4 : ReportError(
2124 : CE_Failure, CPLE_IllegalArg,
2125 : "Expected list of real value for argument '%s', "
2126 : "but got '%s'.",
2127 : name.c_str(), value.c_str());
2128 4 : return false;
2129 : }
2130 333 : valueVector.push_back(dfValue);
2131 : }
2132 105 : if (arg->GetMaxCount() == 1)
2133 : {
2134 2 : bool ret = arg->Set(std::move(valueVector));
2135 2 : inConstructionValues.erase(inConstructionValues.find(arg));
2136 2 : return ret;
2137 : }
2138 :
2139 103 : break;
2140 : }
2141 :
2142 795 : case GAAT_DATASET_LIST:
2143 : {
2144 795 : if (!cpl::contains(inConstructionValues, arg))
2145 : {
2146 787 : inConstructionValues[arg] = std::vector<GDALArgDatasetValue>();
2147 : }
2148 : auto &valueVector = std::get<std::vector<GDALArgDatasetValue>>(
2149 795 : inConstructionValues[arg]);
2150 795 : if (!value.empty() && value[0] == '{' && value.back() == '}')
2151 : {
2152 12 : valueVector.push_back(GDALArgDatasetValue(value));
2153 : }
2154 : else
2155 : {
2156 : const CPLStringList aosTokens(
2157 783 : arg->GetPackedValuesAllowed()
2158 6 : ? CSLTokenizeString2(value.c_str(), ",",
2159 : CSLT_HONOURSTRINGS |
2160 : CSLT_STRIPLEADSPACES)
2161 1572 : : CSLAddString(nullptr, value.c_str()));
2162 1569 : for (const char *v : aosTokens)
2163 : {
2164 786 : valueVector.push_back(GDALArgDatasetValue(v));
2165 : }
2166 : }
2167 795 : if (arg->GetMaxCount() == 1)
2168 : {
2169 687 : bool ret = arg->Set(std::move(valueVector));
2170 687 : inConstructionValues.erase(inConstructionValues.find(arg));
2171 687 : return ret;
2172 : }
2173 :
2174 108 : break;
2175 : }
2176 : }
2177 :
2178 533 : return true;
2179 : }
2180 :
2181 : /************************************************************************/
2182 : /* FormatSuggestionsAsString() */
2183 : /************************************************************************/
2184 :
2185 : static std::string
2186 6 : FormatSuggestionsAsString(const std::vector<std::string> &suggestions,
2187 : bool addDashDashPrefix)
2188 : {
2189 6 : std::string ret;
2190 14 : for (auto [i, suggestion] : cpl::enumerate(suggestions))
2191 : {
2192 8 : if (i > 0)
2193 : {
2194 2 : ret += (i + 1 < suggestions.size()) ? ", " : " or ";
2195 : }
2196 8 : ret += '\'';
2197 8 : if (addDashDashPrefix)
2198 6 : ret += "--";
2199 8 : ret += suggestion;
2200 8 : ret += '\'';
2201 : }
2202 6 : return ret;
2203 : }
2204 :
2205 : /************************************************************************/
2206 : /* GDALAlgorithm::ParseCommandLineArguments() */
2207 : /************************************************************************/
2208 :
2209 2365 : bool GDALAlgorithm::ParseCommandLineArguments(
2210 : const std::vector<std::string> &args)
2211 : {
2212 2365 : if (m_parsedSubStringAlreadyCalled)
2213 : {
2214 6 : ReportError(CE_Failure, CPLE_AppDefined,
2215 : "ParseCommandLineArguments() can only be called once per "
2216 : "instance.");
2217 6 : return false;
2218 : }
2219 2359 : m_parsedSubStringAlreadyCalled = true;
2220 :
2221 : // AWS like syntax supported too (not advertized)
2222 2359 : if (args.size() == 1 && args[0] == "help")
2223 : {
2224 1 : auto arg = GetArg("help");
2225 1 : assert(arg);
2226 1 : arg->Set(true);
2227 1 : arg->RunActions();
2228 1 : return true;
2229 : }
2230 :
2231 2358 : if (HasSubAlgorithms())
2232 : {
2233 495 : if (args.empty())
2234 : {
2235 2 : ReportError(CE_Failure, CPLE_AppDefined, "Missing %s name.",
2236 2 : m_callPath.size() == 1 ? "command" : "subcommand");
2237 2 : return false;
2238 : }
2239 493 : if (!args[0].empty() && args[0][0] == '-')
2240 : {
2241 : // go on argument parsing
2242 : }
2243 : else
2244 : {
2245 490 : const auto nCounter = CPLGetErrorCounter();
2246 490 : m_selectedSubAlgHolder = InstantiateSubAlgorithm(args[0]);
2247 490 : if (m_selectedSubAlgHolder)
2248 : {
2249 487 : m_selectedSubAlg = m_selectedSubAlgHolder.get();
2250 487 : m_selectedSubAlg->SetReferencePathForRelativePaths(
2251 487 : m_referencePath);
2252 487 : m_selectedSubAlg->m_executionForStreamOutput =
2253 487 : m_executionForStreamOutput;
2254 487 : m_selectedSubAlg->m_calledFromCommandLine =
2255 487 : m_calledFromCommandLine;
2256 487 : m_selectedSubAlg->m_skipValidationInParseCommandLine =
2257 487 : m_skipValidationInParseCommandLine;
2258 487 : bool bRet = m_selectedSubAlg->ParseCommandLineArguments(
2259 974 : std::vector<std::string>(args.begin() + 1, args.end()));
2260 487 : m_selectedSubAlg->PropagateSpecialActionTo(this);
2261 487 : return bRet;
2262 : }
2263 : else
2264 : {
2265 4 : if (!(CPLGetErrorCounter() == nCounter + 1 &&
2266 1 : strstr(CPLGetLastErrorMsg(), "Do you mean")))
2267 : {
2268 2 : ReportError(CE_Failure, CPLE_AppDefined,
2269 2 : "Unknown command: '%s'", args[0].c_str());
2270 : }
2271 3 : return false;
2272 : }
2273 : }
2274 : }
2275 :
2276 : std::map<
2277 : GDALAlgorithmArg *,
2278 : std::variant<std::vector<std::string>, std::vector<int>,
2279 : std::vector<double>, std::vector<GDALArgDatasetValue>>>
2280 3732 : inConstructionValues;
2281 :
2282 2230 : const auto ProcessInConstructionValues = [&inConstructionValues]()
2283 : {
2284 2196 : for (auto &[arg, value] : inConstructionValues)
2285 : {
2286 492 : if (arg->GetType() == GAAT_STRING_LIST)
2287 : {
2288 239 : if (!arg->Set(std::get<std::vector<std::string>>(
2289 239 : inConstructionValues[arg])))
2290 : {
2291 34 : return false;
2292 : }
2293 : }
2294 253 : else if (arg->GetType() == GAAT_INTEGER_LIST)
2295 : {
2296 52 : if (!arg->Set(
2297 52 : std::get<std::vector<int>>(inConstructionValues[arg])))
2298 : {
2299 4 : return false;
2300 : }
2301 : }
2302 201 : else if (arg->GetType() == GAAT_REAL_LIST)
2303 : {
2304 101 : if (!arg->Set(std::get<std::vector<double>>(
2305 101 : inConstructionValues[arg])))
2306 : {
2307 10 : return false;
2308 : }
2309 : }
2310 100 : else if (arg->GetType() == GAAT_DATASET_LIST)
2311 : {
2312 100 : if (!arg->Set(
2313 : std::move(std::get<std::vector<GDALArgDatasetValue>>(
2314 100 : inConstructionValues[arg]))))
2315 : {
2316 2 : return false;
2317 : }
2318 : }
2319 : }
2320 1704 : return true;
2321 1866 : };
2322 :
2323 3732 : std::vector<std::string> lArgs(args);
2324 1866 : bool helpValueRequested = false;
2325 5328 : for (size_t i = 0; i < lArgs.size(); /* incremented in loop */)
2326 : {
2327 3575 : const auto &strArg = lArgs[i];
2328 3575 : GDALAlgorithmArg *arg = nullptr;
2329 3575 : std::string name;
2330 3575 : std::string value;
2331 3575 : bool hasValue = false;
2332 3575 : if (m_calledFromCommandLine && cpl::ends_with(strArg, "=?"))
2333 5 : helpValueRequested = true;
2334 3575 : if (strArg.size() >= 2 && strArg[0] == '-' && strArg[1] == '-')
2335 : {
2336 2203 : const auto equalPos = strArg.find('=');
2337 4406 : name = (equalPos != std::string::npos) ? strArg.substr(0, equalPos)
2338 2203 : : strArg;
2339 2203 : const std::string nameWithoutDash = name.substr(2);
2340 2203 : auto iterArg = m_mapLongNameToArg.find(nameWithoutDash);
2341 2259 : if (m_arbitraryLongNameArgsAllowed &&
2342 2259 : iterArg == m_mapLongNameToArg.end())
2343 : {
2344 17 : GetArg(nameWithoutDash);
2345 17 : iterArg = m_mapLongNameToArg.find(nameWithoutDash);
2346 : }
2347 2203 : if (iterArg == m_mapLongNameToArg.end())
2348 : {
2349 : const auto suggestions =
2350 28 : GetSuggestionsForArgumentName(nameWithoutDash);
2351 28 : if (!suggestions.empty())
2352 : {
2353 3 : ReportError(CE_Failure, CPLE_IllegalArg,
2354 : "Option '%s' is unknown. Do you mean %s?",
2355 : name.c_str(),
2356 6 : FormatSuggestionsAsString(
2357 : suggestions, /* addDashDashPrefix = */ true)
2358 : .c_str());
2359 : }
2360 : else
2361 : {
2362 25 : ReportError(CE_Failure, CPLE_IllegalArg,
2363 : "Option '%s' is unknown.", name.c_str());
2364 : }
2365 28 : return false;
2366 : }
2367 2175 : arg = iterArg->second;
2368 2175 : if (equalPos != std::string::npos)
2369 : {
2370 469 : hasValue = true;
2371 469 : value = strArg.substr(equalPos + 1);
2372 : }
2373 : }
2374 1451 : else if (strArg.size() >= 2 && strArg[0] == '-' &&
2375 79 : CPLGetValueType(strArg.c_str()) == CPL_VALUE_STRING)
2376 : {
2377 153 : for (size_t j = 1; j < strArg.size(); ++j)
2378 : {
2379 79 : name.clear();
2380 79 : name += strArg[j];
2381 79 : const auto iterArg = m_mapShortNameToArg.find(name);
2382 79 : if (iterArg == m_mapShortNameToArg.end())
2383 : {
2384 5 : const std::string nameWithoutDash = strArg.substr(1);
2385 5 : if (m_mapLongNameToArg.find(nameWithoutDash) !=
2386 10 : m_mapLongNameToArg.end())
2387 : {
2388 1 : ReportError(CE_Failure, CPLE_IllegalArg,
2389 : "Short name option '%s' is unknown. Do you "
2390 : "mean '--%s' (with leading double dash) ?",
2391 : name.c_str(), nameWithoutDash.c_str());
2392 : }
2393 : else
2394 : {
2395 : const auto suggestions =
2396 8 : GetSuggestionsForArgumentName(nameWithoutDash);
2397 4 : if (!suggestions.empty())
2398 : {
2399 1 : ReportError(
2400 : CE_Failure, CPLE_IllegalArg,
2401 : "Short name option '%s' is unknown. Do you "
2402 : "mean %s (with leading double dash) ?",
2403 : name.c_str(),
2404 2 : FormatSuggestionsAsString(
2405 : suggestions, /* addDashDashPrefix = */ true)
2406 : .c_str());
2407 : }
2408 : else
2409 : {
2410 3 : ReportError(CE_Failure, CPLE_IllegalArg,
2411 : "Short name option '%s' is unknown.",
2412 : name.c_str());
2413 : }
2414 : }
2415 5 : return false;
2416 : }
2417 74 : arg = iterArg->second;
2418 74 : if (strArg.size() > 2)
2419 : {
2420 0 : if (arg->GetType() != GAAT_BOOLEAN)
2421 : {
2422 0 : ReportError(CE_Failure, CPLE_IllegalArg,
2423 : "Invalid argument '%s'. Option '%s' is not "
2424 : "a boolean option.",
2425 : strArg.c_str(), name.c_str());
2426 0 : return false;
2427 : }
2428 :
2429 0 : if (!ParseArgument(arg, name, "true", inConstructionValues))
2430 0 : return false;
2431 : }
2432 : }
2433 74 : if (strArg.size() > 2)
2434 : {
2435 0 : lArgs.erase(lArgs.begin() + i);
2436 0 : continue;
2437 : }
2438 : }
2439 : else
2440 : {
2441 1293 : ++i;
2442 1293 : continue;
2443 : }
2444 2249 : CPLAssert(arg);
2445 :
2446 2249 : if (arg && arg->GetType() == GAAT_BOOLEAN)
2447 : {
2448 337 : if (!hasValue)
2449 : {
2450 334 : hasValue = true;
2451 334 : value = "true";
2452 : }
2453 : }
2454 :
2455 2249 : lArgs.erase(lArgs.begin() + i);
2456 :
2457 2249 : if (!hasValue)
2458 : {
2459 1446 : if (i == lArgs.size())
2460 : {
2461 41 : if (m_parseForAutoCompletion)
2462 : {
2463 35 : break;
2464 : }
2465 6 : ReportError(
2466 : CE_Failure, CPLE_IllegalArg,
2467 : "Expected value for argument '%s', but ran short of tokens",
2468 : name.c_str());
2469 6 : return false;
2470 : }
2471 1405 : value = lArgs[i];
2472 1405 : lArgs.erase(lArgs.begin() + i);
2473 : }
2474 :
2475 2208 : if (arg && !ParseArgument(arg, name, value, inConstructionValues))
2476 : {
2477 39 : return false;
2478 : }
2479 :
2480 : // Consume next strings if it is a positional argument, until finding
2481 : // a value starting with dash.
2482 2549 : if (!hasValue && arg && GDALAlgorithmArgTypeIsList(arg->GetType()) &&
2483 380 : std::find(m_positionalArgs.begin(), m_positionalArgs.end(), arg) !=
2484 2549 : m_positionalArgs.end())
2485 : {
2486 112 : int countVals = 1;
2487 113 : while (i < lArgs.size() && !lArgs[i].empty() && lArgs[i][0] != '-')
2488 : {
2489 5 : if (countVals == arg->GetMaxCount())
2490 4 : break;
2491 1 : if (!ParseArgument(arg, name, lArgs[i], inConstructionValues))
2492 : {
2493 0 : ProcessInConstructionValues();
2494 0 : return false;
2495 : }
2496 1 : lArgs.erase(lArgs.begin() + i);
2497 1 : ++countVals;
2498 : }
2499 : }
2500 : }
2501 :
2502 1788 : if (m_specialActionRequested)
2503 : {
2504 26 : return true;
2505 : }
2506 :
2507 : // Process positional arguments that have not been set through their
2508 : // option name.
2509 1762 : size_t i = 0;
2510 1762 : size_t iCurPosArg = 0;
2511 :
2512 : // Special case for <INPUT> <AUXILIARY>... <OUTPUT>
2513 1794 : if (m_positionalArgs.size() == 3 &&
2514 33 : (m_positionalArgs[0]->IsRequired() ||
2515 32 : m_positionalArgs[0]->GetMinCount() == 1) &&
2516 62 : m_positionalArgs[0]->GetMaxCount() == 1 &&
2517 38 : (m_positionalArgs[1]->IsRequired() ||
2518 38 : m_positionalArgs[1]->GetMinCount() == 1) &&
2519 : /* Second argument may have several occurrences */
2520 62 : m_positionalArgs[1]->GetMaxCount() >= 1 &&
2521 49 : (m_positionalArgs[2]->IsRequired() ||
2522 31 : m_positionalArgs[2]->GetMinCount() == 1) &&
2523 13 : m_positionalArgs[2]->GetMaxCount() == 1 &&
2524 9 : !m_positionalArgs[0]->IsExplicitlySet() &&
2525 1803 : !m_positionalArgs[1]->IsExplicitlySet() &&
2526 9 : !m_positionalArgs[2]->IsExplicitlySet())
2527 : {
2528 7 : if (lArgs.size() - i < 3)
2529 : {
2530 1 : ReportError(CE_Failure, CPLE_AppDefined,
2531 : "Not enough positional values.");
2532 1 : return false;
2533 : }
2534 12 : bool ok = ParseArgument(m_positionalArgs[0],
2535 6 : m_positionalArgs[0]->GetName().c_str(),
2536 6 : lArgs[i], inConstructionValues);
2537 6 : if (ok)
2538 : {
2539 5 : ++i;
2540 11 : for (; i + 1 < lArgs.size() && ok; ++i)
2541 : {
2542 12 : ok = ParseArgument(m_positionalArgs[1],
2543 6 : m_positionalArgs[1]->GetName().c_str(),
2544 6 : lArgs[i], inConstructionValues);
2545 : }
2546 : }
2547 6 : if (ok)
2548 : {
2549 10 : ok = ParseArgument(m_positionalArgs[2],
2550 10 : m_positionalArgs[2]->GetName().c_str(), lArgs[i],
2551 : inConstructionValues);
2552 5 : ++i;
2553 : }
2554 6 : if (!ok)
2555 : {
2556 3 : ProcessInConstructionValues();
2557 3 : return false;
2558 : }
2559 : }
2560 :
2561 588 : if (m_inputDatasetCanBeOmitted && m_positionalArgs.size() >= 1 &&
2562 652 : !m_positionalArgs[0]->IsExplicitlySet() &&
2563 2676 : m_positionalArgs[0]->GetName() == GDAL_ARG_NAME_INPUT &&
2564 78 : (m_positionalArgs[0]->GetType() == GAAT_DATASET ||
2565 39 : m_positionalArgs[0]->GetType() == GAAT_DATASET_LIST))
2566 : {
2567 39 : ++iCurPosArg;
2568 : }
2569 :
2570 2971 : while (i < lArgs.size() && iCurPosArg < m_positionalArgs.size())
2571 : {
2572 1220 : GDALAlgorithmArg *arg = m_positionalArgs[iCurPosArg];
2573 1231 : while (arg->IsExplicitlySet())
2574 : {
2575 12 : ++iCurPosArg;
2576 12 : if (iCurPosArg == m_positionalArgs.size())
2577 1 : break;
2578 11 : arg = m_positionalArgs[iCurPosArg];
2579 : }
2580 1220 : if (iCurPosArg == m_positionalArgs.size())
2581 : {
2582 1 : break;
2583 : }
2584 1905 : if (GDALAlgorithmArgTypeIsList(arg->GetType()) &&
2585 686 : arg->GetMinCount() != arg->GetMaxCount())
2586 : {
2587 102 : if (iCurPosArg == 0)
2588 : {
2589 80 : size_t nCountAtEnd = 0;
2590 109 : for (size_t j = 1; j < m_positionalArgs.size(); j++)
2591 : {
2592 31 : const auto *otherArg = m_positionalArgs[j];
2593 31 : if (GDALAlgorithmArgTypeIsList(otherArg->GetType()))
2594 : {
2595 4 : if (otherArg->GetMinCount() != otherArg->GetMaxCount())
2596 : {
2597 2 : ReportError(
2598 : CE_Failure, CPLE_AppDefined,
2599 : "Ambiguity in definition of positional "
2600 : "argument "
2601 : "'%s' given it has a varying number of values, "
2602 : "but follows argument '%s' which also has a "
2603 : "varying number of values",
2604 1 : otherArg->GetName().c_str(),
2605 1 : arg->GetName().c_str());
2606 1 : ProcessInConstructionValues();
2607 1 : return false;
2608 : }
2609 3 : nCountAtEnd += otherArg->GetMinCount();
2610 : }
2611 : else
2612 : {
2613 27 : if (!otherArg->IsRequired())
2614 : {
2615 2 : ReportError(
2616 : CE_Failure, CPLE_AppDefined,
2617 : "Ambiguity in definition of positional "
2618 : "argument "
2619 : "'%s', given it is not required but follows "
2620 : "argument '%s' which has a varying number of "
2621 : "values",
2622 1 : otherArg->GetName().c_str(),
2623 1 : arg->GetName().c_str());
2624 1 : ProcessInConstructionValues();
2625 1 : return false;
2626 : }
2627 26 : nCountAtEnd++;
2628 : }
2629 : }
2630 78 : if (lArgs.size() < nCountAtEnd)
2631 : {
2632 1 : ReportError(CE_Failure, CPLE_AppDefined,
2633 : "Not enough positional values.");
2634 1 : ProcessInConstructionValues();
2635 1 : return false;
2636 : }
2637 162 : for (; i < lArgs.size() - nCountAtEnd; ++i)
2638 : {
2639 85 : if (!ParseArgument(arg, arg->GetName().c_str(), lArgs[i],
2640 : inConstructionValues))
2641 : {
2642 0 : ProcessInConstructionValues();
2643 0 : return false;
2644 : }
2645 : }
2646 : }
2647 22 : else if (iCurPosArg == m_positionalArgs.size() - 1)
2648 : {
2649 49 : for (; i < lArgs.size(); ++i)
2650 : {
2651 28 : if (!ParseArgument(arg, arg->GetName().c_str(), lArgs[i],
2652 : inConstructionValues))
2653 : {
2654 0 : ProcessInConstructionValues();
2655 0 : return false;
2656 : }
2657 : }
2658 : }
2659 : else
2660 : {
2661 1 : ReportError(CE_Failure, CPLE_AppDefined,
2662 : "Ambiguity in definition of positional arguments: "
2663 : "arguments with varying number of values must be "
2664 : "first or last one.");
2665 1 : return false;
2666 : }
2667 : }
2668 : else
2669 : {
2670 1117 : if (lArgs.size() - i < static_cast<size_t>(arg->GetMaxCount()))
2671 : {
2672 1 : ReportError(CE_Failure, CPLE_AppDefined,
2673 : "Not enough positional values.");
2674 1 : return false;
2675 : }
2676 1116 : const size_t iMax = i + arg->GetMaxCount();
2677 2235 : for (; i < iMax; ++i)
2678 : {
2679 1120 : if (!ParseArgument(arg, arg->GetName().c_str(), lArgs[i],
2680 : inConstructionValues))
2681 : {
2682 1 : ProcessInConstructionValues();
2683 1 : return false;
2684 : }
2685 : }
2686 : }
2687 1213 : ++iCurPosArg;
2688 : }
2689 :
2690 1752 : if (i < lArgs.size())
2691 : {
2692 21 : ReportError(CE_Failure, CPLE_AppDefined,
2693 : "Positional values starting at '%s' are not expected.",
2694 21 : lArgs[i].c_str());
2695 21 : return false;
2696 : }
2697 :
2698 1731 : if (!ProcessInConstructionValues())
2699 : {
2700 33 : return false;
2701 : }
2702 :
2703 : // Skip to first unset positional argument.
2704 2796 : while (iCurPosArg < m_positionalArgs.size() &&
2705 603 : m_positionalArgs[iCurPosArg]->IsExplicitlySet())
2706 : {
2707 495 : ++iCurPosArg;
2708 : }
2709 : // Check if this positional argument is required.
2710 1805 : if (iCurPosArg < m_positionalArgs.size() && !helpValueRequested &&
2711 107 : (GDALAlgorithmArgTypeIsList(m_positionalArgs[iCurPosArg]->GetType())
2712 59 : ? m_positionalArgs[iCurPosArg]->GetMinCount() > 0
2713 48 : : m_positionalArgs[iCurPosArg]->IsRequired()))
2714 : {
2715 87 : ReportError(CE_Failure, CPLE_AppDefined,
2716 : "Positional arguments starting at '%s' have not been "
2717 : "specified.",
2718 87 : m_positionalArgs[iCurPosArg]->GetMetaVar().c_str());
2719 87 : return false;
2720 : }
2721 :
2722 1611 : if (m_calledFromCommandLine)
2723 : {
2724 5522 : for (auto &arg : m_args)
2725 : {
2726 7138 : if (arg->IsExplicitlySet() &&
2727 1105 : ((arg->GetType() == GAAT_STRING &&
2728 1102 : arg->Get<std::string>() == "?") ||
2729 999 : (arg->GetType() == GAAT_STRING_LIST &&
2730 157 : arg->Get<std::vector<std::string>>().size() == 1 &&
2731 78 : arg->Get<std::vector<std::string>>()[0] == "?")))
2732 : {
2733 : {
2734 10 : CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
2735 5 : ValidateArguments();
2736 : }
2737 :
2738 5 : auto choices = arg->GetChoices();
2739 5 : if (choices.empty())
2740 2 : choices = arg->GetAutoCompleteChoices(std::string());
2741 5 : if (!choices.empty())
2742 : {
2743 5 : if (choices.size() == 1)
2744 : {
2745 4 : ReportError(
2746 : CE_Failure, CPLE_AppDefined,
2747 : "Single potential value for argument '%s' is '%s'",
2748 4 : arg->GetName().c_str(), choices.front().c_str());
2749 : }
2750 : else
2751 : {
2752 6 : std::string msg("Potential values for argument '");
2753 3 : msg += arg->GetName();
2754 3 : msg += "' are:";
2755 45 : for (const auto &v : choices)
2756 : {
2757 42 : msg += "\n- ";
2758 42 : msg += v;
2759 : }
2760 3 : ReportError(CE_Failure, CPLE_AppDefined, "%s",
2761 : msg.c_str());
2762 : }
2763 5 : return false;
2764 : }
2765 : }
2766 : }
2767 : }
2768 :
2769 1606 : return m_skipValidationInParseCommandLine || ValidateArguments();
2770 : }
2771 :
2772 : /************************************************************************/
2773 : /* GDALAlgorithm::ReportError() */
2774 : /************************************************************************/
2775 :
2776 : //! @cond Doxygen_Suppress
2777 981 : void GDALAlgorithm::ReportError(CPLErr eErrClass, CPLErrorNum err_no,
2778 : const char *fmt, ...) const
2779 : {
2780 : va_list args;
2781 981 : va_start(args, fmt);
2782 981 : CPLError(eErrClass, err_no, "%s",
2783 981 : std::string(m_name)
2784 981 : .append(": ")
2785 1962 : .append(CPLString().vPrintf(fmt, args))
2786 : .c_str());
2787 981 : va_end(args);
2788 981 : }
2789 :
2790 : //! @endcond
2791 :
2792 : /************************************************************************/
2793 : /* GDALAlgorithm::ProcessDatasetArg() */
2794 : /************************************************************************/
2795 :
2796 11319 : bool GDALAlgorithm::ProcessDatasetArg(GDALAlgorithmArg *arg,
2797 : GDALAlgorithm *algForOutput)
2798 : {
2799 11319 : bool ret = true;
2800 :
2801 11319 : const auto updateArg = algForOutput->GetArg(GDAL_ARG_NAME_UPDATE);
2802 11319 : const bool hasUpdateArg = updateArg && updateArg->GetType() == GAAT_BOOLEAN;
2803 11319 : const bool update = hasUpdateArg && updateArg->Get<bool>();
2804 :
2805 11319 : const auto appendArg = algForOutput->GetArg(GDAL_ARG_NAME_APPEND);
2806 11319 : const bool hasAppendArg = appendArg && appendArg->GetType() == GAAT_BOOLEAN;
2807 11319 : const bool append = hasAppendArg && appendArg->Get<bool>();
2808 :
2809 11319 : const auto overwriteArg = algForOutput->GetArg(GDAL_ARG_NAME_OVERWRITE);
2810 : const bool overwrite =
2811 18624 : (arg->IsOutput() && overwriteArg &&
2812 18624 : overwriteArg->GetType() == GAAT_BOOLEAN && overwriteArg->Get<bool>());
2813 :
2814 11319 : auto outputArg = algForOutput->GetArg(GDAL_ARG_NAME_OUTPUT);
2815 22638 : auto &val = [arg]() -> GDALArgDatasetValue &
2816 : {
2817 11319 : if (arg->GetType() == GAAT_DATASET_LIST)
2818 6641 : return arg->Get<std::vector<GDALArgDatasetValue>>()[0];
2819 : else
2820 4678 : return arg->Get<GDALArgDatasetValue>();
2821 11319 : }();
2822 : const bool onlyInputSpecifiedInUpdateAndOutputNotRequired =
2823 17980 : arg->GetName() == GDAL_ARG_NAME_INPUT && outputArg &&
2824 17988 : !outputArg->IsExplicitlySet() && !outputArg->IsRequired() && update &&
2825 8 : !overwrite;
2826 :
2827 : // Used for nested pipelines
2828 : const auto oIterDatasetNameToDataset =
2829 22635 : val.IsNameSet() ? m_oMapDatasetNameToDataset.find(val.GetName())
2830 11319 : : m_oMapDatasetNameToDataset.end();
2831 :
2832 11319 : if (!val.GetDatasetRef() && !val.IsNameSet())
2833 : {
2834 3 : ReportError(CE_Failure, CPLE_AppDefined,
2835 : "Argument '%s' has no dataset object or dataset name.",
2836 3 : arg->GetName().c_str());
2837 3 : ret = false;
2838 : }
2839 11316 : else if (val.GetDatasetRef() && !CheckCanSetDatasetObject(arg))
2840 : {
2841 3 : return false;
2842 : }
2843 316 : else if (m_inputDatasetCanBeOmitted &&
2844 11629 : val.GetName() == GDAL_DATASET_PIPELINE_PLACEHOLDER_VALUE &&
2845 17 : !arg->IsOutput())
2846 : {
2847 17 : return true;
2848 : }
2849 16701 : else if (!val.GetDatasetRef() &&
2850 5727 : (arg->AutoOpenDataset() ||
2851 17023 : oIterDatasetNameToDataset != m_oMapDatasetNameToDataset.end()) &&
2852 5084 : (!arg->IsOutput() || (arg == outputArg && update && !overwrite) ||
2853 : onlyInputSpecifiedInUpdateAndOutputNotRequired))
2854 : {
2855 1555 : int flags = arg->GetDatasetType();
2856 1555 : bool assignToOutputArg = false;
2857 :
2858 : // Check if input and output parameters point to the same
2859 : // filename (for vector datasets)
2860 2883 : if (arg->GetName() == GDAL_ARG_NAME_INPUT && update && !overwrite &&
2861 2883 : outputArg && outputArg->GetType() == GAAT_DATASET)
2862 : {
2863 62 : auto &outputVal = outputArg->Get<GDALArgDatasetValue>();
2864 121 : if (!outputVal.GetDatasetRef() &&
2865 121 : outputVal.GetName() == val.GetName() &&
2866 2 : (outputArg->GetDatasetInputFlags() & GADV_OBJECT) != 0)
2867 : {
2868 2 : assignToOutputArg = true;
2869 2 : flags |= GDAL_OF_UPDATE | GDAL_OF_VERBOSE_ERROR;
2870 : }
2871 60 : else if (onlyInputSpecifiedInUpdateAndOutputNotRequired)
2872 : {
2873 2 : flags |= GDAL_OF_UPDATE | GDAL_OF_VERBOSE_ERROR;
2874 : }
2875 : }
2876 :
2877 1555 : if (!arg->IsOutput() || arg->GetDatasetInputFlags() == GADV_NAME)
2878 1472 : flags |= GDAL_OF_VERBOSE_ERROR;
2879 1555 : if ((arg == outputArg || !outputArg) && update)
2880 : {
2881 85 : flags |= GDAL_OF_UPDATE;
2882 85 : if (!append)
2883 64 : flags |= GDAL_OF_VERBOSE_ERROR;
2884 : }
2885 :
2886 1555 : const auto readOnlyArg = GetArg(GDAL_ARG_NAME_READ_ONLY);
2887 : const bool readOnly =
2888 1599 : (readOnlyArg && readOnlyArg->GetType() == GAAT_BOOLEAN &&
2889 44 : readOnlyArg->Get<bool>());
2890 1555 : if (readOnly)
2891 12 : flags &= ~GDAL_OF_UPDATE;
2892 :
2893 3110 : CPLStringList aosOpenOptions;
2894 3110 : CPLStringList aosAllowedDrivers;
2895 1555 : if (arg->IsInput())
2896 : {
2897 1555 : if (arg == outputArg)
2898 : {
2899 83 : if (update && !overwrite)
2900 : {
2901 83 : const auto ooArg = GetArg(GDAL_ARG_NAME_OUTPUT_OPEN_OPTION);
2902 83 : if (ooArg && ooArg->GetType() == GAAT_STRING_LIST)
2903 46 : aosOpenOptions = CPLStringList(
2904 46 : ooArg->Get<std::vector<std::string>>());
2905 : }
2906 : }
2907 : else
2908 : {
2909 1472 : const auto ooArg = GetArg(GDAL_ARG_NAME_OPEN_OPTION);
2910 1472 : if (ooArg && ooArg->GetType() == GAAT_STRING_LIST)
2911 : aosOpenOptions =
2912 1393 : CPLStringList(ooArg->Get<std::vector<std::string>>());
2913 :
2914 1472 : const auto ifArg = GetArg(GDAL_ARG_NAME_INPUT_FORMAT);
2915 1472 : if (ifArg && ifArg->GetType() == GAAT_STRING_LIST)
2916 : aosAllowedDrivers =
2917 1349 : CPLStringList(ifArg->Get<std::vector<std::string>>());
2918 : }
2919 : }
2920 :
2921 3110 : std::string osDatasetName = val.GetName();
2922 1555 : if (!m_referencePath.empty())
2923 : {
2924 46 : osDatasetName = GDALDataset::BuildFilename(
2925 23 : osDatasetName.c_str(), m_referencePath.c_str(), true);
2926 : }
2927 1555 : if (osDatasetName == "-" && (flags & GDAL_OF_UPDATE) == 0)
2928 0 : osDatasetName = "/vsistdin/";
2929 :
2930 : // Handle special case of overview delete in GTiff which would fail
2931 : // if it is COG without IGNORE_COG_LAYOUT_BREAK=YES open option.
2932 145 : if ((flags & GDAL_OF_UPDATE) != 0 && m_callPath.size() == 4 &&
2933 1702 : m_callPath[2] == "overview" && m_callPath[3] == "delete" &&
2934 2 : aosOpenOptions.FetchNameValue("IGNORE_COG_LAYOUT_BREAK") == nullptr)
2935 : {
2936 4 : CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
2937 : GDALDriverH hDrv =
2938 2 : GDALIdentifyDriver(osDatasetName.c_str(), nullptr);
2939 2 : if (hDrv && EQUAL(GDALGetDescription(hDrv), "GTiff"))
2940 : {
2941 : // Cleaning does not break COG layout
2942 2 : aosOpenOptions.SetNameValue("IGNORE_COG_LAYOUT_BREAK", "YES");
2943 : }
2944 : }
2945 :
2946 : GDALDataset *poDS;
2947 3110 : CPLErrorAccumulator oAccumulator;
2948 : {
2949 3110 : auto oContext = oAccumulator.InstallForCurrentScope();
2950 :
2951 1555 : poDS = oIterDatasetNameToDataset != m_oMapDatasetNameToDataset.end()
2952 1555 : ? oIterDatasetNameToDataset->second
2953 1539 : : GDALDataset::Open(osDatasetName.c_str(), flags,
2954 1539 : aosAllowedDrivers.List(),
2955 1539 : aosOpenOptions.List());
2956 :
2957 71 : if (!poDS && aosAllowedDrivers.empty() && aosOpenOptions.empty() &&
2958 1626 : !arg->IsOutput() && arg->GetDatasetType() & GDAL_OF_VECTOR)
2959 : {
2960 41 : auto [poWktGeom, eErr] = OGRGeometryFactory::createFromWkt(
2961 82 : osDatasetName.c_str(), nullptr);
2962 41 : if (eErr == OGRERR_NONE)
2963 : {
2964 12 : auto poMemDS = std::make_unique<MEMDataset>();
2965 12 : auto *poLayer = poMemDS->CreateLayer(
2966 : "layer", poWktGeom->getSpatialReference(),
2967 6 : poWktGeom->getGeometryType());
2968 :
2969 6 : auto poFeatureDefn = poLayer->GetLayerDefn();
2970 12 : OGRFeature oFeature(poFeatureDefn);
2971 :
2972 6 : oFeature.SetGeometry(std::move(poWktGeom));
2973 6 : if (poLayer->CreateFeature(&oFeature) == OGRERR_NONE)
2974 : {
2975 6 : poDS = poMemDS.release();
2976 6 : oAccumulator.ClearErrors();
2977 : }
2978 : }
2979 : }
2980 :
2981 : // Retry with PostGIS vector driver
2982 65 : if (!poDS && (flags & (GDAL_OF_RASTER | GDAL_OF_VECTOR)) != 0 &&
2983 63 : cpl::starts_with(osDatasetName, "PG:") &&
2984 0 : GetGDALDriverManager()->GetDriverByName("PostGISRaster") &&
2985 1620 : aosAllowedDrivers.empty() && aosOpenOptions.empty())
2986 : {
2987 0 : oAccumulator.ClearErrors();
2988 0 : poDS = GDALDataset::Open(
2989 0 : osDatasetName.c_str(), flags & ~GDAL_OF_RASTER,
2990 0 : aosAllowedDrivers.List(), aosOpenOptions.List());
2991 : }
2992 : }
2993 1555 : oAccumulator.ReplayErrors();
2994 :
2995 1555 : if (poDS)
2996 : {
2997 1490 : if (oIterDatasetNameToDataset != m_oMapDatasetNameToDataset.end())
2998 : {
2999 16 : if (arg->GetType() == GAAT_DATASET)
3000 8 : arg->Get<GDALArgDatasetValue>().Set(poDS->GetDescription());
3001 16 : poDS->Reference();
3002 16 : m_oMapDatasetNameToDataset.erase(oIterDatasetNameToDataset);
3003 : }
3004 :
3005 : // A bit of a hack for situations like 'gdal raster clip --like "PG:..."'
3006 : // where the PG: dataset will be first opened with the PostGISRaster
3007 : // driver whereas the PostgreSQL (vector) one is actually wanted.
3008 2083 : if (poDS->GetRasterCount() == 0 && (flags & GDAL_OF_RASTER) != 0 &&
3009 2198 : (flags & GDAL_OF_VECTOR) != 0 && aosAllowedDrivers.empty() &&
3010 115 : aosOpenOptions.empty())
3011 : {
3012 111 : auto poDrv = poDS->GetDriver();
3013 111 : if (poDrv && EQUAL(poDrv->GetDescription(), "PostGISRaster"))
3014 : {
3015 : // Retry with PostgreSQL (vector) driver
3016 : std::unique_ptr<GDALDataset> poTmpDS(GDALDataset::Open(
3017 0 : osDatasetName.c_str(), flags & ~GDAL_OF_RASTER));
3018 0 : if (poTmpDS)
3019 : {
3020 0 : poDS->ReleaseRef();
3021 0 : poDS = poTmpDS.release();
3022 : }
3023 : }
3024 : }
3025 :
3026 1490 : if (assignToOutputArg)
3027 : {
3028 : // Avoid opening twice the same datasource if it is both
3029 : // the input and output.
3030 : // Known to cause problems with at least FGdb, SQLite
3031 : // and GPKG drivers. See #4270
3032 : // Restrict to those 3 drivers. For example it is known
3033 : // to break with the PG driver due to the way it
3034 : // manages transactions.
3035 2 : auto poDriver = poDS->GetDriver();
3036 4 : if (poDriver && (EQUAL(poDriver->GetDescription(), "FileGDB") ||
3037 2 : EQUAL(poDriver->GetDescription(), "SQLite") ||
3038 2 : EQUAL(poDriver->GetDescription(), "GPKG")))
3039 : {
3040 2 : outputArg->Get<GDALArgDatasetValue>().Set(poDS);
3041 : }
3042 : }
3043 1490 : val.SetDatasetOpenedByAlgorithm();
3044 1490 : val.Set(poDS);
3045 1490 : poDS->ReleaseRef();
3046 : }
3047 65 : else if (!append)
3048 : {
3049 63 : ret = false;
3050 : }
3051 : }
3052 :
3053 : // Deal with overwriting the output dataset
3054 11299 : if (ret && arg == outputArg && val.GetDatasetRef() == nullptr)
3055 : {
3056 3531 : if (!append)
3057 : {
3058 : // If outputting to MEM, do not try to erase a real file of the same name!
3059 : const auto outputFormatArg =
3060 3519 : algForOutput->GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
3061 10519 : if (!(outputFormatArg &&
3062 3500 : outputFormatArg->GetType() == GAAT_STRING &&
3063 3500 : (EQUAL(outputFormatArg->Get<std::string>().c_str(), "MEM") ||
3064 2292 : EQUAL(outputFormatArg->Get<std::string>().c_str(),
3065 1288 : "stream") ||
3066 1288 : EQUAL(outputFormatArg->Get<std::string>().c_str(),
3067 : "Memory"))))
3068 : {
3069 1307 : const char *pszType = "";
3070 1307 : GDALDriver *poDriver = nullptr;
3071 2568 : if (!val.GetName().empty() &&
3072 1261 : GDALDoesFileOrDatasetExist(val.GetName().c_str(), &pszType,
3073 : &poDriver))
3074 : {
3075 79 : if (!overwrite)
3076 : {
3077 68 : std::string options;
3078 34 : if (algForOutput->GetArg(GDAL_ARG_NAME_OVERWRITE_LAYER))
3079 : {
3080 11 : options += "--";
3081 11 : options += GDAL_ARG_NAME_OVERWRITE_LAYER;
3082 : }
3083 34 : if (hasAppendArg)
3084 : {
3085 22 : if (!options.empty())
3086 8 : options += '/';
3087 22 : options += "--";
3088 22 : options += GDAL_ARG_NAME_APPEND;
3089 : }
3090 34 : if (hasUpdateArg)
3091 : {
3092 15 : if (!options.empty())
3093 12 : options += '/';
3094 15 : options += "--";
3095 15 : options += GDAL_ARG_NAME_UPDATE;
3096 : }
3097 :
3098 34 : if (poDriver)
3099 : {
3100 68 : const char *pszPrefix = poDriver->GetMetadataItem(
3101 34 : GDAL_DMD_CONNECTION_PREFIX);
3102 34 : if (pszPrefix &&
3103 0 : STARTS_WITH_CI(val.GetName().c_str(),
3104 : pszPrefix))
3105 : {
3106 0 : bool bExists = false;
3107 : {
3108 : CPLErrorStateBackuper oBackuper(
3109 0 : CPLQuietErrorHandler);
3110 0 : bExists = std::unique_ptr<GDALDataset>(
3111 : GDALDataset::Open(
3112 0 : val.GetName().c_str())) !=
3113 : nullptr;
3114 : }
3115 0 : if (bExists)
3116 : {
3117 0 : if (!options.empty())
3118 0 : options = " You may specify the " +
3119 0 : options + " option.";
3120 0 : ReportError(CE_Failure, CPLE_AppDefined,
3121 : "%s '%s' already exists.%s",
3122 0 : pszType, val.GetName().c_str(),
3123 : options.c_str());
3124 0 : return false;
3125 : }
3126 :
3127 0 : return true;
3128 : }
3129 : }
3130 :
3131 34 : if (!options.empty())
3132 28 : options = '/' + options;
3133 68 : ReportError(
3134 : CE_Failure, CPLE_AppDefined,
3135 : "%s '%s' already exists. You may specify the "
3136 : "--overwrite%s option.",
3137 34 : pszType, val.GetName().c_str(), options.c_str());
3138 34 : return false;
3139 : }
3140 45 : else if (EQUAL(pszType, "File"))
3141 : {
3142 1 : if (VSIUnlink(val.GetName().c_str()) != 0)
3143 : {
3144 0 : ReportError(CE_Failure, CPLE_AppDefined,
3145 : "Deleting %s failed: %s",
3146 0 : val.GetName().c_str(),
3147 0 : VSIStrerror(errno));
3148 0 : return false;
3149 : }
3150 : }
3151 44 : else if (EQUAL(pszType, "Directory"))
3152 : {
3153 : // We don't want the user to accidentally erase a non-GDAL dataset
3154 1 : ReportError(CE_Failure, CPLE_AppDefined,
3155 : "Directory '%s' already exists, but is not "
3156 : "recognized as a valid GDAL dataset. "
3157 : "Please manually delete it before retrying",
3158 1 : val.GetName().c_str());
3159 1 : return false;
3160 : }
3161 43 : else if (poDriver)
3162 : {
3163 : bool bDeleteOK;
3164 : {
3165 : CPLErrorStateBackuper oBackuper(
3166 43 : CPLQuietErrorHandler);
3167 43 : bDeleteOK = (poDriver->Delete(
3168 43 : val.GetName().c_str()) == CE_None);
3169 : }
3170 : VSIStatBufL sStat;
3171 46 : if (!bDeleteOK &&
3172 3 : VSIStatL(val.GetName().c_str(), &sStat) == 0)
3173 : {
3174 3 : if (VSI_ISDIR(sStat.st_mode))
3175 : {
3176 : // We don't want the user to accidentally erase a non-GDAL dataset
3177 0 : ReportError(
3178 : CE_Failure, CPLE_AppDefined,
3179 : "Directory '%s' already exists, but is not "
3180 : "recognized as a valid GDAL dataset. "
3181 : "Please manually delete it before retrying",
3182 0 : val.GetName().c_str());
3183 2 : return false;
3184 : }
3185 3 : else if (VSIUnlink(val.GetName().c_str()) != 0)
3186 : {
3187 2 : ReportError(CE_Failure, CPLE_AppDefined,
3188 : "Deleting %s failed: %s",
3189 2 : val.GetName().c_str(),
3190 2 : VSIStrerror(errno));
3191 2 : return false;
3192 : }
3193 : }
3194 : }
3195 : }
3196 : }
3197 : }
3198 : }
3199 :
3200 : // If outputting to stdout, automatically turn off progress bar
3201 11262 : if (arg == outputArg && val.GetName() == "/vsistdout/")
3202 : {
3203 8 : auto quietArg = GetArg(GDAL_ARG_NAME_QUIET);
3204 8 : if (quietArg && quietArg->GetType() == GAAT_BOOLEAN)
3205 5 : quietArg->Set(true);
3206 : }
3207 :
3208 11262 : return ret;
3209 : }
3210 :
3211 : /************************************************************************/
3212 : /* GDALAlgorithm::ValidateArguments() */
3213 : /************************************************************************/
3214 :
3215 7897 : bool GDALAlgorithm::ValidateArguments()
3216 : {
3217 7897 : if (m_selectedSubAlg)
3218 3 : return m_selectedSubAlg->ValidateArguments();
3219 :
3220 7894 : if (m_specialActionRequested)
3221 1 : return true;
3222 :
3223 7893 : m_arbitraryLongNameArgsAllowed = false;
3224 :
3225 : // If only --output=format=MEM/stream is specified and not --output,
3226 : // then set empty name for --output.
3227 7893 : auto outputArg = GetArg(GDAL_ARG_NAME_OUTPUT);
3228 7893 : auto outputFormatArg = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
3229 4632 : if (outputArg && outputFormatArg && outputFormatArg->IsExplicitlySet() &&
3230 2948 : !outputArg->IsExplicitlySet() &&
3231 390 : outputFormatArg->GetType() == GAAT_STRING &&
3232 390 : (EQUAL(outputFormatArg->Get<std::string>().c_str(), "MEM") ||
3233 632 : EQUAL(outputFormatArg->Get<std::string>().c_str(), "stream")) &&
3234 12886 : outputArg->GetType() == GAAT_DATASET &&
3235 361 : (outputArg->GetDatasetInputFlags() & GADV_NAME))
3236 : {
3237 361 : outputArg->Get<GDALArgDatasetValue>().Set("");
3238 : }
3239 :
3240 : // The method may emit several errors if several constraints are not met.
3241 7893 : bool ret = true;
3242 15786 : std::map<std::string, std::string> mutualExclusionGroupUsed;
3243 15786 : std::map<std::string, std::vector<std::string>> mutualDependencyGroupUsed;
3244 147217 : for (auto &arg : m_args)
3245 : {
3246 : // Check mutually exclusive/dependent arguments
3247 139324 : if (arg->IsExplicitlySet())
3248 : {
3249 :
3250 21902 : const auto &mutualExclusionGroup = arg->GetMutualExclusionGroup();
3251 21902 : if (!mutualExclusionGroup.empty())
3252 : {
3253 : auto oIter =
3254 992 : mutualExclusionGroupUsed.find(mutualExclusionGroup);
3255 992 : if (oIter != mutualExclusionGroupUsed.end())
3256 : {
3257 13 : ret = false;
3258 26 : ReportError(
3259 : CE_Failure, CPLE_AppDefined,
3260 : "Argument '%s' is mutually exclusive with '%s'.",
3261 26 : arg->GetName().c_str(), oIter->second.c_str());
3262 : }
3263 : else
3264 : {
3265 979 : mutualExclusionGroupUsed[mutualExclusionGroup] =
3266 1958 : arg->GetName();
3267 : }
3268 : }
3269 :
3270 21902 : const auto &mutualDependencyGroup = arg->GetMutualDependencyGroup();
3271 21902 : if (!mutualDependencyGroup.empty())
3272 : {
3273 78 : if (mutualDependencyGroupUsed.find(mutualDependencyGroup) ==
3274 156 : mutualDependencyGroupUsed.end())
3275 : {
3276 129 : mutualDependencyGroupUsed[mutualDependencyGroup] = {
3277 129 : arg->GetName()};
3278 : }
3279 : else
3280 : {
3281 70 : mutualDependencyGroupUsed[mutualDependencyGroup].push_back(
3282 35 : arg->GetName());
3283 : }
3284 : }
3285 :
3286 : // Check direct dependencies
3287 21914 : for (const auto &dependency : arg->GetDirectDependencies())
3288 : {
3289 12 : auto depArg = GetArg(dependency);
3290 12 : if (!depArg)
3291 : {
3292 0 : ret = false;
3293 0 : ReportError(CE_Failure, CPLE_AppDefined,
3294 : "Argument '%s' depends on argument '%s' that "
3295 : "is not defined.",
3296 0 : arg->GetName().c_str(), dependency.c_str());
3297 : }
3298 12 : else if (!depArg->IsExplicitlySet())
3299 : {
3300 6 : ret = false;
3301 12 : ReportError(CE_Failure, CPLE_AppDefined,
3302 : "Argument '%s' depends on argument '%s' that "
3303 : "has not been specified.",
3304 6 : arg->GetName().c_str(),
3305 6 : depArg->GetName().c_str());
3306 : }
3307 : }
3308 : }
3309 :
3310 139496 : if (arg->IsRequired() && !arg->IsExplicitlySet() &&
3311 172 : !arg->HasDefaultValue())
3312 : {
3313 172 : bool emitError = true;
3314 172 : const auto &mutualExclusionGroup = arg->GetMutualExclusionGroup();
3315 172 : if (!mutualExclusionGroup.empty())
3316 : {
3317 1885 : for (const auto &otherArg : m_args)
3318 : {
3319 1859 : if (otherArg->GetMutualExclusionGroup() ==
3320 1988 : mutualExclusionGroup &&
3321 129 : otherArg->IsExplicitlySet())
3322 : {
3323 74 : emitError = false;
3324 74 : break;
3325 : }
3326 : }
3327 : }
3328 262 : if (emitError && !(m_inputDatasetCanBeOmitted &&
3329 55 : arg->GetName() == GDAL_ARG_NAME_INPUT &&
3330 70 : (arg->GetType() == GAAT_DATASET ||
3331 35 : arg->GetType() == GAAT_DATASET_LIST)))
3332 : {
3333 63 : ReportError(CE_Failure, CPLE_AppDefined,
3334 : "Required argument '%s' has not been specified.",
3335 63 : arg->GetName().c_str());
3336 63 : ret = false;
3337 : }
3338 : }
3339 139152 : else if (arg->IsExplicitlySet() && arg->GetType() == GAAT_DATASET)
3340 : {
3341 4678 : if (!ProcessDatasetArg(arg.get(), this))
3342 50 : ret = false;
3343 : }
3344 :
3345 139324 : if (arg->IsExplicitlySet() && arg->GetType() == GAAT_DATASET_LIST)
3346 : {
3347 6417 : auto &listVal = arg->Get<std::vector<GDALArgDatasetValue>>();
3348 6417 : if (listVal.size() == 1)
3349 : {
3350 6259 : if (!ProcessDatasetArg(arg.get(), this))
3351 42 : ret = false;
3352 : }
3353 : else
3354 : {
3355 485 : for (auto &val : listVal)
3356 : {
3357 327 : if (val.GetDatasetRef())
3358 : {
3359 120 : if (!CheckCanSetDatasetObject(arg.get()))
3360 : {
3361 0 : ret = false;
3362 : }
3363 323 : continue;
3364 : }
3365 :
3366 207 : if (val.GetName().empty())
3367 : {
3368 0 : ReportError(CE_Failure, CPLE_AppDefined,
3369 : "Argument '%s' has no dataset object or "
3370 : "dataset name.",
3371 0 : arg->GetName().c_str());
3372 0 : ret = false;
3373 0 : continue;
3374 : }
3375 :
3376 207 : auto oIter = m_oMapDatasetNameToDataset.find(val.GetName());
3377 207 : if (oIter != m_oMapDatasetNameToDataset.end())
3378 : {
3379 2 : auto poDS = oIter->second;
3380 2 : val.SetDatasetOpenedByAlgorithm();
3381 2 : val.Set(poDS);
3382 2 : m_oMapDatasetNameToDataset.erase(oIter);
3383 2 : continue;
3384 : }
3385 :
3386 205 : if (!arg->AutoOpenDataset())
3387 201 : continue;
3388 :
3389 4 : int flags = arg->GetDatasetType() | GDAL_OF_VERBOSE_ERROR;
3390 :
3391 8 : CPLStringList aosOpenOptions;
3392 8 : CPLStringList aosAllowedDrivers;
3393 4 : if (arg->GetName() == GDAL_ARG_NAME_INPUT)
3394 : {
3395 4 : const auto ooArg = GetArg(GDAL_ARG_NAME_OPEN_OPTION);
3396 4 : if (ooArg && ooArg->GetType() == GAAT_STRING_LIST)
3397 : {
3398 4 : aosOpenOptions = CPLStringList(
3399 4 : ooArg->Get<std::vector<std::string>>());
3400 : }
3401 :
3402 4 : const auto ifArg = GetArg(GDAL_ARG_NAME_INPUT_FORMAT);
3403 4 : if (ifArg && ifArg->GetType() == GAAT_STRING_LIST)
3404 : {
3405 4 : aosAllowedDrivers = CPLStringList(
3406 4 : ifArg->Get<std::vector<std::string>>());
3407 : }
3408 :
3409 4 : const auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
3410 4 : if (updateArg && updateArg->GetType() == GAAT_BOOLEAN &&
3411 0 : updateArg->Get<bool>())
3412 : {
3413 0 : flags |= GDAL_OF_UPDATE;
3414 : }
3415 : }
3416 :
3417 : auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
3418 4 : val.GetName().c_str(), flags, aosAllowedDrivers.List(),
3419 12 : aosOpenOptions.List()));
3420 4 : if (poDS)
3421 : {
3422 3 : val.Set(std::move(poDS));
3423 : }
3424 : else
3425 : {
3426 1 : ret = false;
3427 : }
3428 : }
3429 : }
3430 : }
3431 :
3432 139324 : if (arg->IsExplicitlySet() && !arg->RunValidationActions())
3433 : {
3434 8 : ret = false;
3435 : }
3436 : }
3437 :
3438 : // Check mutual dependency groups
3439 7893 : std::vector<std::string> processedGroups;
3440 : // Loop through group map and check there are not required args in the group that are not set
3441 7936 : for (const auto &[groupName, argNames] : mutualDependencyGroupUsed)
3442 : {
3443 43 : if (std::find(processedGroups.begin(), processedGroups.end(),
3444 43 : groupName) != processedGroups.end())
3445 0 : continue;
3446 86 : std::vector<std::string> missingArgs;
3447 848 : for (auto &arg : m_args)
3448 : {
3449 805 : const auto &mutualDependencyGroup = arg->GetMutualDependencyGroup();
3450 898 : if (mutualDependencyGroup == groupName &&
3451 93 : std::find(argNames.begin(), argNames.end(), arg->GetName()) ==
3452 898 : argNames.end())
3453 : {
3454 15 : missingArgs.push_back(arg->GetName());
3455 : }
3456 : }
3457 43 : if (!missingArgs.empty())
3458 : {
3459 12 : ret = false;
3460 24 : std::string missingArgsStr;
3461 27 : for (const auto &missingArg : missingArgs)
3462 : {
3463 15 : if (!missingArgsStr.empty())
3464 3 : missingArgsStr += ", ";
3465 15 : missingArgsStr += missingArg;
3466 : }
3467 24 : std::string givenArgsStr;
3468 27 : for (const auto &givenArg : argNames)
3469 : {
3470 15 : if (!givenArgsStr.empty())
3471 3 : givenArgsStr += ", ";
3472 15 : givenArgsStr += givenArg;
3473 : }
3474 12 : ReportError(CE_Failure, CPLE_AppDefined,
3475 : "Argument(s) '%s' require(s) that the following "
3476 : "argument(s) are also specified: %s.",
3477 : givenArgsStr.c_str(), missingArgsStr.c_str());
3478 : }
3479 43 : processedGroups.push_back(groupName);
3480 : }
3481 :
3482 33632 : for (const auto &f : m_validationActions)
3483 : {
3484 25739 : if (!f())
3485 82 : ret = false;
3486 : }
3487 :
3488 7893 : return ret;
3489 : }
3490 :
3491 : /************************************************************************/
3492 : /* GDALAlgorithm::InstantiateSubAlgorithm */
3493 : /************************************************************************/
3494 :
3495 : std::unique_ptr<GDALAlgorithm>
3496 10942 : GDALAlgorithm::InstantiateSubAlgorithm(const std::string &name,
3497 : bool suggestionAllowed) const
3498 : {
3499 10942 : auto ret = m_subAlgRegistry.Instantiate(name);
3500 21884 : auto childCallPath = m_callPath;
3501 10942 : childCallPath.push_back(name);
3502 10942 : if (!ret)
3503 : {
3504 1214 : ret = GDALGlobalAlgorithmRegistry::GetSingleton()
3505 1214 : .InstantiateDeclaredSubAlgorithm(childCallPath);
3506 : }
3507 10942 : if (ret)
3508 : {
3509 10761 : ret->SetCallPath(childCallPath);
3510 : }
3511 181 : else if (suggestionAllowed)
3512 : {
3513 72 : std::string bestCandidate;
3514 36 : size_t bestDistance = std::numeric_limits<size_t>::max();
3515 525 : for (const std::string &candidate : GetSubAlgorithmNames())
3516 : {
3517 : const size_t distance =
3518 489 : CPLLevenshteinDistance(name.c_str(), candidate.c_str(),
3519 : /* transpositionAllowed = */ true);
3520 489 : if (distance < bestDistance)
3521 : {
3522 83 : bestCandidate = candidate;
3523 83 : bestDistance = distance;
3524 : }
3525 406 : else if (distance == bestDistance)
3526 : {
3527 51 : bestCandidate.clear();
3528 : }
3529 : }
3530 36 : if (!bestCandidate.empty() && bestDistance <= 2)
3531 : {
3532 4 : CPLError(CE_Failure, CPLE_AppDefined,
3533 : "Algorithm '%s' is unknown. Do you mean '%s'?",
3534 : name.c_str(), bestCandidate.c_str());
3535 : }
3536 : }
3537 21884 : return ret;
3538 : }
3539 :
3540 : /************************************************************************/
3541 : /* GDALAlgorithm::GetSuggestionForArgumentName() */
3542 : /************************************************************************/
3543 :
3544 : std::string
3545 39 : GDALAlgorithm::GetSuggestionForArgumentName(const std::string &osName) const
3546 : {
3547 39 : if (osName.size() >= 3)
3548 : {
3549 34 : std::string bestCandidate;
3550 34 : size_t bestDistance = std::numeric_limits<size_t>::max();
3551 776 : for (const auto &[key, value] : m_mapLongNameToArg)
3552 : {
3553 742 : CPL_IGNORE_RET_VAL(value);
3554 742 : const size_t distance = CPLLevenshteinDistance(
3555 : osName.c_str(), key.c_str(), /* transpositionAllowed = */ true);
3556 742 : if (distance < bestDistance)
3557 : {
3558 89 : bestCandidate = key;
3559 89 : bestDistance = distance;
3560 : }
3561 653 : else if (distance == bestDistance)
3562 : {
3563 78 : bestCandidate.clear();
3564 : }
3565 : }
3566 48 : if (!bestCandidate.empty() &&
3567 14 : bestDistance <= (bestCandidate.size() >= 4U ? 2U : 1U))
3568 : {
3569 5 : return bestCandidate;
3570 : }
3571 : }
3572 34 : return std::string();
3573 : }
3574 :
3575 : /************************************************************************/
3576 : /* GDALAlgorithm::GetSuggestionsForArgumentName() */
3577 : /************************************************************************/
3578 :
3579 : std::vector<std::string>
3580 39 : GDALAlgorithm::GetSuggestionsForArgumentName(const std::string &osName) const
3581 : {
3582 39 : std::vector<std::string> ret;
3583 78 : std::string suggestion = GetSuggestionForArgumentName(osName);
3584 39 : if (!suggestion.empty())
3585 : {
3586 5 : ret.push_back(std::move(suggestion));
3587 : }
3588 34 : else if (osName.size() >= 3)
3589 : {
3590 : // e.g "crs" for reproject will match "input-crs" and "target-crs"
3591 87 : const std::string dashName = std::string("-").append(osName);
3592 554 : for (const auto &arg : m_args)
3593 : {
3594 525 : if (cpl::ends_with(arg->GetName(), dashName))
3595 : {
3596 3 : ret.push_back(arg->GetName());
3597 : }
3598 : }
3599 : }
3600 78 : return ret;
3601 : }
3602 :
3603 : /************************************************************************/
3604 : /* GDALAlgorithm::IsKnownOutputRelatedBooleanArgName() */
3605 : /************************************************************************/
3606 :
3607 : /* static */
3608 23 : bool GDALAlgorithm::IsKnownOutputRelatedBooleanArgName(std::string_view osName)
3609 : {
3610 69 : return osName == GDAL_ARG_NAME_APPEND || osName == GDAL_ARG_NAME_UPDATE ||
3611 69 : osName == GDAL_ARG_NAME_OVERWRITE ||
3612 46 : osName == GDAL_ARG_NAME_OVERWRITE_LAYER;
3613 : }
3614 :
3615 : /************************************************************************/
3616 : /* GDALAlgorithm::HasOutputString() */
3617 : /************************************************************************/
3618 :
3619 74 : bool GDALAlgorithm::HasOutputString() const
3620 : {
3621 74 : auto outputStringArg = GetArg(GDAL_ARG_NAME_OUTPUT_STRING);
3622 74 : return outputStringArg && outputStringArg->IsOutput();
3623 : }
3624 :
3625 : /************************************************************************/
3626 : /* GDALAlgorithm::GetArg() */
3627 : /************************************************************************/
3628 :
3629 503597 : GDALAlgorithmArg *GDALAlgorithm::GetArg(const std::string &osName,
3630 : bool suggestionAllowed, bool isConst)
3631 : {
3632 503597 : const auto nPos = osName.find_first_not_of('-');
3633 503597 : if (nPos == std::string::npos)
3634 27 : return nullptr;
3635 1007140 : std::string osKey = osName.substr(nPos);
3636 : {
3637 503570 : const auto oIter = m_mapLongNameToArg.find(osKey);
3638 503570 : if (oIter != m_mapLongNameToArg.end())
3639 466417 : return oIter->second;
3640 : }
3641 : {
3642 37153 : const auto oIter = m_mapShortNameToArg.find(osKey);
3643 37153 : if (oIter != m_mapShortNameToArg.end())
3644 8 : return oIter->second;
3645 : }
3646 :
3647 37145 : if (!isConst && m_arbitraryLongNameArgsAllowed)
3648 : {
3649 23 : const auto nDotPos = osKey.find('.');
3650 : const std::string osKeyEnd =
3651 23 : nDotPos == std::string::npos ? osKey : osKey.substr(nDotPos + 1);
3652 23 : if (IsKnownOutputRelatedBooleanArgName(osKeyEnd))
3653 : {
3654 : m_arbitraryLongNameArgsValuesBool.emplace_back(
3655 0 : std::make_unique<bool>());
3656 0 : AddArg(osKey, 0, std::string("User-provided argument ") + osKey,
3657 0 : m_arbitraryLongNameArgsValuesBool.back().get())
3658 0 : .SetUserProvided();
3659 : }
3660 : else
3661 : {
3662 46 : const std::string osKeyInit = osKey;
3663 23 : if (osKey == "oo")
3664 0 : osKey = GDAL_ARG_NAME_OPEN_OPTION;
3665 23 : else if (osKey == "co")
3666 0 : osKey = GDAL_ARG_NAME_CREATION_OPTION;
3667 23 : else if (osKey == "of")
3668 0 : osKey = GDAL_ARG_NAME_OUTPUT_FORMAT;
3669 23 : else if (osKey == "if")
3670 0 : osKey = GDAL_ARG_NAME_INPUT_FORMAT;
3671 : m_arbitraryLongNameArgsValuesStr.emplace_back(
3672 23 : std::make_unique<std::string>());
3673 : auto &arg =
3674 46 : AddArg(osKey, 0, std::string("User-provided argument ") + osKey,
3675 46 : m_arbitraryLongNameArgsValuesStr.back().get())
3676 23 : .SetUserProvided();
3677 23 : if (osKey != osKeyInit)
3678 0 : arg.AddAlias(osKeyInit);
3679 : }
3680 23 : const auto oIter = m_mapLongNameToArg.find(osKey);
3681 23 : CPLAssert(oIter != m_mapLongNameToArg.end());
3682 23 : return oIter->second;
3683 : }
3684 :
3685 37122 : if (suggestionAllowed)
3686 : {
3687 14 : const auto suggestions = GetSuggestionsForArgumentName(osName);
3688 7 : if (!suggestions.empty())
3689 : {
3690 2 : CPLError(CE_Failure, CPLE_AppDefined,
3691 : "Argument '%s' is unknown. Do you mean %s?",
3692 : osName.c_str(),
3693 4 : FormatSuggestionsAsString(suggestions,
3694 : /* addDashDashPrefix = */ false)
3695 : .c_str());
3696 : }
3697 : }
3698 :
3699 37122 : return nullptr;
3700 : }
3701 :
3702 : /************************************************************************/
3703 : /* GDALAlgorithm::AddAliasFor() */
3704 : /************************************************************************/
3705 :
3706 : //! @cond Doxygen_Suppress
3707 87417 : void GDALAlgorithm::AddAliasFor(GDALInConstructionAlgorithmArg *arg,
3708 : const std::string &alias)
3709 : {
3710 87417 : if (cpl::contains(m_mapLongNameToArg, alias))
3711 : {
3712 1 : ReportError(CE_Failure, CPLE_AppDefined, "Name '%s' already declared.",
3713 : alias.c_str());
3714 : }
3715 : else
3716 : {
3717 87416 : m_mapLongNameToArg[alias] = arg;
3718 : }
3719 87417 : }
3720 :
3721 : //! @endcond
3722 :
3723 : /************************************************************************/
3724 : /* GDALAlgorithm::AddShortNameAliasFor() */
3725 : /************************************************************************/
3726 :
3727 : //! @cond Doxygen_Suppress
3728 50 : void GDALAlgorithm::AddShortNameAliasFor(GDALInConstructionAlgorithmArg *arg,
3729 : char shortNameAlias)
3730 : {
3731 100 : std::string alias;
3732 50 : alias += shortNameAlias;
3733 50 : if (cpl::contains(m_mapShortNameToArg, alias))
3734 : {
3735 0 : ReportError(CE_Failure, CPLE_AppDefined,
3736 : "Short name '%s' already declared.", alias.c_str());
3737 : }
3738 : else
3739 : {
3740 50 : m_mapShortNameToArg[alias] = arg;
3741 : }
3742 50 : }
3743 :
3744 : //! @endcond
3745 :
3746 : /************************************************************************/
3747 : /* GDALAlgorithm::SetPositional() */
3748 : /************************************************************************/
3749 :
3750 : //! @cond Doxygen_Suppress
3751 23872 : void GDALAlgorithm::SetPositional(GDALInConstructionAlgorithmArg *arg)
3752 : {
3753 23872 : CPLAssert(std::find(m_positionalArgs.begin(), m_positionalArgs.end(),
3754 : arg) == m_positionalArgs.end());
3755 23872 : m_positionalArgs.push_back(arg);
3756 23872 : }
3757 :
3758 : //! @endcond
3759 :
3760 : /************************************************************************/
3761 : /* GDALAlgorithm::HasSubAlgorithms() */
3762 : /************************************************************************/
3763 :
3764 14192 : bool GDALAlgorithm::HasSubAlgorithms() const
3765 : {
3766 14192 : if (!m_subAlgRegistry.empty())
3767 3707 : return true;
3768 10485 : return !GDALGlobalAlgorithmRegistry::GetSingleton()
3769 20970 : .GetDeclaredSubAlgorithmNames(m_callPath)
3770 10485 : .empty();
3771 : }
3772 :
3773 : /************************************************************************/
3774 : /* GDALAlgorithm::GetSubAlgorithmNames() */
3775 : /************************************************************************/
3776 :
3777 1599 : std::vector<std::string> GDALAlgorithm::GetSubAlgorithmNames() const
3778 : {
3779 1599 : std::vector<std::string> ret = m_subAlgRegistry.GetNames();
3780 1599 : const auto other = GDALGlobalAlgorithmRegistry::GetSingleton()
3781 3198 : .GetDeclaredSubAlgorithmNames(m_callPath);
3782 1599 : ret.insert(ret.end(), other.begin(), other.end());
3783 1599 : if (!other.empty())
3784 521 : std::sort(ret.begin(), ret.end());
3785 3198 : return ret;
3786 : }
3787 :
3788 : /************************************************************************/
3789 : /* GDALAlgorithm::AddArg() */
3790 : /************************************************************************/
3791 :
3792 : GDALInConstructionAlgorithmArg &
3793 346445 : GDALAlgorithm::AddArg(std::unique_ptr<GDALInConstructionAlgorithmArg> arg)
3794 : {
3795 346445 : auto argRaw = arg.get();
3796 346445 : const auto &longName = argRaw->GetName();
3797 346445 : if (!longName.empty())
3798 : {
3799 346432 : if (longName[0] == '-')
3800 : {
3801 1 : ReportError(CE_Failure, CPLE_AppDefined,
3802 : "Long name '%s' should not start with '-'",
3803 : longName.c_str());
3804 : }
3805 346432 : if (longName.find('=') != std::string::npos)
3806 : {
3807 1 : ReportError(CE_Failure, CPLE_AppDefined,
3808 : "Long name '%s' should not contain a '=' character",
3809 : longName.c_str());
3810 : }
3811 346432 : if (cpl::contains(m_mapLongNameToArg, longName))
3812 : {
3813 1 : ReportError(CE_Failure, CPLE_AppDefined,
3814 : "Long name '%s' already declared", longName.c_str());
3815 : }
3816 346432 : m_mapLongNameToArg[longName] = argRaw;
3817 : }
3818 346445 : const auto &shortName = argRaw->GetShortName();
3819 346445 : if (!shortName.empty())
3820 : {
3821 169932 : if (shortName.size() != 1 ||
3822 84966 : !((shortName[0] >= 'a' && shortName[0] <= 'z') ||
3823 66 : (shortName[0] >= 'A' && shortName[0] <= 'Z') ||
3824 2 : (shortName[0] >= '0' && shortName[0] <= '9')))
3825 : {
3826 1 : ReportError(CE_Failure, CPLE_AppDefined,
3827 : "Short name '%s' should be a single letter or digit",
3828 : shortName.c_str());
3829 : }
3830 84966 : if (cpl::contains(m_mapShortNameToArg, shortName))
3831 : {
3832 1 : ReportError(CE_Failure, CPLE_AppDefined,
3833 : "Short name '%s' already declared", shortName.c_str());
3834 : }
3835 84966 : m_mapShortNameToArg[shortName] = argRaw;
3836 : }
3837 346445 : m_args.emplace_back(std::move(arg));
3838 : return *(
3839 346445 : cpl::down_cast<GDALInConstructionAlgorithmArg *>(m_args.back().get()));
3840 : }
3841 :
3842 : GDALInConstructionAlgorithmArg &
3843 157312 : GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3844 : const std::string &helpMessage, bool *pValue)
3845 : {
3846 157312 : return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3847 : this,
3848 314624 : GDALAlgorithmArgDecl(longName, chShortName, helpMessage, GAAT_BOOLEAN),
3849 314624 : pValue));
3850 : }
3851 :
3852 : GDALInConstructionAlgorithmArg &
3853 55376 : GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3854 : const std::string &helpMessage, std::string *pValue)
3855 : {
3856 55376 : return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3857 : this,
3858 110752 : GDALAlgorithmArgDecl(longName, chShortName, helpMessage, GAAT_STRING),
3859 110752 : pValue));
3860 : }
3861 :
3862 : GDALInConstructionAlgorithmArg &
3863 12874 : GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3864 : const std::string &helpMessage, int *pValue)
3865 : {
3866 12874 : return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3867 : this,
3868 25748 : GDALAlgorithmArgDecl(longName, chShortName, helpMessage, GAAT_INTEGER),
3869 25748 : pValue));
3870 : }
3871 :
3872 : GDALInConstructionAlgorithmArg &
3873 10418 : GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3874 : const std::string &helpMessage, double *pValue)
3875 : {
3876 10418 : return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3877 : this,
3878 20836 : GDALAlgorithmArgDecl(longName, chShortName, helpMessage, GAAT_REAL),
3879 20836 : pValue));
3880 : }
3881 :
3882 : GDALInConstructionAlgorithmArg &
3883 13128 : GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3884 : const std::string &helpMessage,
3885 : GDALArgDatasetValue *pValue, GDALArgDatasetType type)
3886 : {
3887 26256 : auto &arg = AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3888 : this,
3889 26256 : GDALAlgorithmArgDecl(longName, chShortName,
3890 : helpMessage, GAAT_DATASET),
3891 13128 : pValue))
3892 13128 : .SetDatasetType(type);
3893 13128 : pValue->SetOwnerArgument(&arg);
3894 13128 : return arg;
3895 : }
3896 :
3897 : GDALInConstructionAlgorithmArg &
3898 74236 : GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3899 : const std::string &helpMessage,
3900 : std::vector<std::string> *pValue)
3901 : {
3902 74236 : return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3903 : this,
3904 148472 : GDALAlgorithmArgDecl(longName, chShortName, helpMessage,
3905 : GAAT_STRING_LIST),
3906 148472 : pValue));
3907 : }
3908 :
3909 : GDALInConstructionAlgorithmArg &
3910 2144 : GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3911 : const std::string &helpMessage, std::vector<int> *pValue)
3912 : {
3913 2144 : return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3914 : this,
3915 4288 : GDALAlgorithmArgDecl(longName, chShortName, helpMessage,
3916 : GAAT_INTEGER_LIST),
3917 4288 : pValue));
3918 : }
3919 :
3920 : GDALInConstructionAlgorithmArg &
3921 5475 : GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3922 : const std::string &helpMessage,
3923 : std::vector<double> *pValue)
3924 : {
3925 5475 : return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3926 : this,
3927 10950 : GDALAlgorithmArgDecl(longName, chShortName, helpMessage,
3928 : GAAT_REAL_LIST),
3929 10950 : pValue));
3930 : }
3931 :
3932 : GDALInConstructionAlgorithmArg &
3933 15482 : GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3934 : const std::string &helpMessage,
3935 : std::vector<GDALArgDatasetValue> *pValue,
3936 : GDALArgDatasetType type)
3937 : {
3938 30964 : return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3939 : this,
3940 30964 : GDALAlgorithmArgDecl(longName, chShortName, helpMessage,
3941 : GAAT_DATASET_LIST),
3942 15482 : pValue))
3943 30964 : .SetDatasetType(type);
3944 : }
3945 :
3946 : /************************************************************************/
3947 : /* MsgOrDefault() */
3948 : /************************************************************************/
3949 :
3950 114106 : inline const char *MsgOrDefault(const char *helpMessage,
3951 : const char *defaultMessage)
3952 : {
3953 114106 : return helpMessage && helpMessage[0] ? helpMessage : defaultMessage;
3954 : }
3955 :
3956 : /************************************************************************/
3957 : /* GDALAlgorithm::SetAutoCompleteFunctionForFilename() */
3958 : /************************************************************************/
3959 :
3960 : /* static */
3961 18914 : void GDALAlgorithm::SetAutoCompleteFunctionForFilename(
3962 : GDALInConstructionAlgorithmArg &arg, GDALArgDatasetType type)
3963 : {
3964 : arg.SetAutoCompleteFunction(
3965 7 : [&arg,
3966 2483 : type](const std::string ¤tValue) -> std::vector<std::string>
3967 : {
3968 14 : std::vector<std::string> oRet;
3969 :
3970 7 : if (arg.IsHidden())
3971 0 : return oRet;
3972 :
3973 : {
3974 7 : CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
3975 : VSIStatBufL sStat;
3976 10 : if (!currentValue.empty() && currentValue.back() != '/' &&
3977 3 : VSIStatL(currentValue.c_str(), &sStat) == 0)
3978 : {
3979 0 : return oRet;
3980 : }
3981 : }
3982 :
3983 7 : auto poDM = GetGDALDriverManager();
3984 14 : std::set<std::string> oExtensions;
3985 7 : if (type)
3986 : {
3987 1386 : for (int i = 0; i < poDM->GetDriverCount(); ++i)
3988 : {
3989 1380 : auto poDriver = poDM->GetDriver(i);
3990 3910 : if (((type & GDAL_OF_RASTER) != 0 &&
3991 1150 : poDriver->GetMetadataItem(GDAL_DCAP_RASTER)) ||
3992 590 : ((type & GDAL_OF_VECTOR) != 0 &&
3993 2899 : poDriver->GetMetadataItem(GDAL_DCAP_VECTOR)) ||
3994 499 : ((type & GDAL_OF_MULTIDIM_RASTER) != 0 &&
3995 0 : poDriver->GetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER)))
3996 : {
3997 : const char *pszExtensions =
3998 881 : poDriver->GetMetadataItem(GDAL_DMD_EXTENSIONS);
3999 881 : if (pszExtensions)
4000 : {
4001 : const CPLStringList aosExts(
4002 1164 : CSLTokenizeString2(pszExtensions, " ", 0));
4003 1313 : for (const char *pszExt : cpl::Iterate(aosExts))
4004 731 : oExtensions.insert(CPLString(pszExt).tolower());
4005 : }
4006 : }
4007 : }
4008 : }
4009 :
4010 14 : std::string osDir;
4011 14 : const CPLStringList aosVSIPrefixes(VSIGetFileSystemsPrefixes());
4012 14 : std::string osPrefix;
4013 7 : if (STARTS_WITH(currentValue.c_str(), "/vsi"))
4014 : {
4015 82 : for (const char *pszPrefix : cpl::Iterate(aosVSIPrefixes))
4016 : {
4017 81 : if (STARTS_WITH(currentValue.c_str(), pszPrefix))
4018 : {
4019 2 : osPrefix = pszPrefix;
4020 2 : break;
4021 : }
4022 : }
4023 3 : if (osPrefix.empty())
4024 1 : return aosVSIPrefixes;
4025 2 : if (currentValue == osPrefix)
4026 1 : osDir = osPrefix;
4027 : }
4028 6 : if (osDir.empty())
4029 : {
4030 5 : osDir = CPLGetDirnameSafe(currentValue.c_str());
4031 5 : if (!osPrefix.empty() && osDir.size() < osPrefix.size())
4032 0 : osDir = std::move(osPrefix);
4033 : }
4034 :
4035 6 : auto psDir = VSIOpenDir(osDir.c_str(), 0, nullptr);
4036 12 : const std::string osSep = VSIGetDirectorySeparator(osDir.c_str());
4037 6 : if (currentValue.empty())
4038 1 : osDir.clear();
4039 : const std::string currentFilename =
4040 12 : CPLGetFilename(currentValue.c_str());
4041 6 : if (psDir)
4042 : {
4043 456 : while (const VSIDIREntry *psEntry = VSIGetNextDirEntry(psDir))
4044 : {
4045 451 : if ((currentFilename.empty() ||
4046 225 : STARTS_WITH(psEntry->pszName,
4047 227 : currentFilename.c_str())) &&
4048 227 : strcmp(psEntry->pszName, ".") != 0 &&
4049 1355 : strcmp(psEntry->pszName, "..") != 0 &&
4050 227 : (oExtensions.empty() ||
4051 226 : !strstr(psEntry->pszName, ".aux.xml")))
4052 : {
4053 898 : if (oExtensions.empty() ||
4054 224 : cpl::contains(
4055 : oExtensions,
4056 449 : CPLString(CPLGetExtensionSafe(psEntry->pszName))
4057 673 : .tolower()) ||
4058 192 : VSI_ISDIR(psEntry->nMode))
4059 : {
4060 74 : std::string osVal;
4061 37 : if (osDir.empty() || osDir == ".")
4062 4 : osVal = psEntry->pszName;
4063 : else
4064 66 : osVal = CPLFormFilenameSafe(
4065 66 : osDir.c_str(), psEntry->pszName, nullptr);
4066 37 : if (VSI_ISDIR(psEntry->nMode))
4067 4 : osVal += osSep;
4068 37 : oRet.push_back(std::move(osVal));
4069 : }
4070 : }
4071 451 : }
4072 5 : VSICloseDir(psDir);
4073 : }
4074 6 : return oRet;
4075 18914 : });
4076 18914 : }
4077 :
4078 : /************************************************************************/
4079 : /* GDALAlgorithm::AddInputDatasetArg() */
4080 : /************************************************************************/
4081 :
4082 909 : GDALInConstructionAlgorithmArg &GDALAlgorithm::AddInputDatasetArg(
4083 : GDALArgDatasetValue *pValue, GDALArgDatasetType type,
4084 : bool positionalAndRequired, const char *helpMessage)
4085 : {
4086 : auto &arg = AddArg(
4087 : GDAL_ARG_NAME_INPUT, 'i',
4088 : MsgOrDefault(helpMessage,
4089 : CPLSPrintf("Input %s dataset",
4090 909 : GDALAlgorithmArgDatasetTypeName(type).c_str())),
4091 1818 : pValue, type);
4092 909 : if (positionalAndRequired)
4093 902 : arg.SetPositional().SetRequired();
4094 :
4095 909 : SetAutoCompleteFunctionForFilename(arg, type);
4096 :
4097 909 : AddValidationAction(
4098 80 : [pValue]()
4099 : {
4100 79 : if (pValue->GetName() == "-")
4101 1 : pValue->Set("/vsistdin/");
4102 79 : return true;
4103 : });
4104 :
4105 909 : return arg;
4106 : }
4107 :
4108 : /************************************************************************/
4109 : /* GDALAlgorithm::AddInputDatasetArg() */
4110 : /************************************************************************/
4111 :
4112 15013 : GDALInConstructionAlgorithmArg &GDALAlgorithm::AddInputDatasetArg(
4113 : std::vector<GDALArgDatasetValue> *pValue, GDALArgDatasetType type,
4114 : bool positionalAndRequired, const char *helpMessage)
4115 : {
4116 : auto &arg =
4117 : AddArg(GDAL_ARG_NAME_INPUT, 'i',
4118 : MsgOrDefault(
4119 : helpMessage,
4120 : CPLSPrintf("Input %s datasets",
4121 15013 : GDALAlgorithmArgDatasetTypeName(type).c_str())),
4122 45039 : pValue, type)
4123 15013 : .SetPackedValuesAllowed(false);
4124 15013 : if (positionalAndRequired)
4125 1695 : arg.SetPositional().SetRequired();
4126 :
4127 15013 : SetAutoCompleteFunctionForFilename(arg, type);
4128 :
4129 15013 : AddValidationAction(
4130 7400 : [pValue]()
4131 : {
4132 13910 : for (auto &val : *pValue)
4133 : {
4134 6510 : if (val.GetName() == "-")
4135 1 : val.Set("/vsistdin/");
4136 : }
4137 7400 : return true;
4138 : });
4139 15013 : return arg;
4140 : }
4141 :
4142 : /************************************************************************/
4143 : /* GDALAlgorithm::AddOutputDatasetArg() */
4144 : /************************************************************************/
4145 :
4146 9095 : GDALInConstructionAlgorithmArg &GDALAlgorithm::AddOutputDatasetArg(
4147 : GDALArgDatasetValue *pValue, GDALArgDatasetType type,
4148 : bool positionalAndRequired, const char *helpMessage)
4149 : {
4150 : auto &arg =
4151 : AddArg(GDAL_ARG_NAME_OUTPUT, 'o',
4152 : MsgOrDefault(
4153 : helpMessage,
4154 : CPLSPrintf("Output %s dataset",
4155 9095 : GDALAlgorithmArgDatasetTypeName(type).c_str())),
4156 27285 : pValue, type)
4157 9095 : .SetIsInput(true)
4158 9095 : .SetIsOutput(true)
4159 9095 : .SetDatasetInputFlags(GADV_NAME)
4160 9095 : .SetDatasetOutputFlags(GADV_OBJECT);
4161 9095 : if (positionalAndRequired)
4162 4543 : arg.SetPositional().SetRequired();
4163 :
4164 9095 : AddValidationAction(
4165 13922 : [this, &arg, pValue]()
4166 : {
4167 4213 : if (pValue->GetName() == "-")
4168 4 : pValue->Set("/vsistdout/");
4169 :
4170 4213 : auto outputFormatArg = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
4171 4161 : if (outputFormatArg && outputFormatArg->GetType() == GAAT_STRING &&
4172 6587 : (!outputFormatArg->IsExplicitlySet() ||
4173 10800 : outputFormatArg->Get<std::string>().empty()) &&
4174 1735 : arg.IsExplicitlySet())
4175 : {
4176 : const auto vrtCompatible =
4177 1239 : outputFormatArg->GetMetadataItem(GAAMDI_VRT_COMPATIBLE);
4178 196 : if (vrtCompatible && !vrtCompatible->empty() &&
4179 1435 : vrtCompatible->front() == "false" &&
4180 1337 : EQUAL(
4181 : CPLGetExtensionSafe(pValue->GetName().c_str()).c_str(),
4182 : "VRT"))
4183 : {
4184 6 : ReportError(
4185 : CE_Failure, CPLE_NotSupported,
4186 : "VRT output is not supported.%s",
4187 6 : outputFormatArg->GetDescription().find("GDALG") !=
4188 : std::string::npos
4189 : ? " Consider using the GDALG driver instead (files "
4190 : "with .gdalg.json extension)"
4191 : : "");
4192 6 : return false;
4193 : }
4194 1233 : else if (pValue->GetName().size() > strlen(".gdalg.json") &&
4195 2443 : EQUAL(pValue->GetName()
4196 : .substr(pValue->GetName().size() -
4197 : strlen(".gdalg.json"))
4198 : .c_str(),
4199 3676 : ".gdalg.json") &&
4200 28 : outputFormatArg->GetDescription().find("GDALG") ==
4201 : std::string::npos)
4202 : {
4203 0 : ReportError(CE_Failure, CPLE_NotSupported,
4204 : "GDALG output is not supported");
4205 0 : return false;
4206 : }
4207 : }
4208 4207 : return true;
4209 : });
4210 :
4211 9095 : return arg;
4212 : }
4213 :
4214 : /************************************************************************/
4215 : /* GDALAlgorithm::AddOverwriteArg() */
4216 : /************************************************************************/
4217 :
4218 : GDALInConstructionAlgorithmArg &
4219 8962 : GDALAlgorithm::AddOverwriteArg(bool *pValue, const char *helpMessage)
4220 : {
4221 : return AddArg(
4222 : GDAL_ARG_NAME_OVERWRITE, 0,
4223 : MsgOrDefault(
4224 : helpMessage,
4225 : _("Whether overwriting existing output dataset is allowed")),
4226 17924 : pValue)
4227 17924 : .SetDefault(false);
4228 : }
4229 :
4230 : /************************************************************************/
4231 : /* GDALAlgorithm::AddOverwriteLayerArg() */
4232 : /************************************************************************/
4233 :
4234 : GDALInConstructionAlgorithmArg &
4235 3736 : GDALAlgorithm::AddOverwriteLayerArg(bool *pValue, const char *helpMessage)
4236 : {
4237 3736 : AddValidationAction(
4238 1785 : [this]
4239 : {
4240 1784 : auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
4241 1784 : if (!(updateArg && updateArg->GetType() == GAAT_BOOLEAN))
4242 : {
4243 1 : ReportError(CE_Failure, CPLE_AppDefined,
4244 : "--update argument must exist for "
4245 : "--overwrite-layer, even if hidden");
4246 1 : return false;
4247 : }
4248 1783 : return true;
4249 : });
4250 : return AddArg(
4251 : GDAL_ARG_NAME_OVERWRITE_LAYER, 0,
4252 : MsgOrDefault(
4253 : helpMessage,
4254 : _("Whether overwriting existing output layer is allowed")),
4255 7472 : pValue)
4256 3736 : .SetDefault(false)
4257 : .AddAction(
4258 19 : [this]
4259 : {
4260 19 : auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
4261 19 : if (updateArg && updateArg->GetType() == GAAT_BOOLEAN)
4262 : {
4263 19 : updateArg->Set(true);
4264 : }
4265 7491 : });
4266 : }
4267 :
4268 : /************************************************************************/
4269 : /* GDALAlgorithm::AddUpdateArg() */
4270 : /************************************************************************/
4271 :
4272 : GDALInConstructionAlgorithmArg &
4273 4307 : GDALAlgorithm::AddUpdateArg(bool *pValue, const char *helpMessage)
4274 : {
4275 : return AddArg(GDAL_ARG_NAME_UPDATE, 0,
4276 : MsgOrDefault(
4277 : helpMessage,
4278 : _("Whether to open existing dataset in update mode")),
4279 8614 : pValue)
4280 8614 : .SetDefault(false);
4281 : }
4282 :
4283 : /************************************************************************/
4284 : /* GDALAlgorithm::AddAppendLayerArg() */
4285 : /************************************************************************/
4286 :
4287 : GDALInConstructionAlgorithmArg &
4288 3507 : GDALAlgorithm::AddAppendLayerArg(bool *pValue, const char *helpMessage)
4289 : {
4290 3507 : AddValidationAction(
4291 1740 : [this]
4292 : {
4293 1739 : auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
4294 1739 : if (!(updateArg && updateArg->GetType() == GAAT_BOOLEAN))
4295 : {
4296 1 : ReportError(CE_Failure, CPLE_AppDefined,
4297 : "--update argument must exist for --append, even "
4298 : "if hidden");
4299 1 : return false;
4300 : }
4301 1738 : return true;
4302 : });
4303 : return AddArg(GDAL_ARG_NAME_APPEND, 0,
4304 : MsgOrDefault(
4305 : helpMessage,
4306 : _("Whether appending to existing layer is allowed")),
4307 7014 : pValue)
4308 3507 : .SetDefault(false)
4309 : .AddAction(
4310 25 : [this]
4311 : {
4312 25 : auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
4313 25 : if (updateArg && updateArg->GetType() == GAAT_BOOLEAN)
4314 : {
4315 25 : updateArg->Set(true);
4316 : }
4317 7039 : });
4318 : }
4319 :
4320 : /************************************************************************/
4321 : /* GDALAlgorithm::AddOptionsSuggestions() */
4322 : /************************************************************************/
4323 :
4324 : /* static */
4325 30 : bool GDALAlgorithm::AddOptionsSuggestions(const char *pszXML, int datasetType,
4326 : const std::string ¤tValue,
4327 : std::vector<std::string> &oRet)
4328 : {
4329 30 : if (!pszXML)
4330 0 : return false;
4331 60 : CPLXMLTreeCloser poTree(CPLParseXMLString(pszXML));
4332 30 : if (!poTree)
4333 0 : return false;
4334 :
4335 60 : std::string typedOptionName = currentValue;
4336 30 : const auto posEqual = typedOptionName.find('=');
4337 60 : std::string typedValue;
4338 30 : if (posEqual != 0 && posEqual != std::string::npos)
4339 : {
4340 2 : typedValue = currentValue.substr(posEqual + 1);
4341 2 : typedOptionName.resize(posEqual);
4342 : }
4343 :
4344 453 : for (const CPLXMLNode *psChild = poTree.get()->psChild; psChild;
4345 423 : psChild = psChild->psNext)
4346 : {
4347 436 : const char *pszName = CPLGetXMLValue(psChild, "name", nullptr);
4348 449 : if (pszName && typedOptionName == pszName &&
4349 13 : (strcmp(psChild->pszValue, "Option") == 0 ||
4350 2 : strcmp(psChild->pszValue, "Argument") == 0))
4351 : {
4352 13 : const char *pszType = CPLGetXMLValue(psChild, "type", "");
4353 13 : const char *pszMin = CPLGetXMLValue(psChild, "min", nullptr);
4354 13 : const char *pszMax = CPLGetXMLValue(psChild, "max", nullptr);
4355 13 : if (EQUAL(pszType, "string-select"))
4356 : {
4357 90 : for (const CPLXMLNode *psChild2 = psChild->psChild; psChild2;
4358 85 : psChild2 = psChild2->psNext)
4359 : {
4360 85 : if (EQUAL(psChild2->pszValue, "Value"))
4361 : {
4362 75 : oRet.push_back(CPLGetXMLValue(psChild2, "", ""));
4363 : }
4364 : }
4365 : }
4366 8 : else if (EQUAL(pszType, "boolean"))
4367 : {
4368 3 : if (typedValue == "YES" || typedValue == "NO")
4369 : {
4370 1 : oRet.push_back(currentValue);
4371 1 : return true;
4372 : }
4373 2 : oRet.push_back("NO");
4374 2 : oRet.push_back("YES");
4375 : }
4376 5 : else if (EQUAL(pszType, "int"))
4377 : {
4378 5 : if (pszMin && pszMax && atoi(pszMax) - atoi(pszMin) > 0 &&
4379 2 : atoi(pszMax) - atoi(pszMin) < 25)
4380 : {
4381 1 : const int nMax = atoi(pszMax);
4382 13 : for (int i = atoi(pszMin); i <= nMax; ++i)
4383 12 : oRet.push_back(std::to_string(i));
4384 : }
4385 : }
4386 :
4387 12 : if (oRet.empty())
4388 : {
4389 4 : if (pszMin && pszMax)
4390 : {
4391 1 : oRet.push_back(std::string("##"));
4392 2 : oRet.push_back(std::string("validity range: [")
4393 1 : .append(pszMin)
4394 1 : .append(",")
4395 1 : .append(pszMax)
4396 1 : .append("]"));
4397 : }
4398 3 : else if (pszMin)
4399 : {
4400 1 : oRet.push_back(std::string("##"));
4401 1 : oRet.push_back(
4402 1 : std::string("validity range: >= ").append(pszMin));
4403 : }
4404 2 : else if (pszMax)
4405 : {
4406 1 : oRet.push_back(std::string("##"));
4407 1 : oRet.push_back(
4408 1 : std::string("validity range: <= ").append(pszMax));
4409 : }
4410 1 : else if (const char *pszDescription =
4411 1 : CPLGetXMLValue(psChild, "description", nullptr))
4412 : {
4413 1 : oRet.push_back(std::string("##"));
4414 2 : oRet.push_back(std::string("type: ")
4415 1 : .append(pszType)
4416 1 : .append(", description: ")
4417 1 : .append(pszDescription));
4418 : }
4419 : }
4420 :
4421 12 : return true;
4422 : }
4423 : }
4424 :
4425 367 : for (const CPLXMLNode *psChild = poTree.get()->psChild; psChild;
4426 350 : psChild = psChild->psNext)
4427 : {
4428 350 : const char *pszName = CPLGetXMLValue(psChild, "name", nullptr);
4429 350 : if (pszName && (strcmp(psChild->pszValue, "Option") == 0 ||
4430 5 : strcmp(psChild->pszValue, "Argument") == 0))
4431 : {
4432 347 : const char *pszScope = CPLGetXMLValue(psChild, "scope", nullptr);
4433 347 : if (!pszScope ||
4434 40 : (EQUAL(pszScope, "raster") &&
4435 40 : (datasetType & GDAL_OF_RASTER) != 0) ||
4436 20 : (EQUAL(pszScope, "vector") &&
4437 0 : (datasetType & GDAL_OF_VECTOR) != 0))
4438 : {
4439 327 : oRet.push_back(std::string(pszName).append("="));
4440 : }
4441 : }
4442 : }
4443 :
4444 17 : return false;
4445 : }
4446 :
4447 : /************************************************************************/
4448 : /* GDALAlgorithm::OpenOptionCompleteFunction() */
4449 : /************************************************************************/
4450 :
4451 : //! @cond Doxygen_Suppress
4452 : std::vector<std::string>
4453 2 : GDALAlgorithm::OpenOptionCompleteFunction(const std::string ¤tValue) const
4454 : {
4455 2 : std::vector<std::string> oRet;
4456 :
4457 2 : int datasetType = GDAL_OF_RASTER | GDAL_OF_VECTOR | GDAL_OF_MULTIDIM_RASTER;
4458 2 : auto inputArg = GetArg(GDAL_ARG_NAME_INPUT);
4459 4 : if (inputArg && (inputArg->GetType() == GAAT_DATASET ||
4460 2 : inputArg->GetType() == GAAT_DATASET_LIST))
4461 : {
4462 2 : datasetType = inputArg->GetDatasetType();
4463 : }
4464 :
4465 2 : auto inputFormat = GetArg(GDAL_ARG_NAME_INPUT_FORMAT);
4466 4 : if (inputFormat && inputFormat->GetType() == GAAT_STRING_LIST &&
4467 2 : inputFormat->IsExplicitlySet())
4468 : {
4469 : const auto &aosAllowedDrivers =
4470 1 : inputFormat->Get<std::vector<std::string>>();
4471 1 : if (aosAllowedDrivers.size() == 1)
4472 : {
4473 2 : auto poDriver = GetGDALDriverManager()->GetDriverByName(
4474 1 : aosAllowedDrivers[0].c_str());
4475 1 : if (poDriver)
4476 : {
4477 1 : AddOptionsSuggestions(
4478 1 : poDriver->GetMetadataItem(GDAL_DMD_OPENOPTIONLIST),
4479 : datasetType, currentValue, oRet);
4480 : }
4481 1 : return oRet;
4482 : }
4483 : }
4484 :
4485 1 : const auto AddSuggestions = [datasetType, ¤tValue,
4486 375 : &oRet](const GDALArgDatasetValue &datasetValue)
4487 : {
4488 1 : auto poDM = GetGDALDriverManager();
4489 :
4490 1 : const auto &osDSName = datasetValue.GetName();
4491 1 : const std::string osExt = CPLGetExtensionSafe(osDSName.c_str());
4492 1 : if (!osExt.empty())
4493 : {
4494 1 : std::set<std::string> oVisitedExtensions;
4495 231 : for (int i = 0; i < poDM->GetDriverCount(); ++i)
4496 : {
4497 230 : auto poDriver = poDM->GetDriver(i);
4498 690 : if (((datasetType & GDAL_OF_RASTER) != 0 &&
4499 230 : poDriver->GetMetadataItem(GDAL_DCAP_RASTER)) ||
4500 72 : ((datasetType & GDAL_OF_VECTOR) != 0 &&
4501 460 : poDriver->GetMetadataItem(GDAL_DCAP_VECTOR)) ||
4502 72 : ((datasetType & GDAL_OF_MULTIDIM_RASTER) != 0 &&
4503 0 : poDriver->GetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER)))
4504 : {
4505 : const char *pszExtensions =
4506 158 : poDriver->GetMetadataItem(GDAL_DMD_EXTENSIONS);
4507 158 : if (pszExtensions)
4508 : {
4509 : const CPLStringList aosExts(
4510 104 : CSLTokenizeString2(pszExtensions, " ", 0));
4511 229 : for (const char *pszExt : cpl::Iterate(aosExts))
4512 : {
4513 129 : if (EQUAL(pszExt, osExt.c_str()) &&
4514 3 : !cpl::contains(oVisitedExtensions, pszExt))
4515 : {
4516 1 : oVisitedExtensions.insert(pszExt);
4517 1 : if (AddOptionsSuggestions(
4518 : poDriver->GetMetadataItem(
4519 1 : GDAL_DMD_OPENOPTIONLIST),
4520 : datasetType, currentValue, oRet))
4521 : {
4522 0 : return;
4523 : }
4524 1 : break;
4525 : }
4526 : }
4527 : }
4528 : }
4529 : }
4530 : }
4531 1 : };
4532 :
4533 1 : if (inputArg && inputArg->GetType() == GAAT_DATASET)
4534 : {
4535 0 : auto &datasetValue = inputArg->Get<GDALArgDatasetValue>();
4536 0 : AddSuggestions(datasetValue);
4537 : }
4538 1 : else if (inputArg && inputArg->GetType() == GAAT_DATASET_LIST)
4539 : {
4540 1 : auto &datasetValues = inputArg->Get<std::vector<GDALArgDatasetValue>>();
4541 1 : if (datasetValues.size() == 1)
4542 1 : AddSuggestions(datasetValues[0]);
4543 : }
4544 :
4545 1 : return oRet;
4546 : }
4547 :
4548 : //! @endcond
4549 :
4550 : /************************************************************************/
4551 : /* GDALAlgorithm::AddOpenOptionsArg() */
4552 : /************************************************************************/
4553 :
4554 : GDALInConstructionAlgorithmArg &
4555 9982 : GDALAlgorithm::AddOpenOptionsArg(std::vector<std::string> *pValue,
4556 : const char *helpMessage)
4557 : {
4558 : auto &arg = AddArg(GDAL_ARG_NAME_OPEN_OPTION, 0,
4559 19964 : MsgOrDefault(helpMessage, _("Open options")), pValue)
4560 19964 : .AddAlias("oo")
4561 19964 : .SetMetaVar("<KEY>=<VALUE>")
4562 9982 : .SetPackedValuesAllowed(false)
4563 9982 : .SetCategory(GAAC_ADVANCED);
4564 :
4565 31 : arg.AddValidationAction([this, &arg]()
4566 10013 : { return ParseAndValidateKeyValue(arg); });
4567 :
4568 : arg.SetAutoCompleteFunction(
4569 2 : [this](const std::string ¤tValue)
4570 9984 : { return OpenOptionCompleteFunction(currentValue); });
4571 :
4572 9982 : return arg;
4573 : }
4574 :
4575 : /************************************************************************/
4576 : /* GDALAlgorithm::AddOutputOpenOptionsArg() */
4577 : /************************************************************************/
4578 :
4579 : GDALInConstructionAlgorithmArg &
4580 3584 : GDALAlgorithm::AddOutputOpenOptionsArg(std::vector<std::string> *pValue,
4581 : const char *helpMessage)
4582 : {
4583 : auto &arg =
4584 : AddArg(GDAL_ARG_NAME_OUTPUT_OPEN_OPTION, 0,
4585 7168 : MsgOrDefault(helpMessage, _("Output open options")), pValue)
4586 7168 : .AddAlias("output-oo")
4587 7168 : .SetMetaVar("<KEY>=<VALUE>")
4588 3584 : .SetPackedValuesAllowed(false)
4589 3584 : .SetCategory(GAAC_ADVANCED);
4590 :
4591 0 : arg.AddValidationAction([this, &arg]()
4592 3584 : { return ParseAndValidateKeyValue(arg); });
4593 :
4594 : arg.SetAutoCompleteFunction(
4595 0 : [this](const std::string ¤tValue)
4596 3584 : { return OpenOptionCompleteFunction(currentValue); });
4597 :
4598 3584 : return arg;
4599 : }
4600 :
4601 : /************************************************************************/
4602 : /* ValidateFormat() */
4603 : /************************************************************************/
4604 :
4605 5164 : bool GDALAlgorithm::ValidateFormat(const GDALAlgorithmArg &arg,
4606 : bool bStreamAllowed,
4607 : bool bGDALGAllowed) const
4608 : {
4609 5164 : if (arg.GetChoices().empty())
4610 : {
4611 : const auto Validate =
4612 22345 : [this, &arg, bStreamAllowed, bGDALGAllowed](const std::string &val)
4613 : {
4614 5043 : if (const auto extraFormats =
4615 5043 : arg.GetMetadataItem(GAAMDI_EXTRA_FORMATS))
4616 : {
4617 60 : for (const auto &extraFormat : *extraFormats)
4618 : {
4619 48 : if (EQUAL(val.c_str(), extraFormat.c_str()))
4620 14 : return true;
4621 : }
4622 : }
4623 :
4624 5029 : if (bStreamAllowed && EQUAL(val.c_str(), "stream"))
4625 1953 : return true;
4626 :
4627 3084 : if (EQUAL(val.c_str(), "GDALG") &&
4628 8 : arg.GetName() == GDAL_ARG_NAME_OUTPUT_FORMAT)
4629 : {
4630 4 : if (bGDALGAllowed)
4631 : {
4632 4 : return true;
4633 : }
4634 : else
4635 : {
4636 0 : ReportError(CE_Failure, CPLE_NotSupported,
4637 : "GDALG output is not supported.");
4638 0 : return false;
4639 : }
4640 : }
4641 :
4642 : const auto vrtCompatible =
4643 3072 : arg.GetMetadataItem(GAAMDI_VRT_COMPATIBLE);
4644 540 : if (vrtCompatible && !vrtCompatible->empty() &&
4645 3612 : vrtCompatible->front() == "false" && EQUAL(val.c_str(), "VRT"))
4646 : {
4647 7 : ReportError(CE_Failure, CPLE_NotSupported,
4648 : "VRT output is not supported.%s",
4649 : bGDALGAllowed
4650 : ? " Consider using the GDALG driver instead "
4651 : "(files with .gdalg.json extension)."
4652 : : "");
4653 7 : return false;
4654 : }
4655 :
4656 : const auto allowedFormats =
4657 3065 : arg.GetMetadataItem(GAAMDI_ALLOWED_FORMATS);
4658 3118 : if (allowedFormats && !allowedFormats->empty() &&
4659 0 : std::find(allowedFormats->begin(), allowedFormats->end(),
4660 3118 : val) != allowedFormats->end())
4661 : {
4662 12 : return true;
4663 : }
4664 :
4665 : const auto excludedFormats =
4666 3053 : arg.GetMetadataItem(GAAMDI_EXCLUDED_FORMATS);
4667 3100 : if (excludedFormats && !excludedFormats->empty() &&
4668 0 : std::find(excludedFormats->begin(), excludedFormats->end(),
4669 3100 : val) != excludedFormats->end())
4670 : {
4671 0 : ReportError(CE_Failure, CPLE_NotSupported,
4672 : "%s output is not supported.", val.c_str());
4673 0 : return false;
4674 : }
4675 :
4676 3053 : auto hDriver = GDALGetDriverByName(val.c_str());
4677 3053 : if (!hDriver)
4678 : {
4679 : auto poMissingDriver =
4680 4 : GetGDALDriverManager()->GetHiddenDriverByName(val.c_str());
4681 4 : if (poMissingDriver)
4682 : {
4683 : const std::string msg =
4684 0 : GDALGetMessageAboutMissingPluginDriver(poMissingDriver);
4685 0 : ReportError(CE_Failure, CPLE_AppDefined,
4686 : "Invalid value for argument '%s'. Driver '%s' "
4687 : "not found but is known. However plugin %s",
4688 0 : arg.GetName().c_str(), val.c_str(),
4689 : msg.c_str());
4690 : }
4691 : else
4692 : {
4693 8 : ReportError(CE_Failure, CPLE_AppDefined,
4694 : "Invalid value for argument '%s'. Driver '%s' "
4695 : "does not exist.",
4696 4 : arg.GetName().c_str(), val.c_str());
4697 : }
4698 4 : return false;
4699 : }
4700 :
4701 3049 : const auto caps = arg.GetMetadataItem(GAAMDI_REQUIRED_CAPABILITIES);
4702 3049 : if (caps)
4703 : {
4704 9239 : for (const std::string &cap : *caps)
4705 : {
4706 : const char *pszVal =
4707 6221 : GDALGetMetadataItem(hDriver, cap.c_str(), nullptr);
4708 6221 : if (!(pszVal && pszVal[0]))
4709 : {
4710 1853 : if (cap == GDAL_DCAP_CREATECOPY &&
4711 0 : std::find(caps->begin(), caps->end(),
4712 925 : GDAL_DCAP_RASTER) != caps->end() &&
4713 925 : GDALGetMetadataItem(hDriver, GDAL_DCAP_RASTER,
4714 1853 : nullptr) &&
4715 925 : GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATE,
4716 : nullptr))
4717 : {
4718 : // if it supports Create, it supports CreateCopy
4719 : }
4720 3 : else if (cap == GDAL_DMD_EXTENSIONS)
4721 : {
4722 2 : ReportError(
4723 : CE_Failure, CPLE_AppDefined,
4724 : "Invalid value for argument '%s'. Driver '%s' "
4725 : "does "
4726 : "not advertise any file format extension.",
4727 1 : arg.GetName().c_str(), val.c_str());
4728 3 : return false;
4729 : }
4730 : else
4731 : {
4732 2 : if (cap == GDAL_DCAP_CREATE)
4733 : {
4734 1 : auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
4735 1 : if (updateArg &&
4736 2 : updateArg->GetType() == GAAT_BOOLEAN &&
4737 1 : updateArg->IsExplicitlySet())
4738 : {
4739 0 : continue;
4740 : }
4741 :
4742 2 : ReportError(
4743 : CE_Failure, CPLE_AppDefined,
4744 : "Invalid value for argument '%s'. "
4745 : "Driver '%s' does not have write support.",
4746 1 : arg.GetName().c_str(), val.c_str());
4747 1 : return false;
4748 : }
4749 : else
4750 : {
4751 2 : ReportError(
4752 : CE_Failure, CPLE_AppDefined,
4753 : "Invalid value for argument '%s'. Driver "
4754 : "'%s' "
4755 : "does "
4756 : "not expose the required '%s' capability.",
4757 1 : arg.GetName().c_str(), val.c_str(),
4758 : cap.c_str());
4759 1 : return false;
4760 : }
4761 : }
4762 : }
4763 : }
4764 : }
4765 3046 : return true;
4766 5046 : };
4767 :
4768 5046 : if (arg.GetType() == GAAT_STRING)
4769 : {
4770 5033 : return Validate(arg.Get<std::string>());
4771 : }
4772 15 : else if (arg.GetType() == GAAT_STRING_LIST)
4773 : {
4774 25 : for (const auto &val : arg.Get<std::vector<std::string>>())
4775 : {
4776 12 : if (!Validate(val))
4777 2 : return false;
4778 : }
4779 : }
4780 : }
4781 :
4782 131 : return true;
4783 : }
4784 :
4785 : /************************************************************************/
4786 : /* FormatAutoCompleteFunction() */
4787 : /************************************************************************/
4788 :
4789 : /* static */
4790 7 : std::vector<std::string> GDALAlgorithm::FormatAutoCompleteFunction(
4791 : const GDALAlgorithmArg &arg, bool /* bStreamAllowed */, bool bGDALGAllowed)
4792 : {
4793 7 : std::vector<std::string> res;
4794 7 : auto poDM = GetGDALDriverManager();
4795 7 : const auto vrtCompatible = arg.GetMetadataItem(GAAMDI_VRT_COMPATIBLE);
4796 7 : const auto allowedFormats = arg.GetMetadataItem(GAAMDI_ALLOWED_FORMATS);
4797 7 : const auto excludedFormats = arg.GetMetadataItem(GAAMDI_EXCLUDED_FORMATS);
4798 7 : const auto caps = arg.GetMetadataItem(GAAMDI_REQUIRED_CAPABILITIES);
4799 7 : if (auto extraFormats = arg.GetMetadataItem(GAAMDI_EXTRA_FORMATS))
4800 0 : res = std::move(*extraFormats);
4801 1616 : for (int i = 0; i < poDM->GetDriverCount(); ++i)
4802 : {
4803 1609 : auto poDriver = poDM->GetDriver(i);
4804 :
4805 0 : if (vrtCompatible && !vrtCompatible->empty() &&
4806 1609 : vrtCompatible->front() == "false" &&
4807 0 : EQUAL(poDriver->GetDescription(), "VRT"))
4808 : {
4809 : // do nothing
4810 : }
4811 1609 : else if (allowedFormats && !allowedFormats->empty() &&
4812 0 : std::find(allowedFormats->begin(), allowedFormats->end(),
4813 1609 : poDriver->GetDescription()) != allowedFormats->end())
4814 : {
4815 0 : res.push_back(poDriver->GetDescription());
4816 : }
4817 1609 : else if (excludedFormats && !excludedFormats->empty() &&
4818 0 : std::find(excludedFormats->begin(), excludedFormats->end(),
4819 0 : poDriver->GetDescription()) !=
4820 1609 : excludedFormats->end())
4821 : {
4822 0 : continue;
4823 : }
4824 1609 : else if (caps)
4825 : {
4826 1609 : bool ok = true;
4827 3183 : for (const std::string &cap : *caps)
4828 : {
4829 2398 : if (cap == GDAL_ALG_DCAP_RASTER_OR_MULTIDIM_RASTER)
4830 : {
4831 0 : if (!poDriver->GetMetadataItem(GDAL_DCAP_RASTER) &&
4832 0 : !poDriver->GetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER))
4833 : {
4834 0 : ok = false;
4835 0 : break;
4836 : }
4837 : }
4838 2398 : else if (const char *pszVal =
4839 2398 : poDriver->GetMetadataItem(cap.c_str());
4840 1502 : pszVal && pszVal[0])
4841 : {
4842 : }
4843 1292 : else if (cap == GDAL_DCAP_CREATECOPY &&
4844 0 : (std::find(caps->begin(), caps->end(),
4845 396 : GDAL_DCAP_RASTER) != caps->end() &&
4846 1688 : poDriver->GetMetadataItem(GDAL_DCAP_RASTER)) &&
4847 396 : poDriver->GetMetadataItem(GDAL_DCAP_CREATE))
4848 : {
4849 : // if it supports Create, it supports CreateCopy
4850 : }
4851 : else
4852 : {
4853 824 : ok = false;
4854 824 : break;
4855 : }
4856 : }
4857 1609 : if (ok)
4858 : {
4859 785 : res.push_back(poDriver->GetDescription());
4860 : }
4861 : }
4862 : }
4863 7 : if (bGDALGAllowed)
4864 4 : res.push_back("GDALG");
4865 7 : return res;
4866 : }
4867 :
4868 : /************************************************************************/
4869 : /* GDALAlgorithm::AddInputFormatsArg() */
4870 : /************************************************************************/
4871 :
4872 : GDALInConstructionAlgorithmArg &
4873 9763 : GDALAlgorithm::AddInputFormatsArg(std::vector<std::string> *pValue,
4874 : const char *helpMessage)
4875 : {
4876 : auto &arg = AddArg(GDAL_ARG_NAME_INPUT_FORMAT, 0,
4877 19526 : MsgOrDefault(helpMessage, _("Input formats")), pValue)
4878 19526 : .AddAlias("if")
4879 9763 : .SetCategory(GAAC_ADVANCED);
4880 15 : arg.AddValidationAction([this, &arg]()
4881 9778 : { return ValidateFormat(arg, false, false); });
4882 : arg.SetAutoCompleteFunction(
4883 1 : [&arg](const std::string &)
4884 9764 : { return FormatAutoCompleteFunction(arg, false, false); });
4885 9763 : return arg;
4886 : }
4887 :
4888 : /************************************************************************/
4889 : /* GDALAlgorithm::AddOutputFormatArg() */
4890 : /************************************************************************/
4891 :
4892 : GDALInConstructionAlgorithmArg &
4893 10149 : GDALAlgorithm::AddOutputFormatArg(std::string *pValue, bool bStreamAllowed,
4894 : bool bGDALGAllowed, const char *helpMessage)
4895 : {
4896 : auto &arg = AddArg(GDAL_ARG_NAME_OUTPUT_FORMAT, 'f',
4897 : MsgOrDefault(helpMessage,
4898 : bGDALGAllowed
4899 : ? _("Output format (\"GDALG\" allowed)")
4900 : : _("Output format")),
4901 20298 : pValue)
4902 20298 : .AddAlias("of")
4903 10149 : .AddAlias("format");
4904 : arg.AddValidationAction(
4905 5145 : [this, &arg, bStreamAllowed, bGDALGAllowed]()
4906 15294 : { return ValidateFormat(arg, bStreamAllowed, bGDALGAllowed); });
4907 : arg.SetAutoCompleteFunction(
4908 4 : [&arg, bStreamAllowed, bGDALGAllowed](const std::string &)
4909 : {
4910 : return FormatAutoCompleteFunction(arg, bStreamAllowed,
4911 4 : bGDALGAllowed);
4912 10149 : });
4913 10149 : return arg;
4914 : }
4915 :
4916 : /************************************************************************/
4917 : /* GDALAlgorithm::AddOutputDataTypeArg() */
4918 : /************************************************************************/
4919 : GDALInConstructionAlgorithmArg &
4920 1846 : GDALAlgorithm::AddOutputDataTypeArg(std::string *pValue,
4921 : const char *helpMessage)
4922 : {
4923 : auto &arg =
4924 : AddArg(GDAL_ARG_NAME_OUTPUT_DATA_TYPE, 0,
4925 3692 : MsgOrDefault(helpMessage, _("Output data type")), pValue)
4926 3692 : .AddAlias("ot")
4927 3692 : .AddAlias("datatype")
4928 5538 : .AddMetadataItem("type", {"GDALDataType"})
4929 : .SetChoices("UInt8", "Int8", "UInt16", "Int16", "UInt32", "Int32",
4930 : "UInt64", "Int64", "CInt16", "CInt32", "Float16",
4931 1846 : "Float32", "Float64", "CFloat32", "CFloat64")
4932 1846 : .SetHiddenChoices("Byte");
4933 1846 : return arg;
4934 : }
4935 :
4936 : /************************************************************************/
4937 : /* GDALAlgorithm::AddNodataArg() */
4938 : /************************************************************************/
4939 :
4940 : GDALInConstructionAlgorithmArg &
4941 710 : GDALAlgorithm::AddNodataArg(std::string *pValue, bool noneAllowed,
4942 : const std::string &optionName,
4943 : const char *helpMessage)
4944 : {
4945 : auto &arg = AddArg(
4946 : optionName, 0,
4947 : MsgOrDefault(helpMessage,
4948 : noneAllowed
4949 : ? _("Assign a specified nodata value to output bands "
4950 : "('none', numeric value, 'nan', 'inf', '-inf')")
4951 : : _("Assign a specified nodata value to output bands "
4952 : "(numeric value, 'nan', 'inf', '-inf')")),
4953 710 : pValue);
4954 : arg.AddValidationAction(
4955 496 : [this, pValue, noneAllowed, optionName]()
4956 : {
4957 105 : if (!(noneAllowed && EQUAL(pValue->c_str(), "none")))
4958 : {
4959 95 : char *endptr = nullptr;
4960 95 : CPLStrtod(pValue->c_str(), &endptr);
4961 95 : if (endptr != pValue->c_str() + pValue->size())
4962 : {
4963 1 : ReportError(CE_Failure, CPLE_IllegalArg,
4964 : "Value of '%s' should be %sa "
4965 : "numeric value, 'nan', 'inf' or '-inf'",
4966 : optionName.c_str(),
4967 : noneAllowed ? "'none', " : "");
4968 1 : return false;
4969 : }
4970 : }
4971 104 : return true;
4972 710 : });
4973 710 : return arg;
4974 : }
4975 :
4976 : /************************************************************************/
4977 : /* GDALAlgorithm::AddOutputStringArg() */
4978 : /************************************************************************/
4979 :
4980 : GDALInConstructionAlgorithmArg &
4981 6858 : GDALAlgorithm::AddOutputStringArg(std::string *pValue, const char *helpMessage)
4982 : {
4983 : return AddArg(
4984 : GDAL_ARG_NAME_OUTPUT_STRING, 0,
4985 : MsgOrDefault(helpMessage,
4986 : _("Output string, in which the result is placed")),
4987 13716 : pValue)
4988 6858 : .SetHiddenForCLI()
4989 6858 : .SetIsInput(false)
4990 13716 : .SetIsOutput(true);
4991 : }
4992 :
4993 : /************************************************************************/
4994 : /* GDALAlgorithm::AddStdoutArg() */
4995 : /************************************************************************/
4996 :
4997 : GDALInConstructionAlgorithmArg &
4998 1684 : GDALAlgorithm::AddStdoutArg(bool *pValue, const char *helpMessage)
4999 : {
5000 : return AddArg(GDAL_ARG_NAME_STDOUT, 0,
5001 : MsgOrDefault(helpMessage,
5002 : _("Directly output on stdout. If enabled, "
5003 : "output-string will be empty")),
5004 3368 : pValue)
5005 3368 : .SetHidden();
5006 : }
5007 :
5008 : /************************************************************************/
5009 : /* GDALAlgorithm::AddLayerNameArg() */
5010 : /************************************************************************/
5011 :
5012 : GDALInConstructionAlgorithmArg &
5013 222 : GDALAlgorithm::AddLayerNameArg(std::string *pValue, const char *helpMessage)
5014 : {
5015 : return AddArg(GDAL_ARG_NAME_INPUT_LAYER, 'l',
5016 222 : MsgOrDefault(helpMessage, _("Input layer name")), pValue);
5017 : }
5018 :
5019 : /************************************************************************/
5020 : /* GDALAlgorithm::AddArrayNameArg() */
5021 : /************************************************************************/
5022 :
5023 : GDALInConstructionAlgorithmArg &
5024 59 : GDALAlgorithm::AddArrayNameArg(std::string *pValue, const char *helpMessage)
5025 : {
5026 : return AddArg("array", 0, MsgOrDefault(helpMessage, _("Array name")),
5027 118 : pValue)
5028 2 : .SetAutoCompleteFunction([this](const std::string &)
5029 120 : { return AutoCompleteArrayName(); });
5030 : }
5031 :
5032 : /************************************************************************/
5033 : /* GDALAlgorithm::AddArrayNameArg() */
5034 : /************************************************************************/
5035 :
5036 : GDALInConstructionAlgorithmArg &
5037 136 : GDALAlgorithm::AddArrayNameArg(std::vector<std::string> *pValue,
5038 : const char *helpMessage)
5039 : {
5040 : return AddArg("array", 0, MsgOrDefault(helpMessage, _("Array name(s)")),
5041 272 : pValue)
5042 0 : .SetAutoCompleteFunction([this](const std::string &)
5043 272 : { return AutoCompleteArrayName(); });
5044 : }
5045 :
5046 : /************************************************************************/
5047 : /* GDALAlgorithm::AutoCompleteArrayName() */
5048 : /************************************************************************/
5049 :
5050 2 : std::vector<std::string> GDALAlgorithm::AutoCompleteArrayName() const
5051 : {
5052 2 : std::vector<std::string> ret;
5053 4 : std::string osDSName;
5054 2 : auto inputArg = GetArg(GDAL_ARG_NAME_INPUT);
5055 2 : if (inputArg && inputArg->GetType() == GAAT_DATASET_LIST)
5056 : {
5057 2 : auto &inputDatasets = inputArg->Get<std::vector<GDALArgDatasetValue>>();
5058 2 : if (!inputDatasets.empty())
5059 : {
5060 2 : osDSName = inputDatasets[0].GetName();
5061 : }
5062 : }
5063 0 : else if (inputArg && inputArg->GetType() == GAAT_DATASET)
5064 : {
5065 0 : auto &inputDataset = inputArg->Get<GDALArgDatasetValue>();
5066 0 : osDSName = inputDataset.GetName();
5067 : }
5068 :
5069 2 : if (!osDSName.empty())
5070 : {
5071 4 : CPLStringList aosAllowedDrivers;
5072 2 : const auto ifArg = GetArg(GDAL_ARG_NAME_INPUT_FORMAT);
5073 2 : if (ifArg && ifArg->GetType() == GAAT_STRING_LIST)
5074 : aosAllowedDrivers =
5075 2 : CPLStringList(ifArg->Get<std::vector<std::string>>());
5076 :
5077 4 : CPLStringList aosOpenOptions;
5078 2 : const auto ooArg = GetArg(GDAL_ARG_NAME_OPEN_OPTION);
5079 2 : if (ooArg && ooArg->GetType() == GAAT_STRING_LIST)
5080 : aosOpenOptions =
5081 2 : CPLStringList(ooArg->Get<std::vector<std::string>>());
5082 :
5083 2 : if (auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
5084 : osDSName.c_str(), GDAL_OF_MULTIDIM_RASTER,
5085 4 : aosAllowedDrivers.List(), aosOpenOptions.List(), nullptr)))
5086 : {
5087 2 : if (auto poRG = poDS->GetRootGroup())
5088 : {
5089 1 : ret = poRG->GetMDArrayFullNamesRecursive();
5090 : }
5091 : }
5092 : }
5093 :
5094 4 : return ret;
5095 : }
5096 :
5097 : /************************************************************************/
5098 : /* GDALAlgorithm::AddMemorySizeArg() */
5099 : /************************************************************************/
5100 :
5101 : GDALInConstructionAlgorithmArg &
5102 227 : GDALAlgorithm::AddMemorySizeArg(size_t *pValue, std::string *pStrValue,
5103 : const std::string &optionName,
5104 : const char *helpMessage)
5105 : {
5106 454 : return AddArg(optionName, 0, helpMessage, pStrValue)
5107 227 : .SetDefault(*pStrValue)
5108 : .AddValidationAction(
5109 139 : [this, pValue, pStrValue]()
5110 : {
5111 47 : CPLDebug("GDAL", "StrValue `%s`", pStrValue->c_str());
5112 : GIntBig nBytes;
5113 : bool bUnitSpecified;
5114 47 : if (CPLParseMemorySize(pStrValue->c_str(), &nBytes,
5115 47 : &bUnitSpecified) != CE_None)
5116 : {
5117 2 : return false;
5118 : }
5119 45 : if (!bUnitSpecified)
5120 : {
5121 1 : ReportError(CE_Failure, CPLE_AppDefined,
5122 : "Memory size must have a unit or be a "
5123 : "percentage of usable RAM (2GB, 5%%, etc.)");
5124 1 : return false;
5125 : }
5126 : if constexpr (sizeof(std::uint64_t) > sizeof(size_t))
5127 : {
5128 : // -1 to please CoverityScan
5129 : if (static_cast<std::uint64_t>(nBytes) >
5130 : std::numeric_limits<size_t>::max() - 1U)
5131 : {
5132 : ReportError(CE_Failure, CPLE_AppDefined,
5133 : "Memory size %s is too large.",
5134 : pStrValue->c_str());
5135 : return false;
5136 : }
5137 : }
5138 :
5139 44 : *pValue = static_cast<size_t>(nBytes);
5140 44 : return true;
5141 454 : });
5142 : }
5143 :
5144 : /************************************************************************/
5145 : /* GDALAlgorithm::AddOutputLayerNameArg() */
5146 : /************************************************************************/
5147 :
5148 : GDALInConstructionAlgorithmArg &
5149 404 : GDALAlgorithm::AddOutputLayerNameArg(std::string *pValue,
5150 : const char *helpMessage)
5151 : {
5152 : return AddArg(GDAL_ARG_NAME_OUTPUT_LAYER, 0,
5153 404 : MsgOrDefault(helpMessage, _("Output layer name")), pValue);
5154 : }
5155 :
5156 : /************************************************************************/
5157 : /* GDALAlgorithm::AddLayerNameArg() */
5158 : /************************************************************************/
5159 :
5160 : GDALInConstructionAlgorithmArg &
5161 920 : GDALAlgorithm::AddLayerNameArg(std::vector<std::string> *pValue,
5162 : const char *helpMessage)
5163 : {
5164 : return AddArg(GDAL_ARG_NAME_INPUT_LAYER, 'l',
5165 920 : MsgOrDefault(helpMessage, _("Input layer name")), pValue);
5166 : }
5167 :
5168 : /************************************************************************/
5169 : /* GDALAlgorithm::AddGeometryTypeArg() */
5170 : /************************************************************************/
5171 :
5172 : GDALInConstructionAlgorithmArg &
5173 489 : GDALAlgorithm::AddGeometryTypeArg(std::string *pValue, const char *helpMessage)
5174 : {
5175 : return AddArg("geometry-type", 0,
5176 978 : MsgOrDefault(helpMessage, _("Geometry type")), pValue)
5177 : .SetAutoCompleteFunction(
5178 3 : [](const std::string ¤tValue)
5179 : {
5180 3 : std::vector<std::string> oRet;
5181 51 : for (const char *type :
5182 : {"GEOMETRY", "POINT", "LINESTRING", "POLYGON",
5183 : "MULTIPOINT", "MULTILINESTRING", "MULTIPOLYGON",
5184 : "GEOMETRYCOLLECTION", "CURVE", "CIRCULARSTRING",
5185 : "COMPOUNDCURVE", "SURFACE", "CURVEPOLYGON", "MULTICURVE",
5186 54 : "MULTISURFACE", "POLYHEDRALSURFACE", "TIN"})
5187 : {
5188 68 : if (currentValue.empty() ||
5189 17 : STARTS_WITH(type, currentValue.c_str()))
5190 : {
5191 35 : oRet.push_back(type);
5192 35 : oRet.push_back(std::string(type).append("Z"));
5193 35 : oRet.push_back(std::string(type).append("M"));
5194 35 : oRet.push_back(std::string(type).append("ZM"));
5195 : }
5196 : }
5197 3 : return oRet;
5198 978 : })
5199 : .AddValidationAction(
5200 123 : [this, pValue]()
5201 : {
5202 112 : if (wkbFlatten(OGRFromOGCGeomType(pValue->c_str())) ==
5203 120 : wkbUnknown &&
5204 8 : !STARTS_WITH_CI(pValue->c_str(), "GEOMETRY"))
5205 : {
5206 3 : ReportError(CE_Failure, CPLE_AppDefined,
5207 : "Invalid geometry type '%s'", pValue->c_str());
5208 3 : return false;
5209 : }
5210 109 : return true;
5211 978 : });
5212 : }
5213 :
5214 : /************************************************************************/
5215 : /* GDALAlgorithm::SetAutoCompleteFunctionForLayerName() */
5216 : /************************************************************************/
5217 :
5218 : /* static */
5219 3254 : void GDALAlgorithm::SetAutoCompleteFunctionForLayerName(
5220 : GDALInConstructionAlgorithmArg &layerArg, GDALAlgorithmArg &datasetArg)
5221 : {
5222 3254 : CPLAssert(datasetArg.GetType() == GAAT_DATASET ||
5223 : datasetArg.GetType() == GAAT_DATASET_LIST);
5224 :
5225 : layerArg.SetAutoCompleteFunction(
5226 18 : [&datasetArg](const std::string ¤tValue)
5227 : {
5228 6 : std::vector<std::string> ret;
5229 12 : CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
5230 6 : GDALArgDatasetValue *dsVal = nullptr;
5231 6 : if (datasetArg.GetType() == GAAT_DATASET)
5232 : {
5233 0 : dsVal = &(datasetArg.Get<GDALArgDatasetValue>());
5234 : }
5235 : else
5236 : {
5237 6 : auto &val = datasetArg.Get<std::vector<GDALArgDatasetValue>>();
5238 6 : if (val.size() == 1)
5239 : {
5240 6 : dsVal = &val[0];
5241 : }
5242 : }
5243 6 : if (dsVal && !dsVal->GetName().empty())
5244 : {
5245 : auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
5246 12 : dsVal->GetName().c_str(), GDAL_OF_VECTOR));
5247 6 : if (poDS)
5248 : {
5249 12 : for (auto &&poLayer : poDS->GetLayers())
5250 : {
5251 6 : if (currentValue == poLayer->GetDescription())
5252 : {
5253 1 : ret.clear();
5254 1 : ret.push_back(poLayer->GetDescription());
5255 1 : break;
5256 : }
5257 5 : ret.push_back(poLayer->GetDescription());
5258 : }
5259 : }
5260 : }
5261 12 : return ret;
5262 3254 : });
5263 3254 : }
5264 :
5265 : /************************************************************************/
5266 : /* GDALAlgorithm::SetAutoCompleteFunctionForFieldName() */
5267 : /************************************************************************/
5268 :
5269 801 : void GDALAlgorithm::SetAutoCompleteFunctionForFieldName(
5270 : GDALInConstructionAlgorithmArg &fieldArg,
5271 : const GDALAlgorithmArg *layerNameArg, bool attributeFields,
5272 : bool geometryFields, std::vector<GDALArgDatasetValue> &datasetArg,
5273 : const std::vector<std::string> &extraValues,
5274 : std::function<bool(const OGRFieldDefn *)> filterFn)
5275 : {
5276 :
5277 : fieldArg.SetAutoCompleteFunction(
5278 11 : [&datasetArg, layerNameArg, attributeFields, geometryFields,
5279 : extraValues,
5280 801 : filterFn = std::move(filterFn)](const std::string ¤tValue)
5281 : {
5282 22 : std::set<std::string> ret{};
5283 11 : if (!datasetArg.empty())
5284 : {
5285 18 : CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
5286 :
5287 : const auto getLayerFields =
5288 7 : [&ret, ¤tValue, attributeFields, geometryFields,
5289 87 : &extraValues, &filterFn](const OGRLayer *poLayer)
5290 : {
5291 7 : const auto poDefn = poLayer->GetLayerDefn();
5292 7 : if (attributeFields)
5293 : {
5294 27 : for (const auto poFieldDefn : poDefn->GetFields())
5295 : {
5296 20 : if (filterFn && !filterFn(poFieldDefn))
5297 : {
5298 1 : continue;
5299 : }
5300 :
5301 19 : const char *fieldName = poFieldDefn->GetNameRef();
5302 :
5303 19 : if (currentValue == fieldName)
5304 : {
5305 0 : ret.clear();
5306 0 : ret.insert(fieldName);
5307 0 : break;
5308 : }
5309 19 : ret.insert(fieldName);
5310 : }
5311 : }
5312 7 : if (geometryFields)
5313 : {
5314 2 : for (const auto poFieldDefn : poDefn->GetGeomFields())
5315 : {
5316 1 : const char *fieldName = poFieldDefn->GetNameRef();
5317 1 : if (fieldName[0] == 0)
5318 1 : fieldName = OGR_GEOMETRY_DEFAULT_NON_EMPTY_NAME;
5319 1 : if (currentValue == fieldName)
5320 : {
5321 0 : ret.clear();
5322 0 : ret.insert(fieldName);
5323 0 : break;
5324 : }
5325 1 : ret.insert(fieldName);
5326 : }
5327 : }
5328 8 : for (const auto &value : extraValues)
5329 : {
5330 1 : if (currentValue == value)
5331 : {
5332 0 : ret.clear();
5333 0 : ret.insert(value);
5334 0 : break;
5335 : }
5336 1 : ret.insert(value);
5337 : }
5338 7 : };
5339 :
5340 9 : const GDALArgDatasetValue &dsVal = datasetArg[0];
5341 :
5342 9 : if (!dsVal.GetName().empty())
5343 : {
5344 : auto poDS = std::unique_ptr<GDALDataset>(
5345 9 : GDALDataset::Open(dsVal.GetName().c_str(),
5346 18 : GDAL_OF_VECTOR | GDAL_OF_READONLY));
5347 9 : if (poDS)
5348 : {
5349 18 : std::vector<std::string> layerNames;
5350 9 : if (layerNameArg && layerNameArg->IsExplicitlySet())
5351 : {
5352 4 : if (layerNameArg->GetType() == GAAT_STRING_LIST)
5353 : {
5354 : layerNames =
5355 : layerNameArg
5356 2 : ->Get<std::vector<std::string>>();
5357 : }
5358 2 : else if (layerNameArg->GetType() == GAAT_STRING)
5359 : {
5360 2 : layerNames.push_back(
5361 2 : layerNameArg->Get<std::string>());
5362 : }
5363 : }
5364 9 : if (layerNames.empty())
5365 : {
5366 : // Loop through all layers
5367 10 : for (const auto *poLayer : poDS->GetLayers())
5368 : {
5369 5 : getLayerFields(poLayer);
5370 : }
5371 : }
5372 : else
5373 : {
5374 8 : for (const std::string &layerName : layerNames)
5375 : {
5376 : const auto poLayer =
5377 4 : poDS->GetLayerByName(layerName.c_str());
5378 4 : if (poLayer)
5379 : {
5380 2 : getLayerFields(poLayer);
5381 : }
5382 : }
5383 : }
5384 : }
5385 : }
5386 : }
5387 11 : std::vector<std::string> retVector(ret.begin(), ret.end());
5388 22 : return retVector;
5389 1602 : });
5390 801 : }
5391 :
5392 : /************************************************************************/
5393 : /* GDALAlgorithm::AddFieldNameArg() */
5394 : /************************************************************************/
5395 :
5396 : GDALInConstructionAlgorithmArg &
5397 138 : GDALAlgorithm::AddFieldNameArg(std::string *pValue, const char *helpMessage)
5398 : {
5399 : return AddArg("field-name", 0, MsgOrDefault(helpMessage, _("Field name")),
5400 138 : pValue);
5401 : }
5402 :
5403 : /************************************************************************/
5404 : /* GDALAlgorithm::ParseFieldDefinition() */
5405 : /************************************************************************/
5406 67 : bool GDALAlgorithm::ParseFieldDefinition(const std::string &posStrDef,
5407 : OGRFieldDefn *poFieldDefn,
5408 : std::string *posError)
5409 : {
5410 : static const std::regex re(
5411 67 : R"(^([^:]+):([^(\s]+)(?:\((\d+)(?:,(\d+))?\))?$)");
5412 134 : std::smatch match;
5413 67 : if (std::regex_match(posStrDef, match, re))
5414 : {
5415 132 : const std::string name = match[1];
5416 132 : const std::string type = match[2];
5417 66 : const int width = match[3].matched ? std::stoi(match[3]) : 0;
5418 66 : const int precision = match[4].matched ? std::stoi(match[4]) : 0;
5419 66 : poFieldDefn->SetName(name.c_str());
5420 :
5421 66 : const auto typeEnum{OGRFieldDefn::GetFieldTypeByName(type.c_str())};
5422 66 : if (typeEnum == OFTString && !EQUAL(type.c_str(), "String"))
5423 : {
5424 1 : if (posError)
5425 1 : *posError = "Unsupported field type: " + type;
5426 :
5427 1 : return false;
5428 : }
5429 65 : poFieldDefn->SetType(typeEnum);
5430 65 : poFieldDefn->SetWidth(width);
5431 65 : poFieldDefn->SetPrecision(precision);
5432 65 : return true;
5433 : }
5434 :
5435 1 : if (posError)
5436 : *posError = "Invalid field definition format. Expected "
5437 1 : "<NAME>:<TYPE>[(<WIDTH>[,<PRECISION>])]";
5438 :
5439 1 : return false;
5440 : }
5441 :
5442 : /************************************************************************/
5443 : /* GDALAlgorithm::AddFieldDefinitionArg() */
5444 : /************************************************************************/
5445 :
5446 : GDALInConstructionAlgorithmArg &
5447 132 : GDALAlgorithm::AddFieldDefinitionArg(std::vector<std::string> *pValues,
5448 : std::vector<OGRFieldDefn> *pFieldDefns,
5449 : const char *helpMessage)
5450 : {
5451 : auto &arg =
5452 : AddArg("field", 0, MsgOrDefault(helpMessage, _("Field definition")),
5453 264 : pValues)
5454 264 : .SetMetaVar("<NAME>:<TYPE>[(<WIDTH>[,<PRECISION>])]")
5455 132 : .SetPackedValuesAllowed(true)
5456 132 : .SetRepeatedArgAllowed(true);
5457 :
5458 132 : auto validationFunction = [this, pFieldDefns, pValues]()
5459 : {
5460 65 : pFieldDefns->clear();
5461 130 : for (const auto &strValue : *pValues)
5462 : {
5463 67 : OGRFieldDefn fieldDefn("", OFTString);
5464 67 : std::string error;
5465 67 : if (!GDALAlgorithm::ParseFieldDefinition(strValue, &fieldDefn,
5466 : &error))
5467 : {
5468 2 : ReportError(CE_Failure, CPLE_AppDefined, "%s", error.c_str());
5469 2 : return false;
5470 : }
5471 : // Check uniqueness of field names
5472 67 : for (const auto &existingFieldDefn : *pFieldDefns)
5473 : {
5474 2 : if (EQUAL(existingFieldDefn.GetNameRef(),
5475 : fieldDefn.GetNameRef()))
5476 : {
5477 0 : ReportError(CE_Failure, CPLE_AppDefined,
5478 : "Duplicate field name: '%s'",
5479 : fieldDefn.GetNameRef());
5480 0 : return false;
5481 : }
5482 : }
5483 65 : pFieldDefns->push_back(fieldDefn);
5484 : }
5485 63 : return true;
5486 132 : };
5487 :
5488 132 : arg.AddValidationAction(std::move(validationFunction));
5489 :
5490 132 : return arg;
5491 : }
5492 :
5493 : /************************************************************************/
5494 : /* GDALAlgorithm::AddFieldTypeSubtypeArg() */
5495 : /************************************************************************/
5496 :
5497 276 : GDALInConstructionAlgorithmArg &GDALAlgorithm::AddFieldTypeSubtypeArg(
5498 : OGRFieldType *pTypeValue, OGRFieldSubType *pSubtypeValue,
5499 : std::string *pStrValue, const std::string &argName, const char *helpMessage)
5500 : {
5501 : auto &arg =
5502 552 : AddArg(argName.empty() ? std::string("field-type") : argName, 0,
5503 828 : MsgOrDefault(helpMessage, _("Field type or subtype")), pStrValue)
5504 : .SetAutoCompleteFunction(
5505 1 : [](const std::string ¤tValue)
5506 : {
5507 1 : std::vector<std::string> oRet;
5508 6 : for (int i = 1; i <= OGRFieldSubType::OFSTMaxSubType; i++)
5509 : {
5510 : const char *pszSubType =
5511 5 : OGRFieldDefn::GetFieldSubTypeName(
5512 : static_cast<OGRFieldSubType>(i));
5513 5 : if (pszSubType != nullptr)
5514 : {
5515 5 : if (currentValue.empty() ||
5516 0 : STARTS_WITH(pszSubType, currentValue.c_str()))
5517 : {
5518 5 : oRet.push_back(pszSubType);
5519 : }
5520 : }
5521 : }
5522 :
5523 15 : for (int i = 0; i <= OGRFieldType::OFTMaxType; i++)
5524 : {
5525 : // Skip deprecated
5526 14 : if (static_cast<OGRFieldType>(i) ==
5527 13 : OGRFieldType::OFTWideString ||
5528 : static_cast<OGRFieldType>(i) ==
5529 : OGRFieldType::OFTWideStringList)
5530 2 : continue;
5531 12 : const char *pszType = OGRFieldDefn::GetFieldTypeName(
5532 : static_cast<OGRFieldType>(i));
5533 12 : if (pszType != nullptr)
5534 : {
5535 12 : if (currentValue.empty() ||
5536 0 : STARTS_WITH(pszType, currentValue.c_str()))
5537 : {
5538 12 : oRet.push_back(pszType);
5539 : }
5540 : }
5541 : }
5542 1 : return oRet;
5543 276 : });
5544 :
5545 : auto validationFunction =
5546 845 : [this, &arg, pTypeValue, pSubtypeValue, pStrValue]()
5547 : {
5548 120 : bool isValid{true};
5549 120 : *pTypeValue = OGRFieldDefn::GetFieldTypeByName(pStrValue->c_str());
5550 :
5551 : // String is returned for unknown types
5552 120 : if (!EQUAL(pStrValue->c_str(), "String") && *pTypeValue == OFTString)
5553 : {
5554 16 : isValid = false;
5555 : }
5556 :
5557 120 : *pSubtypeValue =
5558 120 : OGRFieldDefn::GetFieldSubTypeByName(pStrValue->c_str());
5559 :
5560 120 : if (*pSubtypeValue != OFSTNone)
5561 : {
5562 15 : isValid = true;
5563 15 : switch (*pSubtypeValue)
5564 : {
5565 6 : case OFSTBoolean:
5566 : case OFSTInt16:
5567 : {
5568 6 : *pTypeValue = OFTInteger;
5569 6 : break;
5570 : }
5571 3 : case OFSTFloat32:
5572 : {
5573 3 : *pTypeValue = OFTReal;
5574 3 : break;
5575 : }
5576 6 : default:
5577 : {
5578 6 : *pTypeValue = OFTString;
5579 6 : break;
5580 : }
5581 : }
5582 : }
5583 :
5584 120 : if (!isValid)
5585 : {
5586 2 : ReportError(CE_Failure, CPLE_AppDefined,
5587 : "Invalid value for argument '%s': '%s'",
5588 1 : arg.GetName().c_str(), pStrValue->c_str());
5589 : }
5590 :
5591 120 : return isValid;
5592 276 : };
5593 :
5594 276 : if (!pStrValue->empty())
5595 : {
5596 0 : arg.SetDefault(*pStrValue);
5597 0 : validationFunction();
5598 : }
5599 :
5600 276 : arg.AddValidationAction(std::move(validationFunction));
5601 :
5602 276 : return arg;
5603 : }
5604 :
5605 : /************************************************************************/
5606 : /* GDALAlgorithm::ValidateBandArg() */
5607 : /************************************************************************/
5608 :
5609 4696 : bool GDALAlgorithm::ValidateBandArg() const
5610 : {
5611 4696 : bool ret = true;
5612 4696 : const auto bandArg = GetArg(GDAL_ARG_NAME_BAND);
5613 4696 : const auto inputDatasetArg = GetArg(GDAL_ARG_NAME_INPUT);
5614 1748 : if (bandArg && bandArg->IsExplicitlySet() && inputDatasetArg &&
5615 344 : (inputDatasetArg->GetType() == GAAT_DATASET ||
5616 6438 : inputDatasetArg->GetType() == GAAT_DATASET_LIST) &&
5617 175 : (inputDatasetArg->GetDatasetType() & GDAL_OF_RASTER) != 0)
5618 : {
5619 104 : const auto CheckBand = [this](const GDALDataset *poDS, int nBand)
5620 : {
5621 99 : if (nBand > poDS->GetRasterCount())
5622 : {
5623 5 : ReportError(CE_Failure, CPLE_AppDefined,
5624 : "Value of 'band' should be greater or equal than "
5625 : "1 and less or equal than %d.",
5626 : poDS->GetRasterCount());
5627 5 : return false;
5628 : }
5629 94 : return true;
5630 118 : };
5631 :
5632 : const auto ValidateForOneDataset =
5633 356 : [&bandArg, &CheckBand](const GDALDataset *poDS)
5634 : {
5635 113 : bool l_ret = true;
5636 113 : if (bandArg->GetType() == GAAT_INTEGER)
5637 : {
5638 24 : l_ret = CheckBand(poDS, bandArg->Get<int>());
5639 : }
5640 89 : else if (bandArg->GetType() == GAAT_INTEGER_LIST)
5641 : {
5642 130 : for (int nBand : bandArg->Get<std::vector<int>>())
5643 : {
5644 75 : l_ret = l_ret && CheckBand(poDS, nBand);
5645 : }
5646 : }
5647 113 : return l_ret;
5648 118 : };
5649 :
5650 118 : if (inputDatasetArg->GetType() == GAAT_DATASET)
5651 : {
5652 : auto poDS =
5653 6 : inputDatasetArg->Get<GDALArgDatasetValue>().GetDatasetRef();
5654 6 : if (poDS && !ValidateForOneDataset(poDS))
5655 2 : ret = false;
5656 : }
5657 : else
5658 : {
5659 112 : CPLAssert(inputDatasetArg->GetType() == GAAT_DATASET_LIST);
5660 111 : for (auto &datasetValue :
5661 334 : inputDatasetArg->Get<std::vector<GDALArgDatasetValue>>())
5662 : {
5663 111 : auto poDS = datasetValue.GetDatasetRef();
5664 111 : if (poDS && !ValidateForOneDataset(poDS))
5665 3 : ret = false;
5666 : }
5667 : }
5668 : }
5669 4696 : return ret;
5670 : }
5671 :
5672 : /************************************************************************/
5673 : /* GDALAlgorithm::RunPreStepPipelineValidations() */
5674 : /************************************************************************/
5675 :
5676 3741 : bool GDALAlgorithm::RunPreStepPipelineValidations() const
5677 : {
5678 3741 : return ValidateBandArg();
5679 : }
5680 :
5681 : /************************************************************************/
5682 : /* GDALAlgorithm::AddBandArg() */
5683 : /************************************************************************/
5684 :
5685 : GDALInConstructionAlgorithmArg &
5686 1713 : GDALAlgorithm::AddBandArg(int *pValue, const char *helpMessage)
5687 : {
5688 2177 : AddValidationAction([this]() { return ValidateBandArg(); });
5689 :
5690 : return AddArg(GDAL_ARG_NAME_BAND, 'b',
5691 : MsgOrDefault(helpMessage, _("Input band (1-based index)")),
5692 3426 : pValue)
5693 : .AddValidationAction(
5694 34 : [pValue]()
5695 : {
5696 34 : if (*pValue <= 0)
5697 : {
5698 1 : CPLError(CE_Failure, CPLE_AppDefined,
5699 : "Value of 'band' should greater or equal to 1.");
5700 1 : return false;
5701 : }
5702 33 : return true;
5703 3426 : });
5704 : }
5705 :
5706 : /************************************************************************/
5707 : /* GDALAlgorithm::AddBandArg() */
5708 : /************************************************************************/
5709 :
5710 : GDALInConstructionAlgorithmArg &
5711 879 : GDALAlgorithm::AddBandArg(std::vector<int> *pValue, const char *helpMessage)
5712 : {
5713 1370 : AddValidationAction([this]() { return ValidateBandArg(); });
5714 :
5715 : return AddArg(GDAL_ARG_NAME_BAND, 'b',
5716 : MsgOrDefault(helpMessage, _("Input band(s) (1-based index)")),
5717 1758 : pValue)
5718 : .AddValidationAction(
5719 126 : [pValue]()
5720 : {
5721 397 : for (int val : *pValue)
5722 : {
5723 272 : if (val <= 0)
5724 : {
5725 1 : CPLError(CE_Failure, CPLE_AppDefined,
5726 : "Value of 'band' should greater or equal "
5727 : "to 1.");
5728 1 : return false;
5729 : }
5730 : }
5731 125 : return true;
5732 1758 : });
5733 : }
5734 :
5735 : /************************************************************************/
5736 : /* ParseAndValidateKeyValue() */
5737 : /************************************************************************/
5738 :
5739 590 : bool GDALAlgorithm::ParseAndValidateKeyValue(GDALAlgorithmArg &arg)
5740 : {
5741 554 : const auto Validate = [this, &arg](const std::string &val)
5742 : {
5743 549 : if (val.find('=') == std::string::npos)
5744 : {
5745 5 : ReportError(
5746 : CE_Failure, CPLE_AppDefined,
5747 : "Invalid value for argument '%s'. <KEY>=<VALUE> expected",
5748 5 : arg.GetName().c_str());
5749 5 : return false;
5750 : }
5751 :
5752 544 : return true;
5753 590 : };
5754 :
5755 590 : if (arg.GetType() == GAAT_STRING)
5756 : {
5757 0 : return Validate(arg.Get<std::string>());
5758 : }
5759 590 : else if (arg.GetType() == GAAT_STRING_LIST)
5760 : {
5761 590 : std::vector<std::string> &vals = arg.Get<std::vector<std::string>>();
5762 590 : if (vals.size() == 1)
5763 : {
5764 : // Try to split A=B,C=D into A=B and C=D if there is no ambiguity
5765 966 : std::vector<std::string> newVals;
5766 966 : std::string curToken;
5767 483 : bool canSplitOnComma = true;
5768 483 : char lastSep = 0;
5769 483 : bool inString = false;
5770 483 : bool equalFoundInLastToken = false;
5771 7285 : for (char c : vals[0])
5772 : {
5773 6806 : if (!inString && c == ',')
5774 : {
5775 10 : if (lastSep != '=' || !equalFoundInLastToken)
5776 : {
5777 2 : canSplitOnComma = false;
5778 2 : break;
5779 : }
5780 8 : lastSep = c;
5781 8 : newVals.push_back(curToken);
5782 8 : curToken.clear();
5783 8 : equalFoundInLastToken = false;
5784 : }
5785 6796 : else if (!inString && c == '=')
5786 : {
5787 482 : if (lastSep == '=')
5788 : {
5789 2 : canSplitOnComma = false;
5790 2 : break;
5791 : }
5792 480 : equalFoundInLastToken = true;
5793 480 : lastSep = c;
5794 480 : curToken += c;
5795 : }
5796 6314 : else if (c == '"')
5797 : {
5798 4 : inString = !inString;
5799 4 : curToken += c;
5800 : }
5801 : else
5802 : {
5803 6310 : curToken += c;
5804 : }
5805 : }
5806 483 : if (canSplitOnComma && !inString && equalFoundInLastToken)
5807 : {
5808 470 : if (!curToken.empty())
5809 470 : newVals.emplace_back(std::move(curToken));
5810 470 : vals = std::move(newVals);
5811 : }
5812 : }
5813 :
5814 1134 : for (const auto &val : vals)
5815 : {
5816 549 : if (!Validate(val))
5817 5 : return false;
5818 : }
5819 : }
5820 :
5821 585 : return true;
5822 : }
5823 :
5824 : /************************************************************************/
5825 : /* IsGDALGOutput() */
5826 : /************************************************************************/
5827 :
5828 2560 : bool GDALAlgorithm::IsGDALGOutput() const
5829 : {
5830 2560 : bool isGDALGOutput = false;
5831 2560 : const auto outputFormatArg = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
5832 2560 : const auto outputArg = GetArg(GDAL_ARG_NAME_OUTPUT);
5833 4464 : if (outputArg && outputArg->GetType() == GAAT_DATASET &&
5834 1904 : outputArg->IsExplicitlySet())
5835 : {
5836 3731 : if (outputFormatArg && outputFormatArg->GetType() == GAAT_STRING &&
5837 1853 : outputFormatArg->IsExplicitlySet())
5838 : {
5839 : const auto &val =
5840 1150 : outputFormatArg->GDALAlgorithmArg::Get<std::string>();
5841 1150 : isGDALGOutput = EQUAL(val.c_str(), "GDALG");
5842 : }
5843 : else
5844 : {
5845 : const auto &filename =
5846 728 : outputArg->GDALAlgorithmArg::Get<GDALArgDatasetValue>();
5847 728 : isGDALGOutput =
5848 1427 : filename.GetName().size() > strlen(".gdalg.json") &&
5849 699 : EQUAL(filename.GetName().c_str() + filename.GetName().size() -
5850 : strlen(".gdalg.json"),
5851 : ".gdalg.json");
5852 : }
5853 : }
5854 2560 : return isGDALGOutput;
5855 : }
5856 :
5857 : /************************************************************************/
5858 : /* ProcessGDALGOutput() */
5859 : /************************************************************************/
5860 :
5861 2686 : GDALAlgorithm::ProcessGDALGOutputRet GDALAlgorithm::ProcessGDALGOutput()
5862 : {
5863 2686 : if (!SupportsStreamedOutput())
5864 732 : return ProcessGDALGOutputRet::NOT_GDALG;
5865 :
5866 1954 : if (IsGDALGOutput())
5867 : {
5868 12 : const auto outputArg = GetArg(GDAL_ARG_NAME_OUTPUT);
5869 : const auto &filename =
5870 12 : outputArg->GDALAlgorithmArg::Get<GDALArgDatasetValue>().GetName();
5871 : VSIStatBufL sStat;
5872 12 : if (VSIStatL(filename.c_str(), &sStat) == 0)
5873 : {
5874 0 : const auto overwriteArg = GetArg(GDAL_ARG_NAME_OVERWRITE);
5875 0 : if (overwriteArg && overwriteArg->GetType() == GAAT_BOOLEAN)
5876 : {
5877 0 : if (!overwriteArg->GDALAlgorithmArg::Get<bool>())
5878 : {
5879 0 : CPLError(CE_Failure, CPLE_AppDefined,
5880 : "File '%s' already exists. Specify the "
5881 : "--overwrite option to overwrite it.",
5882 : filename.c_str());
5883 0 : return ProcessGDALGOutputRet::GDALG_ERROR;
5884 : }
5885 : }
5886 : }
5887 :
5888 24 : std::string osCommandLine;
5889 :
5890 48 : for (const auto &path : GDALAlgorithm::m_callPath)
5891 : {
5892 36 : if (!osCommandLine.empty())
5893 24 : osCommandLine += ' ';
5894 36 : osCommandLine += path;
5895 : }
5896 :
5897 278 : for (const auto &arg : GetArgs())
5898 : {
5899 296 : if (arg->IsExplicitlySet() &&
5900 48 : arg->GetName() != GDAL_ARG_NAME_OUTPUT &&
5901 35 : arg->GetName() != GDAL_ARG_NAME_OUTPUT_FORMAT &&
5902 313 : arg->GetName() != GDAL_ARG_NAME_UPDATE &&
5903 17 : arg->GetName() != GDAL_ARG_NAME_OVERWRITE)
5904 : {
5905 16 : osCommandLine += ' ';
5906 16 : std::string strArg;
5907 16 : if (!arg->Serialize(strArg))
5908 : {
5909 0 : CPLError(CE_Failure, CPLE_AppDefined,
5910 : "Cannot serialize argument %s",
5911 0 : arg->GetName().c_str());
5912 0 : return ProcessGDALGOutputRet::GDALG_ERROR;
5913 : }
5914 16 : osCommandLine += strArg;
5915 : }
5916 : }
5917 :
5918 12 : osCommandLine += " --output-format stream --output streamed_dataset";
5919 :
5920 12 : std::string outStringUnused;
5921 12 : return SaveGDALG(filename, outStringUnused, osCommandLine)
5922 12 : ? ProcessGDALGOutputRet::GDALG_OK
5923 12 : : ProcessGDALGOutputRet::GDALG_ERROR;
5924 : }
5925 :
5926 1942 : return ProcessGDALGOutputRet::NOT_GDALG;
5927 : }
5928 :
5929 : /************************************************************************/
5930 : /* GDALAlgorithm::SaveGDALG() */
5931 : /************************************************************************/
5932 :
5933 24 : /* static */ bool GDALAlgorithm::SaveGDALG(const std::string &filename,
5934 : std::string &outString,
5935 : const std::string &commandLine)
5936 : {
5937 48 : CPLJSONDocument oDoc;
5938 24 : oDoc.GetRoot().Add("type", "gdal_streamed_alg");
5939 24 : oDoc.GetRoot().Add("command_line", commandLine);
5940 24 : oDoc.GetRoot().Add("gdal_version", GDALVersionInfo("VERSION_NUM"));
5941 :
5942 24 : if (!filename.empty())
5943 23 : return oDoc.Save(filename);
5944 :
5945 1 : outString = oDoc.GetRoot().Format(CPLJSONObject::PrettyFormat::Pretty);
5946 1 : return true;
5947 : }
5948 :
5949 : /************************************************************************/
5950 : /* GDALAlgorithm::AddCreationOptionsArg() */
5951 : /************************************************************************/
5952 :
5953 : GDALInConstructionAlgorithmArg &
5954 8825 : GDALAlgorithm::AddCreationOptionsArg(std::vector<std::string> *pValue,
5955 : const char *helpMessage)
5956 : {
5957 : auto &arg = AddArg(GDAL_ARG_NAME_CREATION_OPTION, 0,
5958 17650 : MsgOrDefault(helpMessage, _("Creation option")), pValue)
5959 17650 : .AddAlias("co")
5960 17650 : .SetMetaVar("<KEY>=<VALUE>")
5961 8825 : .SetPackedValuesAllowed(false);
5962 294 : arg.AddValidationAction([this, &arg]()
5963 9119 : { return ParseAndValidateKeyValue(arg); });
5964 :
5965 : arg.SetAutoCompleteFunction(
5966 51 : [this](const std::string ¤tValue)
5967 : {
5968 17 : std::vector<std::string> oRet;
5969 :
5970 17 : int datasetType =
5971 : GDAL_OF_RASTER | GDAL_OF_VECTOR | GDAL_OF_MULTIDIM_RASTER;
5972 17 : auto outputArg = GetArg(GDAL_ARG_NAME_OUTPUT);
5973 17 : if (outputArg && (outputArg->GetType() == GAAT_DATASET ||
5974 0 : outputArg->GetType() == GAAT_DATASET_LIST))
5975 : {
5976 17 : datasetType = outputArg->GetDatasetType();
5977 : }
5978 :
5979 17 : const char *pszMDCreationOptionList =
5980 : (datasetType == GDAL_OF_MULTIDIM_RASTER)
5981 17 : ? GDAL_DMD_MULTIDIM_DATASET_CREATIONOPTIONLIST
5982 : : GDAL_DMD_CREATIONOPTIONLIST;
5983 :
5984 17 : auto outputFormat = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
5985 34 : if (outputFormat && outputFormat->GetType() == GAAT_STRING &&
5986 17 : outputFormat->IsExplicitlySet())
5987 : {
5988 14 : auto poDriver = GetGDALDriverManager()->GetDriverByName(
5989 7 : outputFormat->Get<std::string>().c_str());
5990 7 : if (poDriver)
5991 : {
5992 7 : AddOptionsSuggestions(
5993 7 : poDriver->GetMetadataItem(pszMDCreationOptionList),
5994 : datasetType, currentValue, oRet);
5995 : }
5996 7 : return oRet;
5997 : }
5998 :
5999 10 : if (outputArg && outputArg->GetType() == GAAT_DATASET)
6000 : {
6001 10 : auto poDM = GetGDALDriverManager();
6002 10 : auto &datasetValue = outputArg->Get<GDALArgDatasetValue>();
6003 10 : const auto &osDSName = datasetValue.GetName();
6004 10 : const std::string osExt = CPLGetExtensionSafe(osDSName.c_str());
6005 10 : if (!osExt.empty())
6006 : {
6007 10 : std::set<std::string> oVisitedExtensions;
6008 721 : for (int i = 0; i < poDM->GetDriverCount(); ++i)
6009 : {
6010 718 : auto poDriver = poDM->GetDriver(i);
6011 2154 : if (((datasetType & GDAL_OF_RASTER) != 0 &&
6012 718 : poDriver->GetMetadataItem(GDAL_DCAP_RASTER)) ||
6013 216 : ((datasetType & GDAL_OF_VECTOR) != 0 &&
6014 1436 : poDriver->GetMetadataItem(GDAL_DCAP_VECTOR)) ||
6015 216 : ((datasetType & GDAL_OF_MULTIDIM_RASTER) != 0 &&
6016 0 : poDriver->GetMetadataItem(
6017 0 : GDAL_DCAP_MULTIDIM_RASTER)))
6018 : {
6019 : const char *pszExtensions =
6020 502 : poDriver->GetMetadataItem(GDAL_DMD_EXTENSIONS);
6021 502 : if (pszExtensions)
6022 : {
6023 : const CPLStringList aosExts(
6024 326 : CSLTokenizeString2(pszExtensions, " ", 0));
6025 722 : for (const char *pszExt : cpl::Iterate(aosExts))
6026 : {
6027 422 : if (EQUAL(pszExt, osExt.c_str()) &&
6028 16 : !cpl::contains(oVisitedExtensions,
6029 : pszExt))
6030 : {
6031 10 : oVisitedExtensions.insert(pszExt);
6032 10 : if (AddOptionsSuggestions(
6033 : poDriver->GetMetadataItem(
6034 10 : pszMDCreationOptionList),
6035 : datasetType, currentValue,
6036 : oRet))
6037 : {
6038 7 : return oRet;
6039 : }
6040 3 : break;
6041 : }
6042 : }
6043 : }
6044 : }
6045 : }
6046 : }
6047 : }
6048 :
6049 3 : return oRet;
6050 8825 : });
6051 :
6052 8825 : return arg;
6053 : }
6054 :
6055 : /************************************************************************/
6056 : /* GDALAlgorithm::AddLayerCreationOptionsArg() */
6057 : /************************************************************************/
6058 :
6059 : GDALInConstructionAlgorithmArg &
6060 4225 : GDALAlgorithm::AddLayerCreationOptionsArg(std::vector<std::string> *pValue,
6061 : const char *helpMessage)
6062 : {
6063 : auto &arg =
6064 : AddArg(GDAL_ARG_NAME_LAYER_CREATION_OPTION, 0,
6065 8450 : MsgOrDefault(helpMessage, _("Layer creation option")), pValue)
6066 8450 : .AddAlias("lco")
6067 8450 : .SetMetaVar("<KEY>=<VALUE>")
6068 4225 : .SetPackedValuesAllowed(false);
6069 76 : arg.AddValidationAction([this, &arg]()
6070 4301 : { return ParseAndValidateKeyValue(arg); });
6071 :
6072 : arg.SetAutoCompleteFunction(
6073 5 : [this](const std::string ¤tValue)
6074 : {
6075 2 : std::vector<std::string> oRet;
6076 :
6077 2 : auto outputFormat = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
6078 4 : if (outputFormat && outputFormat->GetType() == GAAT_STRING &&
6079 2 : outputFormat->IsExplicitlySet())
6080 : {
6081 2 : auto poDriver = GetGDALDriverManager()->GetDriverByName(
6082 1 : outputFormat->Get<std::string>().c_str());
6083 1 : if (poDriver)
6084 : {
6085 1 : AddOptionsSuggestions(poDriver->GetMetadataItem(
6086 1 : GDAL_DS_LAYER_CREATIONOPTIONLIST),
6087 : GDAL_OF_VECTOR, currentValue, oRet);
6088 : }
6089 1 : return oRet;
6090 : }
6091 :
6092 1 : auto outputArg = GetArg(GDAL_ARG_NAME_OUTPUT);
6093 1 : if (outputArg && outputArg->GetType() == GAAT_DATASET)
6094 : {
6095 1 : auto poDM = GetGDALDriverManager();
6096 1 : auto &datasetValue = outputArg->Get<GDALArgDatasetValue>();
6097 1 : const auto &osDSName = datasetValue.GetName();
6098 1 : const std::string osExt = CPLGetExtensionSafe(osDSName.c_str());
6099 1 : if (!osExt.empty())
6100 : {
6101 1 : std::set<std::string> oVisitedExtensions;
6102 231 : for (int i = 0; i < poDM->GetDriverCount(); ++i)
6103 : {
6104 230 : auto poDriver = poDM->GetDriver(i);
6105 230 : if (poDriver->GetMetadataItem(GDAL_DCAP_VECTOR))
6106 : {
6107 : const char *pszExtensions =
6108 91 : poDriver->GetMetadataItem(GDAL_DMD_EXTENSIONS);
6109 91 : if (pszExtensions)
6110 : {
6111 : const CPLStringList aosExts(
6112 62 : CSLTokenizeString2(pszExtensions, " ", 0));
6113 156 : for (const char *pszExt : cpl::Iterate(aosExts))
6114 : {
6115 96 : if (EQUAL(pszExt, osExt.c_str()) &&
6116 1 : !cpl::contains(oVisitedExtensions,
6117 : pszExt))
6118 : {
6119 1 : oVisitedExtensions.insert(pszExt);
6120 1 : if (AddOptionsSuggestions(
6121 : poDriver->GetMetadataItem(
6122 1 : GDAL_DS_LAYER_CREATIONOPTIONLIST),
6123 : GDAL_OF_VECTOR, currentValue,
6124 : oRet))
6125 : {
6126 0 : return oRet;
6127 : }
6128 1 : break;
6129 : }
6130 : }
6131 : }
6132 : }
6133 : }
6134 : }
6135 : }
6136 :
6137 1 : return oRet;
6138 4225 : });
6139 :
6140 4225 : return arg;
6141 : }
6142 :
6143 : /************************************************************************/
6144 : /* GDALAlgorithm::AddBBOXArg() */
6145 : /************************************************************************/
6146 :
6147 : /** Add bbox=xmin,ymin,xmax,ymax argument. */
6148 : GDALInConstructionAlgorithmArg &
6149 1985 : GDALAlgorithm::AddBBOXArg(std::vector<double> *pValue, const char *helpMessage)
6150 : {
6151 : auto &arg = AddArg("bbox", 0,
6152 : MsgOrDefault(helpMessage,
6153 : _("Bounding box as xmin,ymin,xmax,ymax")),
6154 3970 : pValue)
6155 1985 : .SetRepeatedArgAllowed(false)
6156 1985 : .SetMinCount(4)
6157 1985 : .SetMaxCount(4)
6158 1985 : .SetDisplayHintAboutRepetition(false);
6159 : arg.AddValidationAction(
6160 247 : [&arg]()
6161 : {
6162 247 : const auto &val = arg.Get<std::vector<double>>();
6163 247 : CPLAssert(val.size() == 4);
6164 247 : if (!(val[0] <= val[2]) || !(val[1] <= val[3]))
6165 : {
6166 5 : CPLError(CE_Failure, CPLE_AppDefined,
6167 : "Value of 'bbox' should be xmin,ymin,xmax,ymax with "
6168 : "xmin <= xmax and ymin <= ymax");
6169 5 : return false;
6170 : }
6171 242 : return true;
6172 1985 : });
6173 1985 : return arg;
6174 : }
6175 :
6176 : /************************************************************************/
6177 : /* GDALAlgorithm::AddActiveLayerArg() */
6178 : /************************************************************************/
6179 :
6180 : GDALInConstructionAlgorithmArg &
6181 1961 : GDALAlgorithm::AddActiveLayerArg(std::string *pValue, const char *helpMessage)
6182 : {
6183 : return AddArg("active-layer", 0,
6184 : MsgOrDefault(helpMessage,
6185 : _("Set active layer (if not specified, all)")),
6186 1961 : pValue);
6187 : }
6188 :
6189 : /************************************************************************/
6190 : /* GDALAlgorithm::AddNumThreadsArg() */
6191 : /************************************************************************/
6192 :
6193 : GDALInConstructionAlgorithmArg &
6194 728 : GDALAlgorithm::AddNumThreadsArg(int *pValue, std::string *pStrValue,
6195 : const char *helpMessage)
6196 : {
6197 : auto &arg =
6198 : AddArg(GDAL_ARG_NAME_NUM_THREADS, 'j',
6199 : MsgOrDefault(helpMessage, _("Number of jobs (or ALL_CPUS)")),
6200 728 : pStrValue);
6201 :
6202 : AddArg(GDAL_ARG_NAME_NUM_THREADS_INT_HIDDEN, 0,
6203 1456 : _("Number of jobs (read-only, hidden argument)"), pValue)
6204 728 : .SetHidden();
6205 :
6206 2736 : auto lambda = [this, &arg, pValue, pStrValue]
6207 : {
6208 912 : bool bOK = false;
6209 912 : const char *pszVal = CPLGetConfigOption("GDAL_NUM_THREADS", nullptr);
6210 : const int nLimit = std::clamp(
6211 912 : pszVal && !EQUAL(pszVal, "ALL_CPUS") ? atoi(pszVal) : INT_MAX, 1,
6212 1824 : CPLGetNumCPUs());
6213 : const int nNumThreads =
6214 912 : GDALGetNumThreads(pStrValue->c_str(), nLimit,
6215 : /* bDefaultToAllCPUs = */ false, nullptr, &bOK);
6216 912 : if (bOK)
6217 : {
6218 912 : *pValue = nNumThreads;
6219 : }
6220 : else
6221 : {
6222 0 : ReportError(CE_Failure, CPLE_IllegalArg,
6223 : "Invalid value for '%s' argument",
6224 0 : arg.GetName().c_str());
6225 : }
6226 912 : return bOK;
6227 728 : };
6228 728 : if (!pStrValue->empty())
6229 : {
6230 681 : arg.SetDefault(*pStrValue);
6231 681 : lambda();
6232 : }
6233 728 : arg.AddValidationAction(std::move(lambda));
6234 728 : return arg;
6235 : }
6236 :
6237 : /************************************************************************/
6238 : /* GDALAlgorithm::AddAbsolutePathArg() */
6239 : /************************************************************************/
6240 :
6241 : GDALInConstructionAlgorithmArg &
6242 631 : GDALAlgorithm::AddAbsolutePathArg(bool *pValue, const char *helpMessage)
6243 : {
6244 : return AddArg(
6245 : "absolute-path", 0,
6246 : MsgOrDefault(helpMessage, _("Whether the path to the input dataset "
6247 : "should be stored as an absolute path")),
6248 631 : pValue);
6249 : }
6250 :
6251 : /************************************************************************/
6252 : /* GDALAlgorithm::AddPixelFunctionNameArg() */
6253 : /************************************************************************/
6254 :
6255 : GDALInConstructionAlgorithmArg &
6256 139 : GDALAlgorithm::AddPixelFunctionNameArg(std::string *pValue,
6257 : const char *helpMessage)
6258 : {
6259 :
6260 : const auto pixelFunctionNames =
6261 139 : VRTDerivedRasterBand::GetPixelFunctionNames();
6262 : return AddArg(
6263 : "pixel-function", 0,
6264 : MsgOrDefault(
6265 : helpMessage,
6266 : _("Specify a pixel function to calculate output value from "
6267 : "overlapping inputs")),
6268 278 : pValue)
6269 278 : .SetChoices(pixelFunctionNames);
6270 : }
6271 :
6272 : /************************************************************************/
6273 : /* GDALAlgorithm::AddPixelFunctionArgsArg() */
6274 : /************************************************************************/
6275 :
6276 : GDALInConstructionAlgorithmArg &
6277 139 : GDALAlgorithm::AddPixelFunctionArgsArg(std::vector<std::string> *pValue,
6278 : const char *helpMessage)
6279 : {
6280 : auto &pixelFunctionArgArg =
6281 : AddArg("pixel-function-arg", 0,
6282 : MsgOrDefault(
6283 : helpMessage,
6284 : _("Specify argument(s) to pass to the pixel function")),
6285 278 : pValue)
6286 278 : .SetMetaVar("<NAME>=<VALUE>")
6287 139 : .SetRepeatedArgAllowed(true);
6288 : pixelFunctionArgArg.AddValidationAction(
6289 7 : [this, &pixelFunctionArgArg]()
6290 146 : { return ParseAndValidateKeyValue(pixelFunctionArgArg); });
6291 :
6292 : pixelFunctionArgArg.SetAutoCompleteFunction(
6293 12 : [this](const std::string ¤tValue)
6294 : {
6295 12 : std::string pixelFunction;
6296 6 : const auto pixelFunctionArg = GetArg("pixel-function");
6297 6 : if (pixelFunctionArg && pixelFunctionArg->GetType() == GAAT_STRING)
6298 : {
6299 6 : pixelFunction = pixelFunctionArg->Get<std::string>();
6300 : }
6301 :
6302 6 : std::vector<std::string> ret;
6303 :
6304 6 : if (!pixelFunction.empty())
6305 : {
6306 5 : const auto *pair = VRTDerivedRasterBand::GetPixelFunction(
6307 : pixelFunction.c_str());
6308 5 : if (!pair)
6309 : {
6310 1 : ret.push_back("**");
6311 : // Non printable UTF-8 space, to avoid autocompletion to pickup on 'd'
6312 1 : ret.push_back(std::string("\xC2\xA0"
6313 : "Invalid pixel function name"));
6314 : }
6315 4 : else if (pair->second.find("Argument name=") ==
6316 : std::string::npos)
6317 : {
6318 1 : ret.push_back("**");
6319 : // Non printable UTF-8 space, to avoid autocompletion to pickup on 'd'
6320 1 : ret.push_back(
6321 2 : std::string(
6322 : "\xC2\xA0"
6323 : "No pixel function arguments for pixel function '")
6324 1 : .append(pixelFunction)
6325 1 : .append("'"));
6326 : }
6327 : else
6328 : {
6329 3 : AddOptionsSuggestions(pair->second.c_str(), 0, currentValue,
6330 : ret);
6331 : }
6332 : }
6333 :
6334 12 : return ret;
6335 139 : });
6336 :
6337 139 : return pixelFunctionArgArg;
6338 : }
6339 :
6340 : /************************************************************************/
6341 : /* GDALAlgorithm::AddProgressArg() */
6342 : /************************************************************************/
6343 :
6344 10729 : void GDALAlgorithm::AddProgressArg(bool hidden)
6345 : {
6346 : auto &arg =
6347 : AddArg(GDAL_ARG_NAME_QUIET, 'q',
6348 21458 : _("Quiet mode (no progress bar or warning message)"), &m_quiet)
6349 10729 : .SetAvailableInPipelineStep(false)
6350 21458 : .SetCategory(GAAC_COMMON)
6351 10729 : .AddAction([this]() { m_progressBarRequested = false; });
6352 10729 : if (hidden)
6353 2157 : arg.SetHidden();
6354 :
6355 21458 : AddArg("progress", 0, _("Display progress bar"), &m_progressBarRequested)
6356 10729 : .SetAvailableInPipelineStep(false)
6357 10729 : .SetHidden();
6358 10729 : }
6359 :
6360 : /************************************************************************/
6361 : /* GDALAlgorithm::Run() */
6362 : /************************************************************************/
6363 :
6364 5174 : bool GDALAlgorithm::Run(GDALProgressFunc pfnProgress, void *pProgressData)
6365 : {
6366 5174 : WarnIfDeprecated();
6367 :
6368 5174 : if (m_selectedSubAlg)
6369 : {
6370 464 : if (m_calledFromCommandLine)
6371 276 : m_selectedSubAlg->m_calledFromCommandLine = true;
6372 464 : return m_selectedSubAlg->Run(pfnProgress, pProgressData);
6373 : }
6374 :
6375 4710 : if (m_helpRequested || m_helpDocRequested)
6376 : {
6377 19 : if (m_calledFromCommandLine)
6378 19 : printf("%s", GetUsageForCLI(false).c_str()); /*ok*/
6379 19 : return true;
6380 : }
6381 :
6382 4691 : if (m_JSONUsageRequested)
6383 : {
6384 3 : if (m_calledFromCommandLine)
6385 3 : printf("%s", GetUsageAsJSON().c_str()); /*ok*/
6386 3 : return true;
6387 : }
6388 :
6389 4688 : if (!ValidateArguments())
6390 127 : return false;
6391 :
6392 4561 : if (m_alreadyRun)
6393 : {
6394 3 : ReportError(CE_Failure, CPLE_AppDefined,
6395 : "Run() can be called only once per algorithm instance");
6396 3 : return false;
6397 : }
6398 4558 : m_alreadyRun = true;
6399 :
6400 4558 : switch (ProcessGDALGOutput())
6401 : {
6402 0 : case ProcessGDALGOutputRet::GDALG_ERROR:
6403 0 : return false;
6404 :
6405 12 : case ProcessGDALGOutputRet::GDALG_OK:
6406 12 : return true;
6407 :
6408 4546 : case ProcessGDALGOutputRet::NOT_GDALG:
6409 4546 : break;
6410 : }
6411 :
6412 4546 : if (m_executionForStreamOutput)
6413 : {
6414 98 : if (!CheckSafeForStreamOutput())
6415 : {
6416 4 : return false;
6417 : }
6418 : }
6419 :
6420 4542 : return RunImpl(pfnProgress, pProgressData);
6421 : }
6422 :
6423 : /************************************************************************/
6424 : /* GDALAlgorithm::CheckSafeForStreamOutput() */
6425 : /************************************************************************/
6426 :
6427 50 : bool GDALAlgorithm::CheckSafeForStreamOutput()
6428 : {
6429 50 : const auto outputFormatArg = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
6430 50 : if (outputFormatArg && outputFormatArg->GetType() == GAAT_STRING)
6431 : {
6432 50 : const auto &val = outputFormatArg->GDALAlgorithmArg::Get<std::string>();
6433 50 : if (!EQUAL(val.c_str(), "stream"))
6434 : {
6435 : // For security reasons, to avoid that reading a .gdalg.json file
6436 : // writes a file on the file system.
6437 4 : ReportError(
6438 : CE_Failure, CPLE_NotSupported,
6439 : "in streamed execution, --format stream should be used");
6440 4 : return false;
6441 : }
6442 : }
6443 46 : return true;
6444 : }
6445 :
6446 : /************************************************************************/
6447 : /* GDALAlgorithm::Finalize() */
6448 : /************************************************************************/
6449 :
6450 1992 : bool GDALAlgorithm::Finalize()
6451 : {
6452 1992 : bool ret = true;
6453 1992 : if (m_selectedSubAlg)
6454 282 : ret = m_selectedSubAlg->Finalize();
6455 :
6456 36167 : for (auto &arg : m_args)
6457 : {
6458 34175 : if (arg->GetType() == GAAT_DATASET)
6459 : {
6460 1552 : ret = arg->Get<GDALArgDatasetValue>().Close() && ret;
6461 : }
6462 32623 : else if (arg->GetType() == GAAT_DATASET_LIST)
6463 : {
6464 3110 : for (auto &ds : arg->Get<std::vector<GDALArgDatasetValue>>())
6465 : {
6466 1458 : ret = ds.Close() && ret;
6467 : }
6468 : }
6469 : }
6470 1992 : return ret;
6471 : }
6472 :
6473 : /************************************************************************/
6474 : /* GDALAlgorithm::GetArgNamesForCLI() */
6475 : /************************************************************************/
6476 :
6477 : std::pair<std::vector<std::pair<GDALAlgorithmArg *, std::string>>, size_t>
6478 719 : GDALAlgorithm::GetArgNamesForCLI() const
6479 : {
6480 1438 : std::vector<std::pair<GDALAlgorithmArg *, std::string>> options;
6481 :
6482 719 : size_t maxOptLen = 0;
6483 9157 : for (const auto &arg : m_args)
6484 : {
6485 8438 : if (arg->IsHidden() || arg->IsHiddenForCLI())
6486 1766 : continue;
6487 6672 : std::string opt;
6488 6672 : bool addComma = false;
6489 6672 : if (!arg->GetShortName().empty())
6490 : {
6491 1427 : opt += '-';
6492 1427 : opt += arg->GetShortName();
6493 1427 : addComma = true;
6494 : }
6495 6672 : for (char alias : arg->GetShortNameAliases())
6496 : {
6497 0 : if (addComma)
6498 0 : opt += ", ";
6499 0 : opt += "-";
6500 0 : opt += alias;
6501 0 : addComma = true;
6502 : }
6503 7426 : for (const std::string &alias : arg->GetAliases())
6504 : {
6505 754 : if (addComma)
6506 326 : opt += ", ";
6507 754 : opt += "--";
6508 754 : opt += alias;
6509 754 : addComma = true;
6510 : }
6511 6672 : if (!arg->GetName().empty())
6512 : {
6513 6672 : if (addComma)
6514 1855 : opt += ", ";
6515 6672 : opt += "--";
6516 6672 : opt += arg->GetName();
6517 : }
6518 6672 : const auto &metaVar = arg->GetMetaVar();
6519 6672 : if (!metaVar.empty())
6520 : {
6521 4205 : opt += ' ';
6522 4205 : if (metaVar.front() != '<')
6523 3051 : opt += '<';
6524 4205 : opt += metaVar;
6525 4205 : if (metaVar.back() != '>')
6526 3045 : opt += '>';
6527 : }
6528 6672 : maxOptLen = std::max(maxOptLen, opt.size());
6529 6672 : options.emplace_back(arg.get(), opt);
6530 : }
6531 :
6532 1438 : return std::make_pair(std::move(options), maxOptLen);
6533 : }
6534 :
6535 : /************************************************************************/
6536 : /* GDALAlgorithm::GetUsageForCLI() */
6537 : /************************************************************************/
6538 :
6539 : std::string
6540 429 : GDALAlgorithm::GetUsageForCLI(bool shortUsage,
6541 : const UsageOptions &usageOptions) const
6542 : {
6543 429 : if (m_selectedSubAlg)
6544 7 : return m_selectedSubAlg->GetUsageForCLI(shortUsage, usageOptions);
6545 :
6546 844 : std::string osRet(usageOptions.isPipelineStep ? "*" : "Usage:");
6547 844 : std::string osPath;
6548 851 : for (const std::string &s : m_callPath)
6549 : {
6550 429 : if (!osPath.empty())
6551 53 : osPath += ' ';
6552 429 : osPath += s;
6553 : }
6554 422 : osRet += ' ';
6555 422 : osRet += osPath;
6556 :
6557 422 : bool hasNonPositionals = false;
6558 5329 : for (const auto &arg : m_args)
6559 : {
6560 4907 : if (!arg->IsHidden() && !arg->IsHiddenForCLI() && !arg->IsPositional())
6561 3555 : hasNonPositionals = true;
6562 : }
6563 :
6564 422 : if (HasSubAlgorithms())
6565 : {
6566 10 : if (m_callPath.size() == 1)
6567 : {
6568 9 : osRet += " <COMMAND>";
6569 9 : if (hasNonPositionals)
6570 9 : osRet += " [OPTIONS]";
6571 9 : if (usageOptions.isPipelineStep)
6572 : {
6573 5 : const size_t nLenFirstLine = osRet.size();
6574 5 : osRet += '\n';
6575 5 : osRet.append(nLenFirstLine, '-');
6576 5 : osRet += '\n';
6577 : }
6578 9 : osRet += "\nwhere <COMMAND> is one of:\n";
6579 : }
6580 : else
6581 : {
6582 1 : osRet += " <SUBCOMMAND>";
6583 1 : if (hasNonPositionals)
6584 1 : osRet += " [OPTIONS]";
6585 1 : if (usageOptions.isPipelineStep)
6586 : {
6587 0 : const size_t nLenFirstLine = osRet.size();
6588 0 : osRet += '\n';
6589 0 : osRet.append(nLenFirstLine, '-');
6590 0 : osRet += '\n';
6591 : }
6592 1 : osRet += "\nwhere <SUBCOMMAND> is one of:\n";
6593 : }
6594 10 : size_t maxNameLen = 0;
6595 62 : for (const auto &subAlgName : GetSubAlgorithmNames())
6596 : {
6597 52 : maxNameLen = std::max(maxNameLen, subAlgName.size());
6598 : }
6599 62 : for (const auto &subAlgName : GetSubAlgorithmNames())
6600 : {
6601 104 : auto subAlg = InstantiateSubAlgorithm(subAlgName);
6602 52 : if (subAlg && !subAlg->IsHidden())
6603 : {
6604 52 : const std::string &name(subAlg->GetName());
6605 52 : osRet += " - ";
6606 52 : osRet += name;
6607 52 : osRet += ": ";
6608 52 : osRet.append(maxNameLen - name.size(), ' ');
6609 52 : osRet += subAlg->GetDescription();
6610 52 : if (!subAlg->m_aliases.empty())
6611 : {
6612 8 : bool first = true;
6613 8 : for (const auto &alias : subAlg->GetAliases())
6614 : {
6615 8 : if (alias ==
6616 : GDALAlgorithmRegistry::HIDDEN_ALIAS_SEPARATOR)
6617 8 : break;
6618 0 : if (first)
6619 0 : osRet += " (alias: ";
6620 : else
6621 0 : osRet += ", ";
6622 0 : osRet += alias;
6623 0 : first = false;
6624 : }
6625 8 : if (!first)
6626 : {
6627 0 : osRet += ')';
6628 : }
6629 : }
6630 52 : osRet += '\n';
6631 : }
6632 : }
6633 :
6634 10 : if (shortUsage && hasNonPositionals)
6635 : {
6636 3 : osRet += "\nTry '";
6637 3 : osRet += osPath;
6638 3 : osRet += " --help' for help.\n";
6639 : }
6640 : }
6641 : else
6642 : {
6643 412 : if (!m_args.empty())
6644 : {
6645 412 : if (hasNonPositionals)
6646 412 : osRet += " [OPTIONS]";
6647 603 : for (const auto *arg : m_positionalArgs)
6648 : {
6649 273 : if ((!arg->IsHidden() && !arg->IsHiddenForCLI()) ||
6650 82 : (GetName() == "pipeline" && arg->GetName() == "pipeline"))
6651 : {
6652 : const bool optional =
6653 199 : (!arg->IsRequired() && !(GetName() == "pipeline" &&
6654 30 : arg->GetName() == "pipeline"));
6655 169 : osRet += ' ';
6656 169 : if (optional)
6657 25 : osRet += '[';
6658 169 : const std::string &metavar = arg->GetMetaVar();
6659 169 : if (!metavar.empty() && metavar[0] == '<')
6660 : {
6661 4 : osRet += metavar;
6662 : }
6663 : else
6664 : {
6665 165 : osRet += '<';
6666 165 : osRet += metavar;
6667 165 : osRet += '>';
6668 : }
6669 211 : if (arg->GetType() == GAAT_DATASET_LIST &&
6670 42 : arg->GetMaxCount() > 1)
6671 : {
6672 28 : osRet += "...";
6673 : }
6674 169 : if (optional)
6675 25 : osRet += ']';
6676 : }
6677 : }
6678 : }
6679 :
6680 412 : const size_t nLenFirstLine = osRet.size();
6681 412 : osRet += '\n';
6682 412 : if (usageOptions.isPipelineStep)
6683 : {
6684 322 : osRet.append(nLenFirstLine, '-');
6685 322 : osRet += '\n';
6686 : }
6687 :
6688 412 : if (shortUsage)
6689 : {
6690 23 : osRet += "Try '";
6691 23 : osRet += osPath;
6692 23 : osRet += " --help' for help.\n";
6693 23 : return osRet;
6694 : }
6695 :
6696 389 : osRet += '\n';
6697 389 : osRet += m_description;
6698 389 : osRet += '\n';
6699 : }
6700 :
6701 399 : if (!m_args.empty() && !shortUsage)
6702 : {
6703 792 : std::vector<std::pair<GDALAlgorithmArg *, std::string>> options;
6704 : size_t maxOptLen;
6705 396 : std::tie(options, maxOptLen) = GetArgNamesForCLI();
6706 396 : if (usageOptions.maxOptLen)
6707 323 : maxOptLen = usageOptions.maxOptLen;
6708 :
6709 792 : const std::string userProvidedOpt = "--<user-provided-option>=<value>";
6710 396 : if (m_arbitraryLongNameArgsAllowed)
6711 2 : maxOptLen = std::max(maxOptLen, userProvidedOpt.size());
6712 :
6713 : const auto OutputArg =
6714 2552 : [this, maxOptLen, &osRet,
6715 25581 : &usageOptions](const GDALAlgorithmArg *arg, const std::string &opt)
6716 : {
6717 2552 : osRet += " ";
6718 2552 : osRet += opt;
6719 2552 : osRet += " ";
6720 2552 : osRet.append(maxOptLen - opt.size(), ' ');
6721 2552 : osRet += arg->GetDescription();
6722 :
6723 2552 : const auto &choices = arg->GetChoices();
6724 2552 : if (!choices.empty())
6725 : {
6726 237 : osRet += ". ";
6727 237 : osRet += arg->GetMetaVar();
6728 237 : osRet += '=';
6729 237 : bool firstChoice = true;
6730 1800 : for (const auto &choice : choices)
6731 : {
6732 1563 : if (!firstChoice)
6733 1326 : osRet += '|';
6734 1563 : osRet += choice;
6735 1563 : firstChoice = false;
6736 : }
6737 : }
6738 :
6739 5029 : if (arg->GetType() == GAAT_DATASET ||
6740 2477 : arg->GetType() == GAAT_DATASET_LIST)
6741 : {
6742 153 : if (arg->IsOutput() &&
6743 153 : arg->GetDatasetInputFlags() == GADV_NAME &&
6744 9 : arg->GetDatasetOutputFlags() == GADV_OBJECT)
6745 : {
6746 9 : osRet += " (created by algorithm)";
6747 : }
6748 : }
6749 :
6750 2552 : if (arg->GetType() == GAAT_STRING && arg->HasDefaultValue())
6751 : {
6752 198 : osRet += " (default: ";
6753 198 : osRet += arg->GetDefault<std::string>();
6754 198 : osRet += ')';
6755 : }
6756 2354 : else if (arg->GetType() == GAAT_BOOLEAN && arg->HasDefaultValue())
6757 : {
6758 70 : if (arg->GetDefault<bool>())
6759 0 : osRet += " (default: true)";
6760 : }
6761 2284 : else if (arg->GetType() == GAAT_INTEGER && arg->HasDefaultValue())
6762 : {
6763 84 : osRet += " (default: ";
6764 84 : osRet += CPLSPrintf("%d", arg->GetDefault<int>());
6765 84 : osRet += ')';
6766 : }
6767 2200 : else if (arg->GetType() == GAAT_REAL && arg->HasDefaultValue())
6768 : {
6769 49 : osRet += " (default: ";
6770 49 : osRet += CPLSPrintf("%g", arg->GetDefault<double>());
6771 49 : osRet += ')';
6772 : }
6773 2602 : else if (arg->GetType() == GAAT_STRING_LIST &&
6774 451 : arg->HasDefaultValue())
6775 : {
6776 : const auto &defaultVal =
6777 17 : arg->GetDefault<std::vector<std::string>>();
6778 17 : if (defaultVal.size() == 1)
6779 : {
6780 17 : osRet += " (default: ";
6781 17 : osRet += defaultVal[0];
6782 17 : osRet += ')';
6783 : }
6784 : }
6785 2157 : else if (arg->GetType() == GAAT_INTEGER_LIST &&
6786 23 : arg->HasDefaultValue())
6787 : {
6788 0 : const auto &defaultVal = arg->GetDefault<std::vector<int>>();
6789 0 : if (defaultVal.size() == 1)
6790 : {
6791 0 : osRet += " (default: ";
6792 0 : osRet += CPLSPrintf("%d", defaultVal[0]);
6793 0 : osRet += ')';
6794 : }
6795 : }
6796 2134 : else if (arg->GetType() == GAAT_REAL_LIST && arg->HasDefaultValue())
6797 : {
6798 0 : const auto &defaultVal = arg->GetDefault<std::vector<double>>();
6799 0 : if (defaultVal.size() == 1)
6800 : {
6801 0 : osRet += " (default: ";
6802 0 : osRet += CPLSPrintf("%g", defaultVal[0]);
6803 0 : osRet += ')';
6804 : }
6805 : }
6806 :
6807 2552 : if (arg->GetDisplayHintAboutRepetition())
6808 : {
6809 2581 : if (arg->GetMinCount() > 0 &&
6810 92 : arg->GetMinCount() == arg->GetMaxCount())
6811 : {
6812 18 : if (arg->GetMinCount() != 1)
6813 5 : osRet += CPLSPrintf(" [%d values]", arg->GetMaxCount());
6814 : }
6815 2545 : else if (arg->GetMinCount() > 0 &&
6816 74 : arg->GetMaxCount() < GDALAlgorithmArgDecl::UNBOUNDED)
6817 : {
6818 : osRet += CPLSPrintf(" [%d..%d values]", arg->GetMinCount(),
6819 8 : arg->GetMaxCount());
6820 : }
6821 2463 : else if (arg->GetMinCount() > 0)
6822 : {
6823 66 : osRet += CPLSPrintf(" [%d.. values]", arg->GetMinCount());
6824 : }
6825 2397 : else if (arg->GetMaxCount() > 1)
6826 : {
6827 432 : osRet += " [may be repeated]";
6828 : }
6829 : }
6830 :
6831 2552 : if (arg->IsRequired())
6832 : {
6833 168 : osRet += " [required]";
6834 : }
6835 :
6836 2801 : if (!arg->IsAvailableInPipelineStep() &&
6837 249 : !usageOptions.isPipelineStep)
6838 : {
6839 29 : osRet += " [not available in pipelines]";
6840 : }
6841 :
6842 2552 : osRet += '\n';
6843 :
6844 2552 : const auto &mutualExclusionGroup = arg->GetMutualExclusionGroup();
6845 2552 : if (!mutualExclusionGroup.empty())
6846 : {
6847 550 : std::string otherArgs;
6848 5159 : for (const auto &otherArg : m_args)
6849 : {
6850 8963 : if (otherArg->IsHidden() || otherArg->IsHiddenForCLI() ||
6851 4079 : otherArg.get() == arg)
6852 1080 : continue;
6853 3804 : if (otherArg->GetMutualExclusionGroup() ==
6854 : mutualExclusionGroup)
6855 : {
6856 372 : if (!otherArgs.empty())
6857 101 : otherArgs += ", ";
6858 372 : otherArgs += "--";
6859 372 : otherArgs += otherArg->GetName();
6860 : }
6861 : }
6862 275 : if (!otherArgs.empty())
6863 : {
6864 271 : osRet += " ";
6865 271 : osRet += " ";
6866 271 : osRet.append(maxOptLen, ' ');
6867 271 : osRet += "Mutually exclusive with ";
6868 271 : osRet += otherArgs;
6869 271 : osRet += '\n';
6870 : }
6871 : }
6872 :
6873 : // Check dependency
6874 5104 : std::string dependencyArgs;
6875 :
6876 32 : for (const auto &dependencyArgumentName :
6877 2616 : GetArgDependencies(arg->GetName()))
6878 : {
6879 32 : const auto otherArg{GetArg(dependencyArgumentName)};
6880 32 : if (otherArg != nullptr)
6881 : {
6882 32 : if (otherArg->IsHidden() || otherArg->IsHiddenForCLI() ||
6883 : otherArg == arg)
6884 : {
6885 0 : continue;
6886 : }
6887 :
6888 32 : if (!dependencyArgs.empty())
6889 : {
6890 3 : dependencyArgs += ", ";
6891 : }
6892 :
6893 32 : dependencyArgs += "--";
6894 32 : dependencyArgs += otherArg->GetName();
6895 : }
6896 : else
6897 : {
6898 0 : CPLError(CE_Warning, CPLE_AppDefined,
6899 : "Argument '%s' depends on unknown argument '%s'",
6900 0 : arg->GetName().c_str(),
6901 : dependencyArgumentName.c_str());
6902 : }
6903 : }
6904 :
6905 2552 : if (!dependencyArgs.empty())
6906 : {
6907 29 : osRet += " ";
6908 29 : osRet += " ";
6909 29 : osRet.append(maxOptLen, ' ');
6910 29 : osRet += "Depends on ";
6911 29 : osRet += dependencyArgs;
6912 29 : osRet += '\n';
6913 : }
6914 2552 : };
6915 :
6916 396 : if (!m_positionalArgs.empty())
6917 : {
6918 151 : osRet += "\nPositional arguments:\n";
6919 1619 : for (const auto &[arg, opt] : options)
6920 : {
6921 1468 : if (arg->IsPositional())
6922 136 : OutputArg(arg, opt);
6923 : }
6924 : }
6925 :
6926 396 : if (hasNonPositionals)
6927 : {
6928 396 : bool hasCommon = false;
6929 396 : bool hasBase = false;
6930 396 : bool hasAdvanced = false;
6931 396 : bool hasEsoteric = false;
6932 792 : std::vector<std::string> categories;
6933 3933 : for (const auto &iter : options)
6934 : {
6935 3537 : const auto &arg = iter.first;
6936 3537 : if (!arg->IsPositional())
6937 : {
6938 3401 : const auto &category = arg->GetCategory();
6939 3401 : if (category == GAAC_COMMON)
6940 : {
6941 1207 : hasCommon = true;
6942 : }
6943 2194 : else if (category == GAAC_BASE)
6944 : {
6945 1922 : hasBase = true;
6946 : }
6947 272 : else if (category == GAAC_ADVANCED)
6948 : {
6949 210 : hasAdvanced = true;
6950 : }
6951 62 : else if (category == GAAC_ESOTERIC)
6952 : {
6953 29 : hasEsoteric = true;
6954 : }
6955 33 : else if (std::find(categories.begin(), categories.end(),
6956 33 : category) == categories.end())
6957 : {
6958 9 : categories.push_back(category);
6959 : }
6960 : }
6961 : }
6962 396 : if (hasAdvanced || m_arbitraryLongNameArgsAllowed)
6963 71 : categories.insert(categories.begin(), GAAC_ADVANCED);
6964 396 : if (hasBase)
6965 349 : categories.insert(categories.begin(), GAAC_BASE);
6966 396 : if (hasCommon && !usageOptions.isPipelineStep)
6967 69 : categories.insert(categories.begin(), GAAC_COMMON);
6968 396 : if (hasEsoteric)
6969 11 : categories.push_back(GAAC_ESOTERIC);
6970 :
6971 905 : for (const auto &category : categories)
6972 : {
6973 509 : osRet += "\n";
6974 509 : if (category != GAAC_BASE)
6975 : {
6976 160 : osRet += category;
6977 160 : osRet += ' ';
6978 : }
6979 509 : osRet += "Options:\n";
6980 5617 : for (const auto &[arg, opt] : options)
6981 : {
6982 5108 : if (!arg->IsPositional() && arg->GetCategory() == category)
6983 2416 : OutputArg(arg, opt);
6984 : }
6985 509 : if (m_arbitraryLongNameArgsAllowed && category == GAAC_ADVANCED)
6986 : {
6987 2 : osRet += " ";
6988 2 : osRet += userProvidedOpt;
6989 2 : osRet += " ";
6990 2 : if (userProvidedOpt.size() < maxOptLen)
6991 0 : osRet.append(maxOptLen - userProvidedOpt.size(), ' ');
6992 2 : osRet += "Argument provided by user";
6993 2 : osRet += '\n';
6994 : }
6995 : }
6996 : }
6997 : }
6998 :
6999 399 : if (!m_longDescription.empty())
7000 : {
7001 7 : osRet += '\n';
7002 7 : osRet += m_longDescription;
7003 7 : osRet += '\n';
7004 : }
7005 :
7006 399 : if (!m_helpDocRequested && !usageOptions.isPipelineMain)
7007 : {
7008 384 : if (!m_helpURL.empty())
7009 : {
7010 384 : osRet += "\nFor more details, consult ";
7011 384 : osRet += GetHelpFullURL();
7012 384 : osRet += '\n';
7013 : }
7014 384 : osRet += GetUsageForCLIEnd();
7015 : }
7016 :
7017 399 : return osRet;
7018 : }
7019 :
7020 : /************************************************************************/
7021 : /* GDALAlgorithm::GetUsageForCLIEnd() */
7022 : /************************************************************************/
7023 :
7024 : //! @cond Doxygen_Suppress
7025 391 : std::string GDALAlgorithm::GetUsageForCLIEnd() const
7026 : {
7027 391 : std::string osRet;
7028 :
7029 391 : if (!m_callPath.empty() && m_callPath[0] == "gdal")
7030 : {
7031 : osRet += "\nWARNING: the gdal command is provisionally provided as an "
7032 : "alternative interface to GDAL and OGR command line "
7033 : "utilities.\nThe project reserves the right to modify, "
7034 : "rename, reorganize, and change the behavior of the utility\n"
7035 : "until it is officially frozen in a future feature release of "
7036 14 : "GDAL.\n";
7037 : }
7038 391 : return osRet;
7039 : }
7040 :
7041 : //! @endcond
7042 :
7043 : /************************************************************************/
7044 : /* GDALAlgorithm::GetUsageAsJSON() */
7045 : /************************************************************************/
7046 :
7047 591 : std::string GDALAlgorithm::GetUsageAsJSON() const
7048 : {
7049 1182 : CPLJSONDocument oDoc;
7050 1182 : auto oRoot = oDoc.GetRoot();
7051 :
7052 591 : if (m_displayInJSONUsage)
7053 : {
7054 589 : oRoot.Add("name", m_name);
7055 589 : CPLJSONArray jFullPath;
7056 1226 : for (const std::string &s : m_callPath)
7057 : {
7058 637 : jFullPath.Add(s);
7059 : }
7060 589 : oRoot.Add("full_path", jFullPath);
7061 : }
7062 :
7063 591 : oRoot.Add("description", m_description);
7064 591 : if (!m_helpURL.empty())
7065 : {
7066 588 : oRoot.Add("short_url", m_helpURL);
7067 588 : oRoot.Add("url", GetHelpFullURL());
7068 : }
7069 :
7070 1182 : CPLJSONArray jSubAlgorithms;
7071 800 : for (const auto &subAlgName : GetSubAlgorithmNames())
7072 : {
7073 418 : auto subAlg = InstantiateSubAlgorithm(subAlgName);
7074 209 : if (subAlg && subAlg->m_displayInJSONUsage && !subAlg->IsHidden())
7075 : {
7076 207 : CPLJSONDocument oSubDoc;
7077 207 : CPL_IGNORE_RET_VAL(oSubDoc.LoadMemory(subAlg->GetUsageAsJSON()));
7078 207 : jSubAlgorithms.Add(oSubDoc.GetRoot());
7079 : }
7080 : }
7081 591 : oRoot.Add("sub_algorithms", jSubAlgorithms);
7082 :
7083 591 : if (m_arbitraryLongNameArgsAllowed)
7084 : {
7085 1 : oRoot.Add("user_provided_arguments_allowed", true);
7086 : }
7087 :
7088 11316 : const auto ProcessArg = [this](const GDALAlgorithmArg *arg)
7089 : {
7090 5658 : CPLJSONObject jArg;
7091 5658 : jArg.Add("name", arg->GetName());
7092 5658 : jArg.Add("type", GDALAlgorithmArgTypeName(arg->GetType()));
7093 5658 : jArg.Add("description", arg->GetDescription());
7094 :
7095 5658 : const auto &metaVar = arg->GetMetaVar();
7096 5658 : if (!metaVar.empty() && metaVar != CPLString(arg->GetName()).toupper())
7097 : {
7098 1727 : if (metaVar.front() == '<' && metaVar.back() == '>' &&
7099 1727 : metaVar.substr(1, metaVar.size() - 2).find('>') ==
7100 : std::string::npos)
7101 32 : jArg.Add("metavar", metaVar.substr(1, metaVar.size() - 2));
7102 : else
7103 922 : jArg.Add("metavar", metaVar);
7104 : }
7105 :
7106 5658 : if (!arg->IsAvailableInPipelineStep())
7107 : {
7108 1659 : jArg.Add("available_in_pipeline_step", false);
7109 : }
7110 :
7111 5658 : const auto &choices = arg->GetChoices();
7112 5658 : if (!choices.empty())
7113 : {
7114 431 : CPLJSONArray jChoices;
7115 3647 : for (const auto &choice : choices)
7116 3216 : jChoices.Add(choice);
7117 431 : jArg.Add("choices", jChoices);
7118 : }
7119 5658 : if (arg->HasDefaultValue())
7120 : {
7121 1236 : switch (arg->GetType())
7122 : {
7123 436 : case GAAT_BOOLEAN:
7124 436 : jArg.Add("default", arg->GetDefault<bool>());
7125 436 : break;
7126 378 : case GAAT_STRING:
7127 378 : jArg.Add("default", arg->GetDefault<std::string>());
7128 378 : break;
7129 210 : case GAAT_INTEGER:
7130 210 : jArg.Add("default", arg->GetDefault<int>());
7131 210 : break;
7132 178 : case GAAT_REAL:
7133 178 : jArg.Add("default", arg->GetDefault<double>());
7134 178 : break;
7135 32 : case GAAT_STRING_LIST:
7136 : {
7137 : const auto &val =
7138 32 : arg->GetDefault<std::vector<std::string>>();
7139 32 : if (val.size() == 1)
7140 : {
7141 31 : jArg.Add("default", val[0]);
7142 : }
7143 : else
7144 : {
7145 1 : CPLJSONArray jArr;
7146 3 : for (const auto &s : val)
7147 : {
7148 2 : jArr.Add(s);
7149 : }
7150 1 : jArg.Add("default", jArr);
7151 : }
7152 32 : break;
7153 : }
7154 1 : case GAAT_INTEGER_LIST:
7155 : {
7156 1 : const auto &val = arg->GetDefault<std::vector<int>>();
7157 1 : if (val.size() == 1)
7158 : {
7159 0 : jArg.Add("default", val[0]);
7160 : }
7161 : else
7162 : {
7163 1 : CPLJSONArray jArr;
7164 3 : for (int i : val)
7165 : {
7166 2 : jArr.Add(i);
7167 : }
7168 1 : jArg.Add("default", jArr);
7169 : }
7170 1 : break;
7171 : }
7172 1 : case GAAT_REAL_LIST:
7173 : {
7174 1 : const auto &val = arg->GetDefault<std::vector<double>>();
7175 1 : if (val.size() == 1)
7176 : {
7177 0 : jArg.Add("default", val[0]);
7178 : }
7179 : else
7180 : {
7181 1 : CPLJSONArray jArr;
7182 3 : for (double d : val)
7183 : {
7184 2 : jArr.Add(d);
7185 : }
7186 1 : jArg.Add("default", jArr);
7187 : }
7188 1 : break;
7189 : }
7190 0 : case GAAT_DATASET:
7191 : case GAAT_DATASET_LIST:
7192 0 : CPLError(CE_Warning, CPLE_AppDefined,
7193 : "Unhandled default value for arg %s",
7194 0 : arg->GetName().c_str());
7195 0 : break;
7196 : }
7197 : }
7198 :
7199 5658 : const auto [minVal, minValIsIncluded] = arg->GetMinValue();
7200 5658 : if (!std::isnan(minVal))
7201 : {
7202 697 : if (arg->GetType() == GAAT_INTEGER ||
7203 269 : arg->GetType() == GAAT_INTEGER_LIST)
7204 175 : jArg.Add("min_value", static_cast<int>(minVal));
7205 : else
7206 253 : jArg.Add("min_value", minVal);
7207 428 : jArg.Add("min_value_is_included", minValIsIncluded);
7208 : }
7209 :
7210 5658 : const auto [maxVal, maxValIsIncluded] = arg->GetMaxValue();
7211 5658 : if (!std::isnan(maxVal))
7212 : {
7213 199 : if (arg->GetType() == GAAT_INTEGER ||
7214 82 : arg->GetType() == GAAT_INTEGER_LIST)
7215 35 : jArg.Add("max_value", static_cast<int>(maxVal));
7216 : else
7217 82 : jArg.Add("max_value", maxVal);
7218 117 : jArg.Add("max_value_is_included", maxValIsIncluded);
7219 : }
7220 :
7221 5658 : jArg.Add("required", arg->IsRequired());
7222 5658 : if (GDALAlgorithmArgTypeIsList(arg->GetType()))
7223 : {
7224 1599 : jArg.Add("packed_values_allowed", arg->GetPackedValuesAllowed());
7225 1599 : jArg.Add("repeated_arg_allowed", arg->GetRepeatedArgAllowed());
7226 1599 : jArg.Add("min_count", arg->GetMinCount());
7227 1599 : jArg.Add("max_count", arg->GetMaxCount());
7228 : }
7229 :
7230 : // Process dependencies
7231 5658 : const auto &mutualDependencyGroup = arg->GetMutualDependencyGroup();
7232 5658 : if (!mutualDependencyGroup.empty())
7233 : {
7234 32 : jArg.Add("mutual_dependency_group", mutualDependencyGroup);
7235 : }
7236 :
7237 11316 : CPLJSONArray jDependencies;
7238 50 : for (const auto &dependencyArgumentName :
7239 5758 : GetArgDependencies(arg->GetName()))
7240 : {
7241 50 : jDependencies.Add(dependencyArgumentName);
7242 : }
7243 :
7244 5658 : if (jDependencies.Size() > 0)
7245 : {
7246 50 : jArg.Add("depends_on", jDependencies);
7247 : }
7248 :
7249 5658 : jArg.Add("category", arg->GetCategory());
7250 :
7251 11051 : if (arg->GetType() == GAAT_DATASET ||
7252 5393 : arg->GetType() == GAAT_DATASET_LIST)
7253 : {
7254 : {
7255 479 : CPLJSONArray jAr;
7256 479 : if (arg->GetDatasetType() & GDAL_OF_RASTER)
7257 320 : jAr.Add("raster");
7258 479 : if (arg->GetDatasetType() & GDAL_OF_VECTOR)
7259 192 : jAr.Add("vector");
7260 479 : if (arg->GetDatasetType() & GDAL_OF_MULTIDIM_RASTER)
7261 41 : jAr.Add("multidim_raster");
7262 479 : jArg.Add("dataset_type", jAr);
7263 : }
7264 :
7265 650 : const auto GetFlags = [](int flags)
7266 : {
7267 650 : CPLJSONArray jAr;
7268 650 : if (flags & GADV_NAME)
7269 479 : jAr.Add("name");
7270 650 : if (flags & GADV_OBJECT)
7271 609 : jAr.Add("dataset");
7272 650 : return jAr;
7273 : };
7274 :
7275 479 : if (arg->IsInput())
7276 : {
7277 479 : jArg.Add("input_flags", GetFlags(arg->GetDatasetInputFlags()));
7278 : }
7279 479 : if (arg->IsOutput())
7280 : {
7281 171 : jArg.Add("output_flags",
7282 342 : GetFlags(arg->GetDatasetOutputFlags()));
7283 : }
7284 : }
7285 :
7286 5658 : const auto &mutualExclusionGroup = arg->GetMutualExclusionGroup();
7287 5658 : if (!mutualExclusionGroup.empty())
7288 : {
7289 748 : jArg.Add("mutual_exclusion_group", mutualExclusionGroup);
7290 : }
7291 :
7292 11316 : const auto &metadata = arg->GetMetadata();
7293 5658 : if (!metadata.empty())
7294 : {
7295 460 : CPLJSONObject jMetadata;
7296 959 : for (const auto &[key, values] : metadata)
7297 : {
7298 998 : CPLJSONArray jValue;
7299 1204 : for (const auto &value : values)
7300 705 : jValue.Add(value);
7301 499 : jMetadata.Add(key, jValue);
7302 : }
7303 460 : jArg.Add("metadata", jMetadata);
7304 : }
7305 :
7306 11316 : return jArg;
7307 591 : };
7308 :
7309 : {
7310 591 : CPLJSONArray jArgs;
7311 9348 : for (const auto &arg : m_args)
7312 : {
7313 8757 : if (!arg->IsHiddenForAPI() && arg->IsInput() && !arg->IsOutput())
7314 5422 : jArgs.Add(ProcessArg(arg.get()));
7315 : }
7316 591 : oRoot.Add("input_arguments", jArgs);
7317 : }
7318 :
7319 : {
7320 591 : CPLJSONArray jArgs;
7321 9348 : for (const auto &arg : m_args)
7322 : {
7323 8757 : if (!arg->IsHiddenForAPI() && !arg->IsInput() && arg->IsOutput())
7324 65 : jArgs.Add(ProcessArg(arg.get()));
7325 : }
7326 591 : oRoot.Add("output_arguments", jArgs);
7327 : }
7328 :
7329 : {
7330 591 : CPLJSONArray jArgs;
7331 9348 : for (const auto &arg : m_args)
7332 : {
7333 8757 : if (!arg->IsHiddenForAPI() && arg->IsInput() && arg->IsOutput())
7334 171 : jArgs.Add(ProcessArg(arg.get()));
7335 : }
7336 591 : oRoot.Add("input_output_arguments", jArgs);
7337 : }
7338 :
7339 591 : if (m_supportsStreamedOutput)
7340 : {
7341 127 : oRoot.Add("supports_streamed_output", true);
7342 : }
7343 :
7344 1182 : return oDoc.SaveAsString();
7345 : }
7346 :
7347 : /************************************************************************/
7348 : /* GDALAlgorithm::GetAutoComplete() */
7349 : /************************************************************************/
7350 :
7351 : std::vector<std::string>
7352 295 : GDALAlgorithm::GetAutoComplete(std::vector<std::string> &args,
7353 : bool lastWordIsComplete, bool showAllOptions)
7354 : {
7355 590 : std::vector<std::string> ret;
7356 :
7357 : // Get inner-most algorithm
7358 295 : std::unique_ptr<GDALAlgorithm> curAlgHolder;
7359 295 : GDALAlgorithm *curAlg = this;
7360 580 : while (!args.empty() && !args.front().empty() && args.front()[0] != '-')
7361 : {
7362 : auto subAlg = curAlg->InstantiateSubAlgorithm(
7363 431 : args.front(), /* suggestionAllowed = */ false);
7364 431 : if (!subAlg)
7365 145 : break;
7366 286 : if (args.size() == 1 && !lastWordIsComplete)
7367 : {
7368 5 : int nCount = 0;
7369 116 : for (const auto &subAlgName : curAlg->GetSubAlgorithmNames())
7370 : {
7371 111 : if (STARTS_WITH(subAlgName.c_str(), args.front().c_str()))
7372 6 : nCount++;
7373 : }
7374 5 : if (nCount >= 2)
7375 : {
7376 11 : for (const std::string &subAlgName :
7377 23 : curAlg->GetSubAlgorithmNames())
7378 : {
7379 11 : subAlg = curAlg->InstantiateSubAlgorithm(subAlgName);
7380 11 : if (subAlg && !subAlg->IsHidden())
7381 11 : ret.push_back(subAlg->GetName());
7382 : }
7383 1 : return ret;
7384 : }
7385 : }
7386 285 : showAllOptions = false;
7387 285 : args.erase(args.begin());
7388 285 : curAlgHolder = std::move(subAlg);
7389 285 : curAlg = curAlgHolder.get();
7390 : }
7391 294 : if (curAlg != this)
7392 : {
7393 155 : curAlg->m_calledFromCommandLine = m_calledFromCommandLine;
7394 : return curAlg->GetAutoComplete(args, lastWordIsComplete,
7395 155 : /* showAllOptions = */ false);
7396 : }
7397 :
7398 278 : std::string option;
7399 278 : std::string value;
7400 139 : ExtractLastOptionAndValue(args, option, value);
7401 :
7402 170 : if (option.empty() && !args.empty() && !args.back().empty() &&
7403 31 : args.back()[0] == '-')
7404 : {
7405 28 : const auto &lastArg = args.back();
7406 : // List available options
7407 419 : for (const auto &arg : GetArgs())
7408 : {
7409 721 : if (arg->IsHidden() || arg->IsHiddenForCLI() ||
7410 655 : (!showAllOptions &&
7411 894 : (arg->GetName() == "help" || arg->GetName() == "config" ||
7412 542 : arg->GetName() == "version" ||
7413 271 : arg->GetName() == "json-usage")))
7414 : {
7415 142 : continue;
7416 : }
7417 249 : if (!arg->GetShortName().empty())
7418 : {
7419 153 : std::string str = std::string("-").append(arg->GetShortName());
7420 51 : if (lastArg == str)
7421 0 : ret.push_back(std::move(str));
7422 : }
7423 249 : if (lastArg != "-" && lastArg != "--")
7424 : {
7425 54 : for (const std::string &alias : arg->GetAliases())
7426 : {
7427 48 : std::string str = std::string("--").append(alias);
7428 16 : if (cpl::starts_with(str, lastArg))
7429 3 : ret.push_back(std::move(str));
7430 : }
7431 : }
7432 249 : if (!arg->GetName().empty())
7433 : {
7434 747 : std::string str = std::string("--").append(arg->GetName());
7435 249 : if (cpl::starts_with(str, lastArg))
7436 213 : ret.push_back(std::move(str));
7437 : }
7438 : }
7439 28 : std::sort(ret.begin(), ret.end());
7440 : }
7441 111 : else if (!option.empty())
7442 : {
7443 : // List possible choices for current option
7444 104 : auto arg = GetArg(option);
7445 104 : if (arg && arg->GetType() != GAAT_BOOLEAN)
7446 : {
7447 104 : ret = arg->GetChoices();
7448 104 : if (ret.empty())
7449 : {
7450 : {
7451 99 : CPLErrorStateBackuper oErrorQuieter(CPLQuietErrorHandler);
7452 99 : SetParseForAutoCompletion();
7453 99 : CPL_IGNORE_RET_VAL(ParseCommandLineArguments(args));
7454 : }
7455 99 : ret = arg->GetAutoCompleteChoices(value);
7456 : }
7457 : else
7458 : {
7459 5 : std::sort(ret.begin(), ret.end());
7460 : }
7461 104 : if (!ret.empty() && ret.back() == value)
7462 : {
7463 2 : ret.clear();
7464 : }
7465 102 : else if (ret.empty())
7466 : {
7467 13 : ret.push_back("**");
7468 : // Non printable UTF-8 space, to avoid autocompletion to pickup on 'd'
7469 26 : ret.push_back(std::string("\xC2\xA0"
7470 : "description: ")
7471 13 : .append(arg->GetDescription()));
7472 : }
7473 : }
7474 : }
7475 : else
7476 : {
7477 : // List possible sub-algorithms
7478 69 : for (const std::string &subAlgName : GetSubAlgorithmNames())
7479 : {
7480 124 : auto subAlg = InstantiateSubAlgorithm(subAlgName);
7481 62 : if (subAlg && !subAlg->IsHidden())
7482 62 : ret.push_back(subAlg->GetName());
7483 : }
7484 7 : if (!ret.empty())
7485 : {
7486 3 : std::sort(ret.begin(), ret.end());
7487 : }
7488 :
7489 : // Try filenames
7490 7 : if (ret.empty() && !args.empty())
7491 : {
7492 : {
7493 3 : CPLErrorStateBackuper oErrorQuieter(CPLQuietErrorHandler);
7494 3 : SetParseForAutoCompletion();
7495 3 : CPL_IGNORE_RET_VAL(ParseCommandLineArguments(args));
7496 : }
7497 :
7498 3 : const std::string &lastArg = args.back();
7499 3 : GDALAlgorithmArg *arg = nullptr;
7500 18 : for (const char *name : {GDAL_ARG_NAME_INPUT, "dataset", "filename",
7501 21 : "like", "source", "destination"})
7502 : {
7503 18 : if (!arg)
7504 : {
7505 3 : auto newArg = GetArg(name);
7506 3 : if (newArg)
7507 : {
7508 3 : if (!newArg->IsExplicitlySet())
7509 : {
7510 0 : arg = newArg;
7511 : }
7512 6 : else if (newArg->GetType() == GAAT_STRING ||
7513 5 : newArg->GetType() == GAAT_STRING_LIST ||
7514 8 : newArg->GetType() == GAAT_DATASET ||
7515 2 : newArg->GetType() == GAAT_DATASET_LIST)
7516 : {
7517 : VSIStatBufL sStat;
7518 5 : if ((!lastArg.empty() && lastArg.back() == '/') ||
7519 2 : VSIStatL(lastArg.c_str(), &sStat) != 0)
7520 : {
7521 3 : arg = newArg;
7522 : }
7523 : }
7524 : }
7525 : }
7526 : }
7527 3 : if (arg)
7528 : {
7529 3 : ret = arg->GetAutoCompleteChoices(lastArg);
7530 : }
7531 : }
7532 : }
7533 :
7534 139 : return ret;
7535 : }
7536 :
7537 : /************************************************************************/
7538 : /* GDALAlgorithm::GetFieldIndices() */
7539 : /************************************************************************/
7540 :
7541 44 : bool GDALAlgorithm::GetFieldIndices(const std::vector<std::string> &names,
7542 : OGRLayerH hLayer, std::vector<int> &indices)
7543 : {
7544 44 : VALIDATE_POINTER1(hLayer, __func__, false);
7545 :
7546 44 : const OGRLayer &layer = *OGRLayer::FromHandle(hLayer);
7547 :
7548 44 : if (names.size() == 1 && names[0] == "ALL")
7549 : {
7550 12 : const int nSrcFieldCount = layer.GetLayerDefn()->GetFieldCount();
7551 28 : for (int i = 0; i < nSrcFieldCount; ++i)
7552 : {
7553 16 : indices.push_back(i);
7554 : }
7555 : }
7556 32 : else if (!names.empty() && !(names.size() == 1 && names[0] == "NONE"))
7557 : {
7558 6 : std::set<int> fieldsAdded;
7559 14 : for (const std::string &osFieldName : names)
7560 : {
7561 :
7562 : const int nIdx =
7563 10 : layer.GetLayerDefn()->GetFieldIndex(osFieldName.c_str());
7564 :
7565 10 : if (nIdx < 0)
7566 : {
7567 2 : CPLError(CE_Failure, CPLE_AppDefined,
7568 : "Field '%s' does not exist in layer '%s'",
7569 2 : osFieldName.c_str(), layer.GetName());
7570 2 : return false;
7571 : }
7572 :
7573 8 : if (fieldsAdded.insert(nIdx).second)
7574 : {
7575 7 : indices.push_back(nIdx);
7576 : }
7577 : }
7578 : }
7579 :
7580 42 : return true;
7581 : }
7582 :
7583 : /************************************************************************/
7584 : /* GDALAlgorithm::ExtractLastOptionAndValue() */
7585 : /************************************************************************/
7586 :
7587 139 : void GDALAlgorithm::ExtractLastOptionAndValue(std::vector<std::string> &args,
7588 : std::string &option,
7589 : std::string &value) const
7590 : {
7591 139 : if (!args.empty() && !args.back().empty() && args.back()[0] == '-')
7592 : {
7593 97 : const auto nPosEqual = args.back().find('=');
7594 97 : if (nPosEqual == std::string::npos)
7595 : {
7596 : // Deal with "gdal ... --option"
7597 78 : if (GetArg(args.back()))
7598 : {
7599 50 : option = args.back();
7600 50 : args.pop_back();
7601 : }
7602 : }
7603 : else
7604 : {
7605 : // Deal with "gdal ... --option=<value>"
7606 19 : if (GetArg(args.back().substr(0, nPosEqual)))
7607 : {
7608 19 : option = args.back().substr(0, nPosEqual);
7609 19 : value = args.back().substr(nPosEqual + 1);
7610 19 : args.pop_back();
7611 : }
7612 : }
7613 : }
7614 78 : else if (args.size() >= 2 && !args[args.size() - 2].empty() &&
7615 36 : args[args.size() - 2][0] == '-')
7616 : {
7617 : // Deal with "gdal ... --option <value>"
7618 35 : auto arg = GetArg(args[args.size() - 2]);
7619 35 : if (arg && arg->GetType() != GAAT_BOOLEAN)
7620 : {
7621 35 : option = args[args.size() - 2];
7622 35 : value = args.back();
7623 35 : args.pop_back();
7624 : }
7625 : }
7626 :
7627 139 : const auto IsKeyValueOption = [](const std::string &osStr)
7628 : {
7629 382 : return osStr == "--co" || osStr == "--creation-option" ||
7630 357 : osStr == "--lco" || osStr == "--layer-creation-option" ||
7631 380 : osStr == "--oo" || osStr == "--open-option";
7632 : };
7633 :
7634 139 : if (IsKeyValueOption(option))
7635 : {
7636 23 : const auto nPosEqual = value.find('=');
7637 23 : if (nPosEqual != std::string::npos)
7638 : {
7639 11 : value.resize(nPosEqual);
7640 : }
7641 : }
7642 139 : }
7643 :
7644 : /************************************************************************/
7645 : /* GDALAlgorithm::GetArgDependencies() */
7646 : /************************************************************************/
7647 :
7648 : std::vector<std::string>
7649 8219 : GDALAlgorithm::GetArgDependencies(const std::string &osName) const
7650 : {
7651 8219 : const auto arg = GetArg(osName, false);
7652 8219 : if (!arg)
7653 : {
7654 0 : ReportError(CE_Failure, CPLE_AppDefined, "Argument '%s' does not exist",
7655 : osName.c_str());
7656 0 : return {};
7657 : }
7658 16438 : std::vector<std::string> dependencies = arg->GetDirectDependencies();
7659 8219 : if (const auto &mutualDependencyGroup = arg->GetMutualDependencyGroup();
7660 8219 : !mutualDependencyGroup.empty())
7661 : {
7662 896 : for (const auto &otherArg : m_args)
7663 : {
7664 1627 : if (otherArg.get() == arg ||
7665 786 : mutualDependencyGroup.compare(
7666 786 : otherArg->GetMutualDependencyGroup()) != 0)
7667 783 : continue;
7668 58 : dependencies.push_back(otherArg->GetName());
7669 : }
7670 : }
7671 8219 : return dependencies;
7672 : }
7673 :
7674 : //! @cond Doxygen_Suppress
7675 :
7676 : /************************************************************************/
7677 : /* GDALContainerAlgorithm::RunImpl() */
7678 : /************************************************************************/
7679 :
7680 0 : bool GDALContainerAlgorithm::RunImpl(GDALProgressFunc, void *)
7681 : {
7682 0 : return false;
7683 : }
7684 :
7685 : //! @endcond
7686 :
7687 : /************************************************************************/
7688 : /* GDALAlgorithmRelease() */
7689 : /************************************************************************/
7690 :
7691 : /** Release a handle to an algorithm.
7692 : *
7693 : * @since 3.11
7694 : */
7695 13532 : void GDALAlgorithmRelease(GDALAlgorithmH hAlg)
7696 : {
7697 13532 : delete hAlg;
7698 13532 : }
7699 :
7700 : /************************************************************************/
7701 : /* GDALAlgorithmGetName() */
7702 : /************************************************************************/
7703 :
7704 : /** Return the algorithm name.
7705 : *
7706 : * @param hAlg Handle to an algorithm. Must NOT be null.
7707 : * @return algorithm name whose lifetime is bound to hAlg and which must not
7708 : * be freed.
7709 : * @since 3.11
7710 : */
7711 6220 : const char *GDALAlgorithmGetName(GDALAlgorithmH hAlg)
7712 : {
7713 6220 : VALIDATE_POINTER1(hAlg, __func__, nullptr);
7714 6220 : return hAlg->ptr->GetName().c_str();
7715 : }
7716 :
7717 : /************************************************************************/
7718 : /* GDALAlgorithmGetDescription() */
7719 : /************************************************************************/
7720 :
7721 : /** Return the algorithm (short) description.
7722 : *
7723 : * @param hAlg Handle to an algorithm. Must NOT be null.
7724 : * @return algorithm description whose lifetime is bound to hAlg and which must
7725 : * not be freed.
7726 : * @since 3.11
7727 : */
7728 5988 : const char *GDALAlgorithmGetDescription(GDALAlgorithmH hAlg)
7729 : {
7730 5988 : VALIDATE_POINTER1(hAlg, __func__, nullptr);
7731 5988 : return hAlg->ptr->GetDescription().c_str();
7732 : }
7733 :
7734 : /************************************************************************/
7735 : /* GDALAlgorithmGetLongDescription() */
7736 : /************************************************************************/
7737 :
7738 : /** Return the algorithm (longer) description.
7739 : *
7740 : * @param hAlg Handle to an algorithm. Must NOT be null.
7741 : * @return algorithm description whose lifetime is bound to hAlg and which must
7742 : * not be freed.
7743 : * @since 3.11
7744 : */
7745 2 : const char *GDALAlgorithmGetLongDescription(GDALAlgorithmH hAlg)
7746 : {
7747 2 : VALIDATE_POINTER1(hAlg, __func__, nullptr);
7748 2 : return hAlg->ptr->GetLongDescription().c_str();
7749 : }
7750 :
7751 : /************************************************************************/
7752 : /* GDALAlgorithmGetHelpFullURL() */
7753 : /************************************************************************/
7754 :
7755 : /** Return the algorithm full URL.
7756 : *
7757 : * @param hAlg Handle to an algorithm. Must NOT be null.
7758 : * @return algorithm URL whose lifetime is bound to hAlg and which must
7759 : * not be freed.
7760 : * @since 3.11
7761 : */
7762 5250 : const char *GDALAlgorithmGetHelpFullURL(GDALAlgorithmH hAlg)
7763 : {
7764 5250 : VALIDATE_POINTER1(hAlg, __func__, nullptr);
7765 5250 : return hAlg->ptr->GetHelpFullURL().c_str();
7766 : }
7767 :
7768 : /************************************************************************/
7769 : /* GDALAlgorithmHasSubAlgorithms() */
7770 : /************************************************************************/
7771 :
7772 : /** Return whether the algorithm has sub-algorithms.
7773 : *
7774 : * @param hAlg Handle to an algorithm. Must NOT be null.
7775 : * @since 3.11
7776 : */
7777 9967 : bool GDALAlgorithmHasSubAlgorithms(GDALAlgorithmH hAlg)
7778 : {
7779 9967 : VALIDATE_POINTER1(hAlg, __func__, false);
7780 9967 : return hAlg->ptr->HasSubAlgorithms();
7781 : }
7782 :
7783 : /************************************************************************/
7784 : /* GDALAlgorithmGetSubAlgorithmNames() */
7785 : /************************************************************************/
7786 :
7787 : /** Get the names of registered algorithms.
7788 : *
7789 : * @param hAlg Handle to an algorithm. Must NOT be null.
7790 : * @return a NULL terminated list of names, which must be destroyed with
7791 : * CSLDestroy()
7792 : * @since 3.11
7793 : */
7794 938 : char **GDALAlgorithmGetSubAlgorithmNames(GDALAlgorithmH hAlg)
7795 : {
7796 938 : VALIDATE_POINTER1(hAlg, __func__, nullptr);
7797 938 : return CPLStringList(hAlg->ptr->GetSubAlgorithmNames()).StealList();
7798 : }
7799 :
7800 : /************************************************************************/
7801 : /* GDALAlgorithmInstantiateSubAlgorithm() */
7802 : /************************************************************************/
7803 :
7804 : /** Instantiate an algorithm by its name (or its alias).
7805 : *
7806 : * @param hAlg Handle to an algorithm. Must NOT be null.
7807 : * @param pszSubAlgName Algorithm name. Must NOT be null.
7808 : * @return an handle to the algorithm (to be freed with GDALAlgorithmRelease),
7809 : * or NULL if the algorithm does not exist or another error occurred.
7810 : * @since 3.11
7811 : */
7812 9388 : GDALAlgorithmH GDALAlgorithmInstantiateSubAlgorithm(GDALAlgorithmH hAlg,
7813 : const char *pszSubAlgName)
7814 : {
7815 9388 : VALIDATE_POINTER1(hAlg, __func__, nullptr);
7816 9388 : VALIDATE_POINTER1(pszSubAlgName, __func__, nullptr);
7817 18776 : auto subAlg = hAlg->ptr->InstantiateSubAlgorithm(pszSubAlgName);
7818 : return subAlg
7819 18776 : ? std::make_unique<GDALAlgorithmHS>(std::move(subAlg)).release()
7820 18776 : : nullptr;
7821 : }
7822 :
7823 : /************************************************************************/
7824 : /* GDALAlgorithmParseCommandLineArguments() */
7825 : /************************************************************************/
7826 :
7827 : /** Parse a command line argument, which does not include the algorithm
7828 : * name, to set the value of corresponding arguments.
7829 : *
7830 : * @param hAlg Handle to an algorithm. Must NOT be null.
7831 : * @param papszArgs NULL-terminated list of arguments, not including the algorithm name.
7832 : * @return true if successful, false otherwise
7833 : * @since 3.11
7834 : */
7835 :
7836 371 : bool GDALAlgorithmParseCommandLineArguments(GDALAlgorithmH hAlg,
7837 : CSLConstList papszArgs)
7838 : {
7839 371 : VALIDATE_POINTER1(hAlg, __func__, false);
7840 371 : return hAlg->ptr->ParseCommandLineArguments(CPLStringList(papszArgs));
7841 : }
7842 :
7843 : /************************************************************************/
7844 : /* GDALAlgorithmGetActualAlgorithm() */
7845 : /************************************************************************/
7846 :
7847 : /** Return the actual algorithm that is going to be invoked, when the
7848 : * current algorithm has sub-algorithms.
7849 : *
7850 : * Only valid after GDALAlgorithmParseCommandLineArguments() has been called.
7851 : *
7852 : * Note that the lifetime of the returned algorithm does not exceed the one of
7853 : * the hAlg instance that owns it.
7854 : *
7855 : * @param hAlg Handle to an algorithm. Must NOT be null.
7856 : * @return an handle to the algorithm (to be freed with GDALAlgorithmRelease).
7857 : * @since 3.11
7858 : */
7859 959 : GDALAlgorithmH GDALAlgorithmGetActualAlgorithm(GDALAlgorithmH hAlg)
7860 : {
7861 959 : VALIDATE_POINTER1(hAlg, __func__, nullptr);
7862 959 : return GDALAlgorithmHS::FromRef(hAlg->ptr->GetActualAlgorithm()).release();
7863 : }
7864 :
7865 : /************************************************************************/
7866 : /* GDALAlgorithmRun() */
7867 : /************************************************************************/
7868 :
7869 : /** Execute the algorithm, starting with ValidateArguments() and then
7870 : * calling RunImpl().
7871 : *
7872 : * This function must be called at most once per instance.
7873 : *
7874 : * @param hAlg Handle to an algorithm. Must NOT be null.
7875 : * @param pfnProgress Progress callback. May be null.
7876 : * @param pProgressData Progress callback user data. May be null.
7877 : * @return true if successful, false otherwise
7878 : * @since 3.11
7879 : */
7880 :
7881 3009 : bool GDALAlgorithmRun(GDALAlgorithmH hAlg, GDALProgressFunc pfnProgress,
7882 : void *pProgressData)
7883 : {
7884 3009 : VALIDATE_POINTER1(hAlg, __func__, false);
7885 3009 : return hAlg->ptr->Run(pfnProgress, pProgressData);
7886 : }
7887 :
7888 : /************************************************************************/
7889 : /* GDALAlgorithmFinalize() */
7890 : /************************************************************************/
7891 :
7892 : /** Complete any pending actions, and return the final status.
7893 : * This is typically useful for algorithm that generate an output dataset.
7894 : *
7895 : * Note that this function does *NOT* release memory associated with the
7896 : * algorithm. GDALAlgorithmRelease() must still be called afterwards.
7897 : *
7898 : * @param hAlg Handle to an algorithm. Must NOT be null.
7899 : * @return true if successful, false otherwise
7900 : * @since 3.11
7901 : */
7902 :
7903 987 : bool GDALAlgorithmFinalize(GDALAlgorithmH hAlg)
7904 : {
7905 987 : VALIDATE_POINTER1(hAlg, __func__, false);
7906 987 : return hAlg->ptr->Finalize();
7907 : }
7908 :
7909 : /************************************************************************/
7910 : /* GDALAlgorithmGetUsageAsJSON() */
7911 : /************************************************************************/
7912 :
7913 : /** Return the usage of the algorithm as a JSON-serialized string.
7914 : *
7915 : * This can be used to dynamically generate interfaces to algorithms.
7916 : *
7917 : * @param hAlg Handle to an algorithm. Must NOT be null.
7918 : * @return a string that must be freed with CPLFree()
7919 : * @since 3.11
7920 : */
7921 6 : char *GDALAlgorithmGetUsageAsJSON(GDALAlgorithmH hAlg)
7922 : {
7923 6 : VALIDATE_POINTER1(hAlg, __func__, nullptr);
7924 6 : return CPLStrdup(hAlg->ptr->GetUsageAsJSON().c_str());
7925 : }
7926 :
7927 : /************************************************************************/
7928 : /* GDALAlgorithmGetArgNames() */
7929 : /************************************************************************/
7930 :
7931 : /** Return the list of available argument names.
7932 : *
7933 : * @param hAlg Handle to an algorithm. Must NOT be null.
7934 : * @return a NULL terminated list of names, which must be destroyed with
7935 : * CSLDestroy()
7936 : * @since 3.11
7937 : */
7938 16382 : char **GDALAlgorithmGetArgNames(GDALAlgorithmH hAlg)
7939 : {
7940 16382 : VALIDATE_POINTER1(hAlg, __func__, nullptr);
7941 32764 : CPLStringList list;
7942 365773 : for (const auto &arg : hAlg->ptr->GetArgs())
7943 349391 : list.AddString(arg->GetName().c_str());
7944 16382 : return list.StealList();
7945 : }
7946 :
7947 : /************************************************************************/
7948 : /* GDALAlgorithmGetArg() */
7949 : /************************************************************************/
7950 :
7951 : /** Return an argument from its name.
7952 : *
7953 : * The lifetime of the returned object does not exceed the one of hAlg.
7954 : *
7955 : * @param hAlg Handle to an algorithm. Must NOT be null.
7956 : * @param pszArgName Argument name. Must NOT be null.
7957 : * @return an argument that must be released with GDALAlgorithmArgRelease(),
7958 : * or nullptr in case of error
7959 : * @since 3.11
7960 : */
7961 350475 : GDALAlgorithmArgH GDALAlgorithmGetArg(GDALAlgorithmH hAlg,
7962 : const char *pszArgName)
7963 : {
7964 350475 : VALIDATE_POINTER1(hAlg, __func__, nullptr);
7965 350475 : VALIDATE_POINTER1(pszArgName, __func__, nullptr);
7966 700950 : auto arg = hAlg->ptr->GetArg(pszArgName, /* suggestionAllowed = */ true,
7967 350475 : /* isConst = */ true);
7968 350475 : if (!arg)
7969 3 : return nullptr;
7970 350472 : return std::make_unique<GDALAlgorithmArgHS>(arg).release();
7971 : }
7972 :
7973 : /************************************************************************/
7974 : /* GDALAlgorithmGetArgNonConst() */
7975 : /************************************************************************/
7976 :
7977 : /** Return an argument from its name, possibly allowing creation of user-provided
7978 : * argument if the algorithm allow it.
7979 : *
7980 : * The lifetime of the returned object does not exceed the one of hAlg.
7981 : *
7982 : * @param hAlg Handle to an algorithm. Must NOT be null.
7983 : * @param pszArgName Argument name. Must NOT be null.
7984 : * @return an argument that must be released with GDALAlgorithmArgRelease(),
7985 : * or nullptr in case of error
7986 : * @since 3.12
7987 : */
7988 10680 : GDALAlgorithmArgH GDALAlgorithmGetArgNonConst(GDALAlgorithmH hAlg,
7989 : const char *pszArgName)
7990 : {
7991 10680 : VALIDATE_POINTER1(hAlg, __func__, nullptr);
7992 10680 : VALIDATE_POINTER1(pszArgName, __func__, nullptr);
7993 21360 : auto arg = hAlg->ptr->GetArg(pszArgName, /* suggestionAllowed = */ true,
7994 10680 : /* isConst = */ false);
7995 10680 : if (!arg)
7996 2 : return nullptr;
7997 10678 : return std::make_unique<GDALAlgorithmArgHS>(arg).release();
7998 : }
7999 :
8000 : /************************************************************************/
8001 : /* GDALAlgorithmGetArgDependencies() */
8002 : /************************************************************************/
8003 :
8004 : /** Return the list of argument names the specified argument depends on.
8005 : *
8006 : * This includes both regular dependencies and mutual dependencies.
8007 : *
8008 : * @param hAlg Handle to an algorithm. Must NOT be null.
8009 : * @param pszArgName Argument name. Must NOT be null.
8010 : * @return a NULL terminated list of names, which must be destroyed with
8011 : * CSLDestroy()
8012 : * @since 3.11
8013 : */
8014 7 : char **GDALAlgorithmGetArgDependencies(GDALAlgorithmH hAlg,
8015 : const char *pszArgName)
8016 : {
8017 7 : VALIDATE_POINTER1(hAlg, __func__, nullptr);
8018 7 : VALIDATE_POINTER1(pszArgName, __func__, nullptr);
8019 7 : return CPLStringList(hAlg->ptr->GetArgDependencies(pszArgName)).StealList();
8020 : }
8021 :
8022 : /************************************************************************/
8023 : /* GDALAlgorithmArgRelease() */
8024 : /************************************************************************/
8025 :
8026 : /** Release a handle to an argument.
8027 : *
8028 : * @since 3.11
8029 : */
8030 361150 : void GDALAlgorithmArgRelease(GDALAlgorithmArgH hArg)
8031 : {
8032 361150 : delete hArg;
8033 361150 : }
8034 :
8035 : /************************************************************************/
8036 : /* GDALAlgorithmArgGetName() */
8037 : /************************************************************************/
8038 :
8039 : /** Return the name of an argument.
8040 : *
8041 : * @param hArg Handle to an argument. Must NOT be null.
8042 : * @return argument name whose lifetime is bound to hArg and which must not
8043 : * be freed.
8044 : * @since 3.11
8045 : */
8046 20133 : const char *GDALAlgorithmArgGetName(GDALAlgorithmArgH hArg)
8047 : {
8048 20133 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8049 20133 : return hArg->ptr->GetName().c_str();
8050 : }
8051 :
8052 : /************************************************************************/
8053 : /* GDALAlgorithmArgGetType() */
8054 : /************************************************************************/
8055 :
8056 : /** Get the type of an argument
8057 : *
8058 : * @param hArg Handle to an argument. Must NOT be null.
8059 : * @since 3.11
8060 : */
8061 438668 : GDALAlgorithmArgType GDALAlgorithmArgGetType(GDALAlgorithmArgH hArg)
8062 : {
8063 438668 : VALIDATE_POINTER1(hArg, __func__, GAAT_STRING);
8064 438668 : return hArg->ptr->GetType();
8065 : }
8066 :
8067 : /************************************************************************/
8068 : /* GDALAlgorithmArgGetDescription() */
8069 : /************************************************************************/
8070 :
8071 : /** Return the description of an argument.
8072 : *
8073 : * @param hArg Handle to an argument. Must NOT be null.
8074 : * @return argument description whose lifetime is bound to hArg and which must not
8075 : * be freed.
8076 : * @since 3.11
8077 : */
8078 86880 : const char *GDALAlgorithmArgGetDescription(GDALAlgorithmArgH hArg)
8079 : {
8080 86880 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8081 86880 : return hArg->ptr->GetDescription().c_str();
8082 : }
8083 :
8084 : /************************************************************************/
8085 : /* GDALAlgorithmArgGetShortName() */
8086 : /************************************************************************/
8087 :
8088 : /** Return the short name, or empty string if there is none
8089 : *
8090 : * @param hArg Handle to an argument. Must NOT be null.
8091 : * @return short name whose lifetime is bound to hArg and which must not
8092 : * be freed.
8093 : * @since 3.11
8094 : */
8095 1 : const char *GDALAlgorithmArgGetShortName(GDALAlgorithmArgH hArg)
8096 : {
8097 1 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8098 1 : return hArg->ptr->GetShortName().c_str();
8099 : }
8100 :
8101 : /************************************************************************/
8102 : /* GDALAlgorithmArgGetAliases() */
8103 : /************************************************************************/
8104 :
8105 : /** Return the aliases (potentially none)
8106 : *
8107 : * @param hArg Handle to an argument. Must NOT be null.
8108 : * @return a NULL terminated list of names, which must be destroyed with
8109 : * CSLDestroy()
8110 :
8111 : * @since 3.11
8112 : */
8113 164083 : char **GDALAlgorithmArgGetAliases(GDALAlgorithmArgH hArg)
8114 : {
8115 164083 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8116 164083 : return CPLStringList(hArg->ptr->GetAliases()).StealList();
8117 : }
8118 :
8119 : /************************************************************************/
8120 : /* GDALAlgorithmArgGetMetaVar() */
8121 : /************************************************************************/
8122 :
8123 : /** Return the "meta-var" hint.
8124 : *
8125 : * By default, the meta-var value is the long name of the argument in
8126 : * upper case.
8127 : *
8128 : * @param hArg Handle to an argument. Must NOT be null.
8129 : * @return meta-var hint whose lifetime is bound to hArg and which must not
8130 : * be freed.
8131 : * @since 3.11
8132 : */
8133 1 : const char *GDALAlgorithmArgGetMetaVar(GDALAlgorithmArgH hArg)
8134 : {
8135 1 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8136 1 : return hArg->ptr->GetMetaVar().c_str();
8137 : }
8138 :
8139 : /************************************************************************/
8140 : /* GDALAlgorithmArgGetCategory() */
8141 : /************************************************************************/
8142 :
8143 : /** Return the argument category
8144 : *
8145 : * GAAC_COMMON, GAAC_BASE, GAAC_ADVANCED, GAAC_ESOTERIC or a custom category.
8146 : *
8147 : * @param hArg Handle to an argument. Must NOT be null.
8148 : * @return category whose lifetime is bound to hArg and which must not
8149 : * be freed.
8150 : * @since 3.11
8151 : */
8152 1 : const char *GDALAlgorithmArgGetCategory(GDALAlgorithmArgH hArg)
8153 : {
8154 1 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8155 1 : return hArg->ptr->GetCategory().c_str();
8156 : }
8157 :
8158 : /************************************************************************/
8159 : /* GDALAlgorithmArgIsPositional() */
8160 : /************************************************************************/
8161 :
8162 : /** Return if the argument is a positional one.
8163 : *
8164 : * @param hArg Handle to an argument. Must NOT be null.
8165 : * @since 3.11
8166 : */
8167 1 : bool GDALAlgorithmArgIsPositional(GDALAlgorithmArgH hArg)
8168 : {
8169 1 : VALIDATE_POINTER1(hArg, __func__, false);
8170 1 : return hArg->ptr->IsPositional();
8171 : }
8172 :
8173 : /************************************************************************/
8174 : /* GDALAlgorithmArgIsRequired() */
8175 : /************************************************************************/
8176 :
8177 : /** Return whether the argument is required. Defaults to false.
8178 : *
8179 : * @param hArg Handle to an argument. Must NOT be null.
8180 : * @since 3.11
8181 : */
8182 164083 : bool GDALAlgorithmArgIsRequired(GDALAlgorithmArgH hArg)
8183 : {
8184 164083 : VALIDATE_POINTER1(hArg, __func__, false);
8185 164083 : return hArg->ptr->IsRequired();
8186 : }
8187 :
8188 : /************************************************************************/
8189 : /* GDALAlgorithmArgGetMinCount() */
8190 : /************************************************************************/
8191 :
8192 : /** Return the minimum number of values for the argument.
8193 : *
8194 : * Defaults to 0.
8195 : * Only applies to list type of arguments.
8196 : *
8197 : * @param hArg Handle to an argument. Must NOT be null.
8198 : * @since 3.11
8199 : */
8200 1 : int GDALAlgorithmArgGetMinCount(GDALAlgorithmArgH hArg)
8201 : {
8202 1 : VALIDATE_POINTER1(hArg, __func__, 0);
8203 1 : return hArg->ptr->GetMinCount();
8204 : }
8205 :
8206 : /************************************************************************/
8207 : /* GDALAlgorithmArgGetMaxCount() */
8208 : /************************************************************************/
8209 :
8210 : /** Return the maximum number of values for the argument.
8211 : *
8212 : * Defaults to 1 for scalar types, and INT_MAX for list types.
8213 : * Only applies to list type of arguments.
8214 : *
8215 : * @param hArg Handle to an argument. Must NOT be null.
8216 : * @since 3.11
8217 : */
8218 1 : int GDALAlgorithmArgGetMaxCount(GDALAlgorithmArgH hArg)
8219 : {
8220 1 : VALIDATE_POINTER1(hArg, __func__, 0);
8221 1 : return hArg->ptr->GetMaxCount();
8222 : }
8223 :
8224 : /************************************************************************/
8225 : /* GDALAlgorithmArgGetPackedValuesAllowed() */
8226 : /************************************************************************/
8227 :
8228 : /** Return whether, for list type of arguments, several values, space
8229 : * separated, may be specified. That is "--foo=bar,baz".
8230 : * The default is true.
8231 : *
8232 : * @param hArg Handle to an argument. Must NOT be null.
8233 : * @since 3.11
8234 : */
8235 1 : bool GDALAlgorithmArgGetPackedValuesAllowed(GDALAlgorithmArgH hArg)
8236 : {
8237 1 : VALIDATE_POINTER1(hArg, __func__, false);
8238 1 : return hArg->ptr->GetPackedValuesAllowed();
8239 : }
8240 :
8241 : /************************************************************************/
8242 : /* GDALAlgorithmArgGetRepeatedArgAllowed() */
8243 : /************************************************************************/
8244 :
8245 : /** Return whether, for list type of arguments, the argument may be
8246 : * repeated. That is "--foo=bar --foo=baz".
8247 : * The default is true.
8248 : *
8249 : * @param hArg Handle to an argument. Must NOT be null.
8250 : * @since 3.11
8251 : */
8252 1 : bool GDALAlgorithmArgGetRepeatedArgAllowed(GDALAlgorithmArgH hArg)
8253 : {
8254 1 : VALIDATE_POINTER1(hArg, __func__, false);
8255 1 : return hArg->ptr->GetRepeatedArgAllowed();
8256 : }
8257 :
8258 : /************************************************************************/
8259 : /* GDALAlgorithmArgGetChoices() */
8260 : /************************************************************************/
8261 :
8262 : /** Return the allowed values (as strings) for the argument.
8263 : *
8264 : * Only honored for GAAT_STRING and GAAT_STRING_LIST types.
8265 : *
8266 : * @param hArg Handle to an argument. Must NOT be null.
8267 : * @return a NULL terminated list of names, which must be destroyed with
8268 : * CSLDestroy()
8269 :
8270 : * @since 3.11
8271 : */
8272 1 : char **GDALAlgorithmArgGetChoices(GDALAlgorithmArgH hArg)
8273 : {
8274 1 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8275 1 : return CPLStringList(hArg->ptr->GetChoices()).StealList();
8276 : }
8277 :
8278 : /************************************************************************/
8279 : /* GDALAlgorithmArgGetMetadataItem() */
8280 : /************************************************************************/
8281 :
8282 : /** Return the values of the metadata item of an argument.
8283 : *
8284 : * @param hArg Handle to an argument. Must NOT be null.
8285 : * @param pszItem Name of the item. Must NOT be null.
8286 : * @return a NULL terminated list of values, which must be destroyed with
8287 : * CSLDestroy()
8288 :
8289 : * @since 3.11
8290 : */
8291 79 : char **GDALAlgorithmArgGetMetadataItem(GDALAlgorithmArgH hArg,
8292 : const char *pszItem)
8293 : {
8294 79 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8295 79 : VALIDATE_POINTER1(pszItem, __func__, nullptr);
8296 79 : const auto pVecOfStrings = hArg->ptr->GetMetadataItem(pszItem);
8297 79 : return pVecOfStrings ? CPLStringList(*pVecOfStrings).StealList() : nullptr;
8298 : }
8299 :
8300 : /************************************************************************/
8301 : /* GDALAlgorithmArgIsExplicitlySet() */
8302 : /************************************************************************/
8303 :
8304 : /** Return whether the argument value has been explicitly set with Set()
8305 : *
8306 : * @param hArg Handle to an argument. Must NOT be null.
8307 : * @since 3.11
8308 : */
8309 756 : bool GDALAlgorithmArgIsExplicitlySet(GDALAlgorithmArgH hArg)
8310 : {
8311 756 : VALIDATE_POINTER1(hArg, __func__, false);
8312 756 : return hArg->ptr->IsExplicitlySet();
8313 : }
8314 :
8315 : /************************************************************************/
8316 : /* GDALAlgorithmArgHasDefaultValue() */
8317 : /************************************************************************/
8318 :
8319 : /** Return if the argument has a declared default value.
8320 : *
8321 : * @param hArg Handle to an argument. Must NOT be null.
8322 : * @since 3.11
8323 : */
8324 2 : bool GDALAlgorithmArgHasDefaultValue(GDALAlgorithmArgH hArg)
8325 : {
8326 2 : VALIDATE_POINTER1(hArg, __func__, false);
8327 2 : return hArg->ptr->HasDefaultValue();
8328 : }
8329 :
8330 : /************************************************************************/
8331 : /* GDALAlgorithmArgGetDefaultAsBoolean() */
8332 : /************************************************************************/
8333 :
8334 : /** Return the argument default value as a integer.
8335 : *
8336 : * Must only be called on arguments whose type is GAAT_BOOLEAN
8337 : *
8338 : * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
8339 : * argument has a default value.
8340 : *
8341 : * @param hArg Handle to an argument. Must NOT be null.
8342 : * @since 3.12
8343 : */
8344 3 : bool GDALAlgorithmArgGetDefaultAsBoolean(GDALAlgorithmArgH hArg)
8345 : {
8346 3 : VALIDATE_POINTER1(hArg, __func__, false);
8347 3 : if (hArg->ptr->GetType() != GAAT_BOOLEAN)
8348 : {
8349 1 : CPLError(CE_Failure, CPLE_AppDefined,
8350 : "%s must only be called on arguments of type GAAT_BOOLEAN",
8351 : __func__);
8352 1 : return false;
8353 : }
8354 2 : return hArg->ptr->GetDefault<bool>();
8355 : }
8356 :
8357 : /************************************************************************/
8358 : /* GDALAlgorithmArgGetDefaultAsString() */
8359 : /************************************************************************/
8360 :
8361 : /** Return the argument default value as a string.
8362 : *
8363 : * Must only be called on arguments whose type is GAAT_STRING.
8364 : *
8365 : * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
8366 : * argument has a default value.
8367 : *
8368 : * @param hArg Handle to an argument. Must NOT be null.
8369 : * @return string whose lifetime is bound to hArg and which must not
8370 : * be freed.
8371 : * @since 3.11
8372 : */
8373 3 : const char *GDALAlgorithmArgGetDefaultAsString(GDALAlgorithmArgH hArg)
8374 : {
8375 3 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8376 3 : if (hArg->ptr->GetType() != GAAT_STRING)
8377 : {
8378 2 : CPLError(CE_Failure, CPLE_AppDefined,
8379 : "%s must only be called on arguments of type GAAT_STRING",
8380 : __func__);
8381 2 : return nullptr;
8382 : }
8383 1 : return hArg->ptr->GetDefault<std::string>().c_str();
8384 : }
8385 :
8386 : /************************************************************************/
8387 : /* GDALAlgorithmArgGetDefaultAsInteger() */
8388 : /************************************************************************/
8389 :
8390 : /** Return the argument default value as a integer.
8391 : *
8392 : * Must only be called on arguments whose type is GAAT_INTEGER
8393 : *
8394 : * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
8395 : * argument has a default value.
8396 : *
8397 : * @param hArg Handle to an argument. Must NOT be null.
8398 : * @since 3.12
8399 : */
8400 3 : int GDALAlgorithmArgGetDefaultAsInteger(GDALAlgorithmArgH hArg)
8401 : {
8402 3 : VALIDATE_POINTER1(hArg, __func__, 0);
8403 3 : if (hArg->ptr->GetType() != GAAT_INTEGER)
8404 : {
8405 2 : CPLError(CE_Failure, CPLE_AppDefined,
8406 : "%s must only be called on arguments of type GAAT_INTEGER",
8407 : __func__);
8408 2 : return 0;
8409 : }
8410 1 : return hArg->ptr->GetDefault<int>();
8411 : }
8412 :
8413 : /************************************************************************/
8414 : /* GDALAlgorithmArgGetDefaultAsDouble() */
8415 : /************************************************************************/
8416 :
8417 : /** Return the argument default value as a double.
8418 : *
8419 : * Must only be called on arguments whose type is GAAT_REAL
8420 : *
8421 : * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
8422 : * argument has a default value.
8423 : *
8424 : * @param hArg Handle to an argument. Must NOT be null.
8425 : * @since 3.12
8426 : */
8427 3 : double GDALAlgorithmArgGetDefaultAsDouble(GDALAlgorithmArgH hArg)
8428 : {
8429 3 : VALIDATE_POINTER1(hArg, __func__, 0);
8430 3 : if (hArg->ptr->GetType() != GAAT_REAL)
8431 : {
8432 2 : CPLError(CE_Failure, CPLE_AppDefined,
8433 : "%s must only be called on arguments of type GAAT_REAL",
8434 : __func__);
8435 2 : return 0;
8436 : }
8437 1 : return hArg->ptr->GetDefault<double>();
8438 : }
8439 :
8440 : /************************************************************************/
8441 : /* GDALAlgorithmArgGetDefaultAsStringList() */
8442 : /************************************************************************/
8443 :
8444 : /** Return the argument default value as a string list.
8445 : *
8446 : * Must only be called on arguments whose type is GAAT_STRING_LIST.
8447 : *
8448 : * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
8449 : * argument has a default value.
8450 : *
8451 : * @param hArg Handle to an argument. Must NOT be null.
8452 : * @return a NULL terminated list of names, which must be destroyed with
8453 : * CSLDestroy()
8454 :
8455 : * @since 3.12
8456 : */
8457 3 : char **GDALAlgorithmArgGetDefaultAsStringList(GDALAlgorithmArgH hArg)
8458 : {
8459 3 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8460 3 : if (hArg->ptr->GetType() != GAAT_STRING_LIST)
8461 : {
8462 2 : CPLError(CE_Failure, CPLE_AppDefined,
8463 : "%s must only be called on arguments of type GAAT_STRING_LIST",
8464 : __func__);
8465 2 : return nullptr;
8466 : }
8467 2 : return CPLStringList(hArg->ptr->GetDefault<std::vector<std::string>>())
8468 1 : .StealList();
8469 : }
8470 :
8471 : /************************************************************************/
8472 : /* GDALAlgorithmArgGetDefaultAsIntegerList() */
8473 : /************************************************************************/
8474 :
8475 : /** Return the argument default value as a integer list.
8476 : *
8477 : * Must only be called on arguments whose type is GAAT_INTEGER_LIST.
8478 : *
8479 : * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
8480 : * argument has a default value.
8481 : *
8482 : * @param hArg Handle to an argument. Must NOT be null.
8483 : * @param[out] pnCount Pointer to the number of values in the list. Must NOT be null.
8484 : * @since 3.12
8485 : */
8486 3 : const int *GDALAlgorithmArgGetDefaultAsIntegerList(GDALAlgorithmArgH hArg,
8487 : size_t *pnCount)
8488 : {
8489 3 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8490 3 : VALIDATE_POINTER1(pnCount, __func__, nullptr);
8491 3 : if (hArg->ptr->GetType() != GAAT_INTEGER_LIST)
8492 : {
8493 2 : CPLError(
8494 : CE_Failure, CPLE_AppDefined,
8495 : "%s must only be called on arguments of type GAAT_INTEGER_LIST",
8496 : __func__);
8497 2 : *pnCount = 0;
8498 2 : return nullptr;
8499 : }
8500 1 : const auto &val = hArg->ptr->GetDefault<std::vector<int>>();
8501 1 : *pnCount = val.size();
8502 1 : return val.data();
8503 : }
8504 :
8505 : /************************************************************************/
8506 : /* GDALAlgorithmArgGetDefaultAsDoubleList() */
8507 : /************************************************************************/
8508 :
8509 : /** Return the argument default value as a real list.
8510 : *
8511 : * Must only be called on arguments whose type is GAAT_REAL_LIST.
8512 : *
8513 : * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
8514 : * argument has a default value.
8515 : *
8516 : * @param hArg Handle to an argument. Must NOT be null.
8517 : * @param[out] pnCount Pointer to the number of values in the list. Must NOT be null.
8518 : * @since 3.12
8519 : */
8520 3 : const double *GDALAlgorithmArgGetDefaultAsDoubleList(GDALAlgorithmArgH hArg,
8521 : size_t *pnCount)
8522 : {
8523 3 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8524 3 : VALIDATE_POINTER1(pnCount, __func__, nullptr);
8525 3 : if (hArg->ptr->GetType() != GAAT_REAL_LIST)
8526 : {
8527 2 : CPLError(CE_Failure, CPLE_AppDefined,
8528 : "%s must only be called on arguments of type GAAT_REAL_LIST",
8529 : __func__);
8530 2 : *pnCount = 0;
8531 2 : return nullptr;
8532 : }
8533 1 : const auto &val = hArg->ptr->GetDefault<std::vector<double>>();
8534 1 : *pnCount = val.size();
8535 1 : return val.data();
8536 : }
8537 :
8538 : /************************************************************************/
8539 : /* GDALAlgorithmArgIsHidden() */
8540 : /************************************************************************/
8541 :
8542 : /** Return whether the argument is hidden (for GDAL internal use)
8543 : *
8544 : * This is an alias for GDALAlgorithmArgIsHiddenForCLI() &&
8545 : * GDALAlgorithmArgIsHiddenForAPI().
8546 : *
8547 : * @param hArg Handle to an argument. Must NOT be null.
8548 : * @since 3.12
8549 : */
8550 1 : bool GDALAlgorithmArgIsHidden(GDALAlgorithmArgH hArg)
8551 : {
8552 1 : VALIDATE_POINTER1(hArg, __func__, false);
8553 1 : return hArg->ptr->IsHidden();
8554 : }
8555 :
8556 : /************************************************************************/
8557 : /* GDALAlgorithmArgIsHiddenForCLI() */
8558 : /************************************************************************/
8559 :
8560 : /** Return whether the argument must not be mentioned in CLI usage.
8561 : *
8562 : * For example, "output-value" for "gdal raster info", which is only
8563 : * meant when the algorithm is used from a non-CLI context.
8564 : *
8565 : * @param hArg Handle to an argument. Must NOT be null.
8566 : * @since 3.11
8567 : */
8568 1 : bool GDALAlgorithmArgIsHiddenForCLI(GDALAlgorithmArgH hArg)
8569 : {
8570 1 : VALIDATE_POINTER1(hArg, __func__, false);
8571 1 : return hArg->ptr->IsHiddenForCLI();
8572 : }
8573 :
8574 : /************************************************************************/
8575 : /* GDALAlgorithmArgIsHiddenForAPI() */
8576 : /************************************************************************/
8577 :
8578 : /** Return whether the argument must not be mentioned in the context of an
8579 : * API use.
8580 : * Said otherwise, if it is only for CLI usage.
8581 : *
8582 : * For example "--help"
8583 : *
8584 : * @param hArg Handle to an argument. Must NOT be null.
8585 : * @since 3.12
8586 : */
8587 226403 : bool GDALAlgorithmArgIsHiddenForAPI(GDALAlgorithmArgH hArg)
8588 : {
8589 226403 : VALIDATE_POINTER1(hArg, __func__, false);
8590 226403 : return hArg->ptr->IsHiddenForAPI();
8591 : }
8592 :
8593 : /************************************************************************/
8594 : /* GDALAlgorithmArgIsOnlyForCLI() */
8595 : /************************************************************************/
8596 :
8597 : /** Return whether the argument must not be mentioned in the context of an
8598 : * API use.
8599 : * Said otherwise, if it is only for CLI usage.
8600 : *
8601 : * For example "--help"
8602 : *
8603 : * @param hArg Handle to an argument. Must NOT be null.
8604 : * @since 3.11
8605 : * @deprecated Use GDALAlgorithmArgIsHiddenForAPI() instead.
8606 : */
8607 0 : bool GDALAlgorithmArgIsOnlyForCLI(GDALAlgorithmArgH hArg)
8608 : {
8609 0 : VALIDATE_POINTER1(hArg, __func__, false);
8610 0 : return hArg->ptr->IsHiddenForAPI();
8611 : }
8612 :
8613 : /************************************************************************/
8614 : /* GDALAlgorithmArgIsAvailableInPipelineStep() */
8615 : /************************************************************************/
8616 :
8617 : /** Return whether the argument is available in a pipeline step.
8618 : *
8619 : * If false, it is only available in standalone mode.
8620 : *
8621 : * @param hArg Handle to an argument. Must NOT be null.
8622 : * @since 3.13
8623 : */
8624 2 : bool GDALAlgorithmArgIsAvailableInPipelineStep(GDALAlgorithmArgH hArg)
8625 : {
8626 2 : VALIDATE_POINTER1(hArg, __func__, false);
8627 2 : return hArg->ptr->IsAvailableInPipelineStep();
8628 : }
8629 :
8630 : /************************************************************************/
8631 : /* GDALAlgorithmArgIsInput() */
8632 : /************************************************************************/
8633 :
8634 : /** Indicate whether the value of the argument is read-only during the
8635 : * execution of the algorithm.
8636 : *
8637 : * Default is true.
8638 : *
8639 : * @param hArg Handle to an argument. Must NOT be null.
8640 : * @since 3.11
8641 : */
8642 223615 : bool GDALAlgorithmArgIsInput(GDALAlgorithmArgH hArg)
8643 : {
8644 223615 : VALIDATE_POINTER1(hArg, __func__, false);
8645 223615 : return hArg->ptr->IsInput();
8646 : }
8647 :
8648 : /************************************************************************/
8649 : /* GDALAlgorithmArgIsOutput() */
8650 : /************************************************************************/
8651 :
8652 : /** Return whether (at least part of) the value of the argument is set
8653 : * during the execution of the algorithm.
8654 : *
8655 : * For example, "output-value" for "gdal raster info"
8656 : * Default is false.
8657 : * An argument may return both IsInput() and IsOutput() as true.
8658 : * For example the "gdal raster convert" algorithm consumes the dataset
8659 : * name of its "output" argument, and sets the dataset object during its
8660 : * execution.
8661 : *
8662 : * @param hArg Handle to an argument. Must NOT be null.
8663 : * @since 3.11
8664 : */
8665 125752 : bool GDALAlgorithmArgIsOutput(GDALAlgorithmArgH hArg)
8666 : {
8667 125752 : VALIDATE_POINTER1(hArg, __func__, false);
8668 125752 : return hArg->ptr->IsOutput();
8669 : }
8670 :
8671 : /************************************************************************/
8672 : /* GDALAlgorithmArgGetDatasetType() */
8673 : /************************************************************************/
8674 :
8675 : /** Get which type of dataset is allowed / generated.
8676 : *
8677 : * Binary-or combination of GDAL_OF_RASTER, GDAL_OF_VECTOR and
8678 : * GDAL_OF_MULTIDIM_RASTER.
8679 : * Only applies to arguments of type GAAT_DATASET or GAAT_DATASET_LIST.
8680 : *
8681 : * @param hArg Handle to an argument. Must NOT be null.
8682 : * @since 3.11
8683 : */
8684 2 : GDALArgDatasetType GDALAlgorithmArgGetDatasetType(GDALAlgorithmArgH hArg)
8685 : {
8686 2 : VALIDATE_POINTER1(hArg, __func__, 0);
8687 2 : return hArg->ptr->GetDatasetType();
8688 : }
8689 :
8690 : /************************************************************************/
8691 : /* GDALAlgorithmArgGetDatasetInputFlags() */
8692 : /************************************************************************/
8693 :
8694 : /** Indicates which components among name and dataset are accepted as
8695 : * input, when this argument serves as an input.
8696 : *
8697 : * If the GADV_NAME bit is set, it indicates a dataset name is accepted as
8698 : * input.
8699 : * If the GADV_OBJECT bit is set, it indicates a dataset object is
8700 : * accepted as input.
8701 : * If both bits are set, the algorithm can accept either a name or a dataset
8702 : * object.
8703 : * Only applies to arguments of type GAAT_DATASET or GAAT_DATASET_LIST.
8704 : *
8705 : * @param hArg Handle to an argument. Must NOT be null.
8706 : * @return string whose lifetime is bound to hAlg and which must not
8707 : * be freed.
8708 : * @since 3.11
8709 : */
8710 2 : int GDALAlgorithmArgGetDatasetInputFlags(GDALAlgorithmArgH hArg)
8711 : {
8712 2 : VALIDATE_POINTER1(hArg, __func__, 0);
8713 2 : return hArg->ptr->GetDatasetInputFlags();
8714 : }
8715 :
8716 : /************************************************************************/
8717 : /* GDALAlgorithmArgGetDatasetOutputFlags() */
8718 : /************************************************************************/
8719 :
8720 : /** Indicates which components among name and dataset are modified,
8721 : * when this argument serves as an output.
8722 : *
8723 : * If the GADV_NAME bit is set, it indicates a dataset name is generated as
8724 : * output (that is the algorithm will generate the name. Rarely used).
8725 : * If the GADV_OBJECT bit is set, it indicates a dataset object is
8726 : * generated as output, and available for use after the algorithm has
8727 : * completed.
8728 : * Only applies to arguments of type GAAT_DATASET or GAAT_DATASET_LIST.
8729 : *
8730 : * @param hArg Handle to an argument. Must NOT be null.
8731 : * @return string whose lifetime is bound to hAlg and which must not
8732 : * be freed.
8733 : * @since 3.11
8734 : */
8735 2 : int GDALAlgorithmArgGetDatasetOutputFlags(GDALAlgorithmArgH hArg)
8736 : {
8737 2 : VALIDATE_POINTER1(hArg, __func__, 0);
8738 2 : return hArg->ptr->GetDatasetOutputFlags();
8739 : }
8740 :
8741 : /************************************************************************/
8742 : /* GDALAlgorithmArgGetMutualExclusionGroup() */
8743 : /************************************************************************/
8744 :
8745 : /** Return the name of the mutual exclusion group to which this argument
8746 : * belongs to.
8747 : *
8748 : * Or empty string if it does not belong to any exclusion group.
8749 : *
8750 : * @param hArg Handle to an argument. Must NOT be null.
8751 : * @return string whose lifetime is bound to hArg and which must not
8752 : * be freed.
8753 : * @since 3.11
8754 : */
8755 1 : const char *GDALAlgorithmArgGetMutualExclusionGroup(GDALAlgorithmArgH hArg)
8756 : {
8757 1 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8758 1 : return hArg->ptr->GetMutualExclusionGroup().c_str();
8759 : }
8760 :
8761 : /************************************************************************/
8762 : /* GDALAlgorithmArgGetMutualDependencyGroup() */
8763 : /************************************************************************/
8764 :
8765 : /** Return the name of the mutual dependency group to which this argument
8766 : * belongs to.
8767 : *
8768 : * Or empty string if it does not belong to any dependency group.
8769 : *
8770 : * @param hArg Handle to an argument. Must NOT be null.
8771 : * @return string whose lifetime is bound to hArg and which must not
8772 : * be freed.
8773 : * @since 3.13
8774 : */
8775 5 : const char *GDALAlgorithmArgGetMutualDependencyGroup(GDALAlgorithmArgH hArg)
8776 : {
8777 5 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8778 5 : return hArg->ptr->GetMutualDependencyGroup().c_str();
8779 : }
8780 :
8781 : /************************************************************************/
8782 : /* GDALAlgorithmArgGetDirectDependencies() */
8783 : /************************************************************************/
8784 :
8785 : /** Return the list of names of arguments that this argument depends on.
8786 : *
8787 : * This is not necessarily a symmetric relationship.
8788 : * If argument A depends on argument B, it doesn't mean that B depends on A.
8789 : * Mutual dependency groups are a special case of dependencies,
8790 : * where all arguments of the group depend on each other and are not
8791 : * returned by this method.
8792 : *
8793 : * @param hArg Handle to an argument. Must NOT be null.
8794 : * @return a NULL terminated list of names, which must be destroyed with
8795 : * CSLDestroy()
8796 : * @since 3.13
8797 : */
8798 7 : char **GDALAlgorithmArgGetDirectDependencies(GDALAlgorithmArgH hArg)
8799 : {
8800 7 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8801 7 : return CPLStringList(hArg->ptr->GetDirectDependencies()).StealList();
8802 : }
8803 :
8804 : /************************************************************************/
8805 : /* GDALAlgorithmArgGetAsBoolean() */
8806 : /************************************************************************/
8807 :
8808 : /** Return the argument value as a boolean.
8809 : *
8810 : * Must only be called on arguments whose type is GAAT_BOOLEAN.
8811 : *
8812 : * @param hArg Handle to an argument. Must NOT be null.
8813 : * @since 3.11
8814 : */
8815 8 : bool GDALAlgorithmArgGetAsBoolean(GDALAlgorithmArgH hArg)
8816 : {
8817 8 : VALIDATE_POINTER1(hArg, __func__, false);
8818 8 : if (hArg->ptr->GetType() != GAAT_BOOLEAN)
8819 : {
8820 1 : CPLError(CE_Failure, CPLE_AppDefined,
8821 : "%s must only be called on arguments of type GAAT_BOOLEAN",
8822 : __func__);
8823 1 : return false;
8824 : }
8825 7 : return hArg->ptr->Get<bool>();
8826 : }
8827 :
8828 : /************************************************************************/
8829 : /* GDALAlgorithmArgGetAsString() */
8830 : /************************************************************************/
8831 :
8832 : /** Return the argument value as a string.
8833 : *
8834 : * Must only be called on arguments whose type is GAAT_STRING.
8835 : *
8836 : * @param hArg Handle to an argument. Must NOT be null.
8837 : * @return string whose lifetime is bound to hArg and which must not
8838 : * be freed.
8839 : * @since 3.11
8840 : */
8841 378 : const char *GDALAlgorithmArgGetAsString(GDALAlgorithmArgH hArg)
8842 : {
8843 378 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8844 378 : if (hArg->ptr->GetType() != GAAT_STRING)
8845 : {
8846 1 : CPLError(CE_Failure, CPLE_AppDefined,
8847 : "%s must only be called on arguments of type GAAT_STRING",
8848 : __func__);
8849 1 : return nullptr;
8850 : }
8851 377 : return hArg->ptr->Get<std::string>().c_str();
8852 : }
8853 :
8854 : /************************************************************************/
8855 : /* GDALAlgorithmArgGetAsDatasetValue() */
8856 : /************************************************************************/
8857 :
8858 : /** Return the argument value as a GDALArgDatasetValueH.
8859 : *
8860 : * Must only be called on arguments whose type is GAAT_DATASET
8861 : *
8862 : * @param hArg Handle to an argument. Must NOT be null.
8863 : * @return handle to a GDALArgDatasetValue that must be released with
8864 : * GDALArgDatasetValueRelease(). The lifetime of that handle does not exceed
8865 : * the one of hArg.
8866 : * @since 3.11
8867 : */
8868 3413 : GDALArgDatasetValueH GDALAlgorithmArgGetAsDatasetValue(GDALAlgorithmArgH hArg)
8869 : {
8870 3413 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8871 3413 : if (hArg->ptr->GetType() != GAAT_DATASET)
8872 : {
8873 1 : CPLError(CE_Failure, CPLE_AppDefined,
8874 : "%s must only be called on arguments of type GAAT_DATASET",
8875 : __func__);
8876 1 : return nullptr;
8877 : }
8878 3412 : return std::make_unique<GDALArgDatasetValueHS>(
8879 6824 : &(hArg->ptr->Get<GDALArgDatasetValue>()))
8880 3412 : .release();
8881 : }
8882 :
8883 : /************************************************************************/
8884 : /* GDALAlgorithmArgGetAsInteger() */
8885 : /************************************************************************/
8886 :
8887 : /** Return the argument value as a integer.
8888 : *
8889 : * Must only be called on arguments whose type is GAAT_INTEGER
8890 : *
8891 : * @param hArg Handle to an argument. Must NOT be null.
8892 : * @since 3.11
8893 : */
8894 26 : int GDALAlgorithmArgGetAsInteger(GDALAlgorithmArgH hArg)
8895 : {
8896 26 : VALIDATE_POINTER1(hArg, __func__, 0);
8897 26 : if (hArg->ptr->GetType() != GAAT_INTEGER)
8898 : {
8899 1 : CPLError(CE_Failure, CPLE_AppDefined,
8900 : "%s must only be called on arguments of type GAAT_INTEGER",
8901 : __func__);
8902 1 : return 0;
8903 : }
8904 25 : return hArg->ptr->Get<int>();
8905 : }
8906 :
8907 : /************************************************************************/
8908 : /* GDALAlgorithmArgGetAsDouble() */
8909 : /************************************************************************/
8910 :
8911 : /** Return the argument value as a double.
8912 : *
8913 : * Must only be called on arguments whose type is GAAT_REAL
8914 : *
8915 : * @param hArg Handle to an argument. Must NOT be null.
8916 : * @since 3.11
8917 : */
8918 8 : double GDALAlgorithmArgGetAsDouble(GDALAlgorithmArgH hArg)
8919 : {
8920 8 : VALIDATE_POINTER1(hArg, __func__, 0);
8921 8 : if (hArg->ptr->GetType() != GAAT_REAL)
8922 : {
8923 1 : CPLError(CE_Failure, CPLE_AppDefined,
8924 : "%s must only be called on arguments of type GAAT_REAL",
8925 : __func__);
8926 1 : return 0;
8927 : }
8928 7 : return hArg->ptr->Get<double>();
8929 : }
8930 :
8931 : /************************************************************************/
8932 : /* GDALAlgorithmArgGetAsStringList() */
8933 : /************************************************************************/
8934 :
8935 : /** Return the argument value as a string list.
8936 : *
8937 : * Must only be called on arguments whose type is GAAT_STRING_LIST.
8938 : *
8939 : * @param hArg Handle to an argument. Must NOT be null.
8940 : * @return a NULL terminated list of names, which must be destroyed with
8941 : * CSLDestroy()
8942 :
8943 : * @since 3.11
8944 : */
8945 4 : char **GDALAlgorithmArgGetAsStringList(GDALAlgorithmArgH hArg)
8946 : {
8947 4 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8948 4 : if (hArg->ptr->GetType() != GAAT_STRING_LIST)
8949 : {
8950 1 : CPLError(CE_Failure, CPLE_AppDefined,
8951 : "%s must only be called on arguments of type GAAT_STRING_LIST",
8952 : __func__);
8953 1 : return nullptr;
8954 : }
8955 6 : return CPLStringList(hArg->ptr->Get<std::vector<std::string>>())
8956 3 : .StealList();
8957 : }
8958 :
8959 : /************************************************************************/
8960 : /* GDALAlgorithmArgGetAsIntegerList() */
8961 : /************************************************************************/
8962 :
8963 : /** Return the argument value as a integer list.
8964 : *
8965 : * Must only be called on arguments whose type is GAAT_INTEGER_LIST.
8966 : *
8967 : * @param hArg Handle to an argument. Must NOT be null.
8968 : * @param[out] pnCount Pointer to the number of values in the list. Must NOT be null.
8969 : * @since 3.11
8970 : */
8971 8 : const int *GDALAlgorithmArgGetAsIntegerList(GDALAlgorithmArgH hArg,
8972 : size_t *pnCount)
8973 : {
8974 8 : VALIDATE_POINTER1(hArg, __func__, nullptr);
8975 8 : VALIDATE_POINTER1(pnCount, __func__, nullptr);
8976 8 : if (hArg->ptr->GetType() != GAAT_INTEGER_LIST)
8977 : {
8978 1 : CPLError(
8979 : CE_Failure, CPLE_AppDefined,
8980 : "%s must only be called on arguments of type GAAT_INTEGER_LIST",
8981 : __func__);
8982 1 : *pnCount = 0;
8983 1 : return nullptr;
8984 : }
8985 7 : const auto &val = hArg->ptr->Get<std::vector<int>>();
8986 7 : *pnCount = val.size();
8987 7 : return val.data();
8988 : }
8989 :
8990 : /************************************************************************/
8991 : /* GDALAlgorithmArgGetAsDoubleList() */
8992 : /************************************************************************/
8993 :
8994 : /** Return the argument value as a real list.
8995 : *
8996 : * Must only be called on arguments whose type is GAAT_REAL_LIST.
8997 : *
8998 : * @param hArg Handle to an argument. Must NOT be null.
8999 : * @param[out] pnCount Pointer to the number of values in the list. Must NOT be null.
9000 : * @since 3.11
9001 : */
9002 8 : const double *GDALAlgorithmArgGetAsDoubleList(GDALAlgorithmArgH hArg,
9003 : size_t *pnCount)
9004 : {
9005 8 : VALIDATE_POINTER1(hArg, __func__, nullptr);
9006 8 : VALIDATE_POINTER1(pnCount, __func__, nullptr);
9007 8 : if (hArg->ptr->GetType() != GAAT_REAL_LIST)
9008 : {
9009 1 : CPLError(CE_Failure, CPLE_AppDefined,
9010 : "%s must only be called on arguments of type GAAT_REAL_LIST",
9011 : __func__);
9012 1 : *pnCount = 0;
9013 1 : return nullptr;
9014 : }
9015 7 : const auto &val = hArg->ptr->Get<std::vector<double>>();
9016 7 : *pnCount = val.size();
9017 7 : return val.data();
9018 : }
9019 :
9020 : /************************************************************************/
9021 : /* GDALAlgorithmArgSetAsBoolean() */
9022 : /************************************************************************/
9023 :
9024 : /** Set the value for a GAAT_BOOLEAN argument.
9025 : *
9026 : * It cannot be called several times for a given argument.
9027 : * Validation checks and other actions are run.
9028 : *
9029 : * @param hArg Handle to an argument. Must NOT be null.
9030 : * @param value value.
9031 : * @return true if success.
9032 : * @since 3.11
9033 : */
9034 :
9035 757 : bool GDALAlgorithmArgSetAsBoolean(GDALAlgorithmArgH hArg, bool value)
9036 : {
9037 757 : VALIDATE_POINTER1(hArg, __func__, false);
9038 757 : return hArg->ptr->Set(value);
9039 : }
9040 :
9041 : /************************************************************************/
9042 : /* GDALAlgorithmArgSetAsString() */
9043 : /************************************************************************/
9044 :
9045 : /** Set the value for a GAAT_STRING argument.
9046 : *
9047 : * It cannot be called several times for a given argument.
9048 : * Validation checks and other actions are run.
9049 : *
9050 : * @param hArg Handle to an argument. Must NOT be null.
9051 : * @param value value (may be null)
9052 : * @return true if success.
9053 : * @since 3.11
9054 : */
9055 :
9056 3411 : bool GDALAlgorithmArgSetAsString(GDALAlgorithmArgH hArg, const char *value)
9057 : {
9058 3411 : VALIDATE_POINTER1(hArg, __func__, false);
9059 3411 : return hArg->ptr->Set(value ? value : "");
9060 : }
9061 :
9062 : /************************************************************************/
9063 : /* GDALAlgorithmArgSetAsInteger() */
9064 : /************************************************************************/
9065 :
9066 : /** Set the value for a GAAT_INTEGER (or GAAT_REAL) argument.
9067 : *
9068 : * It cannot be called several times for a given argument.
9069 : * Validation checks and other actions are run.
9070 : *
9071 : * @param hArg Handle to an argument. Must NOT be null.
9072 : * @param value value.
9073 : * @return true if success.
9074 : * @since 3.11
9075 : */
9076 :
9077 489 : bool GDALAlgorithmArgSetAsInteger(GDALAlgorithmArgH hArg, int value)
9078 : {
9079 489 : VALIDATE_POINTER1(hArg, __func__, false);
9080 489 : return hArg->ptr->Set(value);
9081 : }
9082 :
9083 : /************************************************************************/
9084 : /* GDALAlgorithmArgSetAsDouble() */
9085 : /************************************************************************/
9086 :
9087 : /** Set the value for a GAAT_REAL argument.
9088 : *
9089 : * It cannot be called several times for a given argument.
9090 : * Validation checks and other actions are run.
9091 : *
9092 : * @param hArg Handle to an argument. Must NOT be null.
9093 : * @param value value.
9094 : * @return true if success.
9095 : * @since 3.11
9096 : */
9097 :
9098 263 : bool GDALAlgorithmArgSetAsDouble(GDALAlgorithmArgH hArg, double value)
9099 : {
9100 263 : VALIDATE_POINTER1(hArg, __func__, false);
9101 263 : return hArg->ptr->Set(value);
9102 : }
9103 :
9104 : /************************************************************************/
9105 : /* GDALAlgorithmArgSetAsDatasetValue() */
9106 : /************************************************************************/
9107 :
9108 : /** Set the value for a GAAT_DATASET argument.
9109 : *
9110 : * It cannot be called several times for a given argument.
9111 : * Validation checks and other actions are run.
9112 : *
9113 : * @param hArg Handle to an argument. Must NOT be null.
9114 : * @param value Handle to a GDALArgDatasetValue. Must NOT be null.
9115 : * @return true if success.
9116 : * @since 3.11
9117 : */
9118 2 : bool GDALAlgorithmArgSetAsDatasetValue(GDALAlgorithmArgH hArg,
9119 : GDALArgDatasetValueH value)
9120 : {
9121 2 : VALIDATE_POINTER1(hArg, __func__, false);
9122 2 : VALIDATE_POINTER1(value, __func__, false);
9123 2 : return hArg->ptr->SetFrom(*(value->ptr));
9124 : }
9125 :
9126 : /************************************************************************/
9127 : /* GDALAlgorithmArgSetDataset() */
9128 : /************************************************************************/
9129 :
9130 : /** Set dataset object, increasing its reference counter.
9131 : *
9132 : * @param hArg Handle to an argument. Must NOT be null.
9133 : * @param hDS Dataset object. May be null.
9134 : * @return true if success.
9135 : * @since 3.11
9136 : */
9137 :
9138 2 : bool GDALAlgorithmArgSetDataset(GDALAlgorithmArgH hArg, GDALDatasetH hDS)
9139 : {
9140 2 : VALIDATE_POINTER1(hArg, __func__, false);
9141 2 : return hArg->ptr->Set(GDALDataset::FromHandle(hDS));
9142 : }
9143 :
9144 : /************************************************************************/
9145 : /* GDALAlgorithmArgSetAsStringList() */
9146 : /************************************************************************/
9147 :
9148 : /** Set the value for a GAAT_STRING_LIST argument.
9149 : *
9150 : * It cannot be called several times for a given argument.
9151 : * Validation checks and other actions are run.
9152 : *
9153 : * @param hArg Handle to an argument. Must NOT be null.
9154 : * @param value value as a NULL terminated list (may be null)
9155 : * @return true if success.
9156 : * @since 3.11
9157 : */
9158 :
9159 967 : bool GDALAlgorithmArgSetAsStringList(GDALAlgorithmArgH hArg, CSLConstList value)
9160 : {
9161 967 : VALIDATE_POINTER1(hArg, __func__, false);
9162 967 : return hArg->ptr->Set(
9163 1934 : static_cast<std::vector<std::string>>(CPLStringList(value)));
9164 : }
9165 :
9166 : /************************************************************************/
9167 : /* GDALAlgorithmArgSetAsIntegerList() */
9168 : /************************************************************************/
9169 :
9170 : /** Set the value for a GAAT_INTEGER_LIST argument.
9171 : *
9172 : * It cannot be called several times for a given argument.
9173 : * Validation checks and other actions are run.
9174 : *
9175 : * @param hArg Handle to an argument. Must NOT be null.
9176 : * @param nCount Number of values in pnValues.
9177 : * @param pnValues Pointer to an array of integer values of size nCount.
9178 : * @return true if success.
9179 : * @since 3.11
9180 : */
9181 65 : bool GDALAlgorithmArgSetAsIntegerList(GDALAlgorithmArgH hArg, size_t nCount,
9182 : const int *pnValues)
9183 : {
9184 65 : VALIDATE_POINTER1(hArg, __func__, false);
9185 65 : return hArg->ptr->Set(std::vector<int>(pnValues, pnValues + nCount));
9186 : }
9187 :
9188 : /************************************************************************/
9189 : /* GDALAlgorithmArgSetAsDoubleList() */
9190 : /************************************************************************/
9191 :
9192 : /** Set the value for a GAAT_REAL_LIST argument.
9193 : *
9194 : * It cannot be called several times for a given argument.
9195 : * Validation checks and other actions are run.
9196 : *
9197 : * @param hArg Handle to an argument. Must NOT be null.
9198 : * @param nCount Number of values in pnValues.
9199 : * @param pnValues Pointer to an array of double values of size nCount.
9200 : * @return true if success.
9201 : * @since 3.11
9202 : */
9203 240 : bool GDALAlgorithmArgSetAsDoubleList(GDALAlgorithmArgH hArg, size_t nCount,
9204 : const double *pnValues)
9205 : {
9206 240 : VALIDATE_POINTER1(hArg, __func__, false);
9207 240 : return hArg->ptr->Set(std::vector<double>(pnValues, pnValues + nCount));
9208 : }
9209 :
9210 : /************************************************************************/
9211 : /* GDALAlgorithmArgSetDatasets() */
9212 : /************************************************************************/
9213 :
9214 : /** Set dataset objects to a GAAT_DATASET_LIST argument, increasing their reference counter.
9215 : *
9216 : * @param hArg Handle to an argument. Must NOT be null.
9217 : * @param nCount Number of values in pnValues.
9218 : * @param pahDS Pointer to an array of dataset of size nCount.
9219 : * @return true if success.
9220 : * @since 3.11
9221 : */
9222 :
9223 1408 : bool GDALAlgorithmArgSetDatasets(GDALAlgorithmArgH hArg, size_t nCount,
9224 : GDALDatasetH *pahDS)
9225 : {
9226 1408 : VALIDATE_POINTER1(hArg, __func__, false);
9227 2816 : std::vector<GDALArgDatasetValue> values;
9228 2842 : for (size_t i = 0; i < nCount; ++i)
9229 : {
9230 1434 : values.emplace_back(GDALDataset::FromHandle(pahDS[i]));
9231 : }
9232 1408 : return hArg->ptr->Set(std::move(values));
9233 : }
9234 :
9235 : /************************************************************************/
9236 : /* GDALAlgorithmArgSetDatasetNames() */
9237 : /************************************************************************/
9238 :
9239 : /** Set dataset names to a GAAT_DATASET_LIST argument.
9240 : *
9241 : * @param hArg Handle to an argument. Must NOT be null.
9242 : * @param names Dataset names as a NULL terminated list (may be null)
9243 : * @return true if success.
9244 : * @since 3.11
9245 : */
9246 :
9247 825 : bool GDALAlgorithmArgSetDatasetNames(GDALAlgorithmArgH hArg, CSLConstList names)
9248 : {
9249 825 : VALIDATE_POINTER1(hArg, __func__, false);
9250 1650 : std::vector<GDALArgDatasetValue> values;
9251 1723 : for (size_t i = 0; names[i]; ++i)
9252 : {
9253 898 : values.emplace_back(names[i]);
9254 : }
9255 825 : return hArg->ptr->Set(std::move(values));
9256 : }
9257 :
9258 : /************************************************************************/
9259 : /* GDALArgDatasetValueCreate() */
9260 : /************************************************************************/
9261 :
9262 : /** Instantiate an empty GDALArgDatasetValue
9263 : *
9264 : * @return new handle to free with GDALArgDatasetValueRelease()
9265 : * @since 3.11
9266 : */
9267 1 : GDALArgDatasetValueH GDALArgDatasetValueCreate()
9268 : {
9269 1 : return std::make_unique<GDALArgDatasetValueHS>().release();
9270 : }
9271 :
9272 : /************************************************************************/
9273 : /* GDALArgDatasetValueRelease() */
9274 : /************************************************************************/
9275 :
9276 : /** Release a handle to a GDALArgDatasetValue
9277 : *
9278 : * @since 3.11
9279 : */
9280 3413 : void GDALArgDatasetValueRelease(GDALArgDatasetValueH hValue)
9281 : {
9282 3413 : delete hValue;
9283 3413 : }
9284 :
9285 : /************************************************************************/
9286 : /* GDALArgDatasetValueGetName() */
9287 : /************************************************************************/
9288 :
9289 : /** Return the name component of the GDALArgDatasetValue
9290 : *
9291 : * @param hValue Handle to a GDALArgDatasetValue. Must NOT be null.
9292 : * @return string whose lifetime is bound to hAlg and which must not
9293 : * be freed.
9294 : * @since 3.11
9295 : */
9296 1 : const char *GDALArgDatasetValueGetName(GDALArgDatasetValueH hValue)
9297 : {
9298 1 : VALIDATE_POINTER1(hValue, __func__, nullptr);
9299 1 : return hValue->ptr->GetName().c_str();
9300 : }
9301 :
9302 : /************************************************************************/
9303 : /* GDALArgDatasetValueGetDatasetRef() */
9304 : /************************************************************************/
9305 :
9306 : /** Return the dataset component of the GDALArgDatasetValue.
9307 : *
9308 : * This does not modify the reference counter, hence the lifetime of the
9309 : * returned object is not guaranteed to exceed the one of hValue.
9310 : *
9311 : * @param hValue Handle to a GDALArgDatasetValue. Must NOT be null.
9312 : * @since 3.11
9313 : */
9314 3 : GDALDatasetH GDALArgDatasetValueGetDatasetRef(GDALArgDatasetValueH hValue)
9315 : {
9316 3 : VALIDATE_POINTER1(hValue, __func__, nullptr);
9317 3 : return GDALDataset::ToHandle(hValue->ptr->GetDatasetRef());
9318 : }
9319 :
9320 : /************************************************************************/
9321 : /* GDALArgDatasetValueGetDatasetIncreaseRefCount() */
9322 : /************************************************************************/
9323 :
9324 : /** Return the dataset component of the GDALArgDatasetValue, and increase its
9325 : * reference count if not null. Once done with the dataset, the caller should
9326 : * call GDALReleaseDataset().
9327 : *
9328 : * @param hValue Handle to a GDALArgDatasetValue. Must NOT be null.
9329 : * @since 3.11
9330 : */
9331 : GDALDatasetH
9332 1162 : GDALArgDatasetValueGetDatasetIncreaseRefCount(GDALArgDatasetValueH hValue)
9333 : {
9334 1162 : VALIDATE_POINTER1(hValue, __func__, nullptr);
9335 1162 : return GDALDataset::ToHandle(hValue->ptr->GetDatasetIncreaseRefCount());
9336 : }
9337 :
9338 : /************************************************************************/
9339 : /* GDALArgDatasetValueSetName() */
9340 : /************************************************************************/
9341 :
9342 : /** Set dataset name
9343 : *
9344 : * @param hValue Handle to a GDALArgDatasetValue. Must NOT be null.
9345 : * @param pszName Dataset name. May be null.
9346 : * @since 3.11
9347 : */
9348 :
9349 1482 : void GDALArgDatasetValueSetName(GDALArgDatasetValueH hValue,
9350 : const char *pszName)
9351 : {
9352 1482 : VALIDATE_POINTER0(hValue, __func__);
9353 1482 : hValue->ptr->Set(pszName ? pszName : "");
9354 : }
9355 :
9356 : /************************************************************************/
9357 : /* GDALArgDatasetValueSetDataset() */
9358 : /************************************************************************/
9359 :
9360 : /** Set dataset object, increasing its reference counter.
9361 : *
9362 : * @param hValue Handle to a GDALArgDatasetValue. Must NOT be null.
9363 : * @param hDS Dataset object. May be null.
9364 : * @since 3.11
9365 : */
9366 :
9367 754 : void GDALArgDatasetValueSetDataset(GDALArgDatasetValueH hValue,
9368 : GDALDatasetH hDS)
9369 : {
9370 754 : VALIDATE_POINTER0(hValue, __func__);
9371 754 : hValue->ptr->Set(GDALDataset::FromHandle(hDS));
9372 : }
|