Coverage Report

Created: 2026-07-25 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/gcore/gdalalgorithm.cpp
Line
Count
Source
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
0
#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
0
    explicit GDALAlgorithmArgHS(GDALAlgorithmArg *arg) : ptr(arg)
60
0
    {
61
0
    }
62
};
63
64
//! @endcond
65
66
//! @cond Doxygen_Suppress
67
struct GDALArgDatasetValueHS
68
{
69
    GDALArgDatasetValue val{};
70
    GDALArgDatasetValue *ptr = nullptr;
71
72
0
    GDALArgDatasetValueHS() : ptr(&val)
73
0
    {
74
0
    }
75
76
0
    explicit GDALArgDatasetValueHS(GDALArgDatasetValue *arg) : ptr(arg)
77
0
    {
78
0
    }
79
80
    GDALArgDatasetValueHS(const GDALArgDatasetValueHS &) = delete;
81
    GDALArgDatasetValueHS &operator=(const GDALArgDatasetValueHS &) = delete;
82
};
83
84
//! @endcond
85
86
/************************************************************************/
87
/*                     GDALAlgorithmArgTypeIsList()                     */
88
/************************************************************************/
89
90
bool GDALAlgorithmArgTypeIsList(GDALAlgorithmArgType type)
91
0
{
92
0
    switch (type)
93
0
    {
94
0
        case GAAT_BOOLEAN:
95
0
        case GAAT_STRING:
96
0
        case GAAT_INTEGER:
97
0
        case GAAT_REAL:
98
0
        case GAAT_DATASET:
99
0
            break;
100
101
0
        case GAAT_STRING_LIST:
102
0
        case GAAT_INTEGER_LIST:
103
0
        case GAAT_REAL_LIST:
104
0
        case GAAT_DATASET_LIST:
105
0
            return true;
106
0
    }
107
108
0
    return false;
109
0
}
110
111
/************************************************************************/
112
/*                      GDALAlgorithmArgTypeName()                      */
113
/************************************************************************/
114
115
const char *GDALAlgorithmArgTypeName(GDALAlgorithmArgType type)
116
0
{
117
0
    switch (type)
118
0
    {
119
0
        case GAAT_BOOLEAN:
120
0
            break;
121
0
        case GAAT_STRING:
122
0
            return "string";
123
0
        case GAAT_INTEGER:
124
0
            return "integer";
125
0
        case GAAT_REAL:
126
0
            return "real";
127
0
        case GAAT_DATASET:
128
0
            return "dataset";
129
0
        case GAAT_STRING_LIST:
130
0
            return "string_list";
131
0
        case GAAT_INTEGER_LIST:
132
0
            return "integer_list";
133
0
        case GAAT_REAL_LIST:
134
0
            return "real_list";
135
0
        case GAAT_DATASET_LIST:
136
0
            return "dataset_list";
137
0
    }
138
139
0
    return "boolean";
140
0
}
141
142
/************************************************************************/
143
/*                  GDALAlgorithmArgDatasetTypeName()                   */
144
/************************************************************************/
145
146
std::string GDALAlgorithmArgDatasetTypeName(GDALArgDatasetType type)
147
0
{
148
0
    std::string ret;
149
0
    if ((type & GDAL_OF_RASTER) != 0)
150
0
        ret = "raster";
151
0
    if ((type & GDAL_OF_VECTOR) != 0)
152
0
    {
153
0
        if (!ret.empty())
154
0
        {
155
0
            if ((type & GDAL_OF_MULTIDIM_RASTER) != 0)
156
0
                ret += ", ";
157
0
            else
158
0
                ret += " or ";
159
0
        }
160
0
        ret += "vector";
161
0
    }
162
0
    if ((type & GDAL_OF_MULTIDIM_RASTER) != 0)
163
0
    {
164
0
        if (!ret.empty())
165
0
        {
166
0
            ret += " or ";
167
0
        }
168
0
        ret += "multidimensional raster";
169
0
    }
170
0
    return ret;
171
0
}
172
173
/************************************************************************/
174
/*                        GDALAlgorithmArgDecl()                        */
175
/************************************************************************/
176
177
// cppcheck-suppress uninitMemberVar
178
GDALAlgorithmArgDecl::GDALAlgorithmArgDecl(const std::string &longName,
179
                                           char chShortName,
180
                                           const std::string &description,
181
                                           GDALAlgorithmArgType type)
182
0
    : m_longName(longName),
183
0
      m_shortName(chShortName ? std::string(&chShortName, 1) : std::string()),
184
0
      m_description(description), m_type(type),
185
0
      m_metaVar(CPLString(m_type == GAAT_BOOLEAN ? std::string() : longName)
186
0
                    .toupper()),
187
0
      m_maxCount(GDALAlgorithmArgTypeIsList(type) ? UNBOUNDED : 1)
188
0
{
189
0
    if (m_type == GAAT_BOOLEAN)
190
0
    {
191
0
        m_defaultValue = false;
192
0
    }
193
0
}
194
195
/************************************************************************/
196
/*                 GDALAlgorithmArgDecl::SetMinCount()                  */
197
/************************************************************************/
198
199
GDALAlgorithmArgDecl &GDALAlgorithmArgDecl::SetMinCount(int count)
200
0
{
201
0
    if (!GDALAlgorithmArgTypeIsList(m_type))
202
0
    {
203
0
        CPLError(CE_Failure, CPLE_NotSupported,
204
0
                 "SetMinCount() illegal on scalar argument '%s'",
205
0
                 GetName().c_str());
206
0
    }
207
0
    else
208
0
    {
209
0
        m_minCount = count;
210
0
    }
211
0
    return *this;
212
0
}
213
214
/************************************************************************/
215
/*                 GDALAlgorithmArgDecl::SetMaxCount()                  */
216
/************************************************************************/
217
218
GDALAlgorithmArgDecl &GDALAlgorithmArgDecl::SetMaxCount(int count)
219
0
{
220
0
    if (!GDALAlgorithmArgTypeIsList(m_type))
221
0
    {
222
0
        CPLError(CE_Failure, CPLE_NotSupported,
223
0
                 "SetMaxCount() illegal on scalar argument '%s'",
224
0
                 GetName().c_str());
225
0
    }
226
0
    else
227
0
    {
228
0
        m_maxCount = count;
229
0
    }
230
0
    return *this;
231
0
}
232
233
/************************************************************************/
234
/*                GDALAlgorithmArg::~GDALAlgorithmArg()                 */
235
/************************************************************************/
236
237
0
GDALAlgorithmArg::~GDALAlgorithmArg() = default;
238
239
/************************************************************************/
240
/*                       GDALAlgorithmArg::Set()                        */
241
/************************************************************************/
242
243
bool GDALAlgorithmArg::Set(bool value)
244
0
{
245
0
    if (m_decl.GetType() != GAAT_BOOLEAN)
246
0
    {
247
0
        CPLError(
248
0
            CE_Failure, CPLE_AppDefined,
249
0
            "Calling Set(bool) on argument '%s' of type %s is not supported",
250
0
            GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
251
0
        return false;
252
0
    }
253
0
    return SetInternal(value);
254
0
}
255
256
bool GDALAlgorithmArg::ProcessString(std::string &value) const
257
0
{
258
0
    if (m_decl.IsReadFromFileAtSyntaxAllowed() && !value.empty() &&
259
0
        value.front() == '@')
260
0
    {
261
0
        GByte *pabyData = nullptr;
262
0
        if (VSIIngestFile(nullptr, value.c_str() + 1, &pabyData, nullptr,
263
0
                          10 * 1024 * 1024))
264
0
        {
265
            // Remove UTF-8 BOM
266
0
            size_t offset = 0;
267
0
            if (pabyData[0] == 0xEF && pabyData[1] == 0xBB &&
268
0
                pabyData[2] == 0xBF)
269
0
            {
270
0
                offset = 3;
271
0
            }
272
0
            value = reinterpret_cast<const char *>(pabyData + offset);
273
0
            VSIFree(pabyData);
274
0
        }
275
0
        else
276
0
        {
277
0
            return false;
278
0
        }
279
0
    }
280
281
0
    if (m_decl.IsRemoveSQLCommentsEnabled())
282
0
        value = CPLRemoveSQLComments(value);
283
284
0
    return true;
285
0
}
286
287
bool GDALAlgorithmArg::Set(const std::string &value)
288
0
{
289
0
    switch (m_decl.GetType())
290
0
    {
291
0
        case GAAT_BOOLEAN:
292
0
            if (EQUAL(value.c_str(), "1") || EQUAL(value.c_str(), "TRUE") ||
293
0
                EQUAL(value.c_str(), "YES") || EQUAL(value.c_str(), "ON"))
294
0
            {
295
0
                return Set(true);
296
0
            }
297
0
            else if (EQUAL(value.c_str(), "0") ||
298
0
                     EQUAL(value.c_str(), "FALSE") ||
299
0
                     EQUAL(value.c_str(), "NO") || EQUAL(value.c_str(), "OFF"))
300
0
            {
301
0
                return Set(false);
302
0
            }
303
0
            break;
304
305
0
        case GAAT_INTEGER:
306
0
        case GAAT_INTEGER_LIST:
307
0
        {
308
0
            errno = 0;
309
0
            char *endptr = nullptr;
310
0
            const auto v = std::strtoll(value.c_str(), &endptr, 10);
311
0
            if (errno == 0 && v >= INT_MIN && v <= INT_MAX &&
312
0
                endptr == value.c_str() + value.size())
313
0
            {
314
0
                if (m_decl.GetType() == GAAT_INTEGER)
315
0
                    return Set(static_cast<int>(v));
316
0
                else
317
0
                    return Set(std::vector<int>{static_cast<int>(v)});
318
0
            }
319
0
            break;
320
0
        }
321
322
0
        case GAAT_REAL:
323
0
        case GAAT_REAL_LIST:
324
0
        {
325
0
            char *endptr = nullptr;
326
0
            const double v = CPLStrtod(value.c_str(), &endptr);
327
0
            if (endptr == value.c_str() + value.size())
328
0
            {
329
0
                if (m_decl.GetType() == GAAT_REAL)
330
0
                    return Set(v);
331
0
                else
332
0
                    return Set(std::vector<double>{v});
333
0
            }
334
0
            break;
335
0
        }
336
337
0
        case GAAT_STRING:
338
0
            break;
339
340
0
        case GAAT_STRING_LIST:
341
0
            return Set(std::vector<std::string>{value});
342
343
0
        case GAAT_DATASET:
344
0
            return SetDatasetName(value);
345
346
0
        case GAAT_DATASET_LIST:
347
0
        {
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
0
        }
353
0
    }
354
355
0
    if (m_decl.GetType() != GAAT_STRING)
356
0
    {
357
0
        CPLError(CE_Failure, CPLE_AppDefined,
358
0
                 "Calling Set(std::string) on argument '%s' of type %s is not "
359
0
                 "supported",
360
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
361
0
        return false;
362
0
    }
363
364
0
    std::string newValue(value);
365
0
    return ProcessString(newValue) && SetInternal(newValue);
366
0
}
367
368
bool GDALAlgorithmArg::Set(int value)
369
0
{
370
0
    if (m_decl.GetType() == GAAT_BOOLEAN)
371
0
    {
372
0
        if (value == 1)
373
0
            return Set(true);
374
0
        else if (value == 0)
375
0
            return Set(false);
376
0
    }
377
0
    else if (m_decl.GetType() == GAAT_REAL)
378
0
    {
379
0
        return Set(static_cast<double>(value));
380
0
    }
381
0
    else if (m_decl.GetType() == GAAT_STRING)
382
0
    {
383
0
        return Set(std::to_string(value));
384
0
    }
385
0
    else if (m_decl.GetType() == GAAT_INTEGER_LIST)
386
0
    {
387
0
        return Set(std::vector<int>{value});
388
0
    }
389
0
    else if (m_decl.GetType() == GAAT_REAL_LIST)
390
0
    {
391
0
        return Set(std::vector<double>{static_cast<double>(value)});
392
0
    }
393
0
    else if (m_decl.GetType() == GAAT_STRING_LIST)
394
0
    {
395
0
        return Set(std::vector<std::string>{std::to_string(value)});
396
0
    }
397
398
0
    if (m_decl.GetType() != GAAT_INTEGER)
399
0
    {
400
0
        CPLError(
401
0
            CE_Failure, CPLE_AppDefined,
402
0
            "Calling Set(int) on argument '%s' of type %s is not supported",
403
0
            GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
404
0
        return false;
405
0
    }
406
0
    return SetInternal(value);
407
0
}
408
409
bool GDALAlgorithmArg::Set(double value)
410
0
{
411
0
    if (m_decl.GetType() == GAAT_INTEGER && value >= INT_MIN &&
412
0
        value <= INT_MAX && static_cast<int>(value) == value)
413
0
    {
414
0
        return Set(static_cast<int>(value));
415
0
    }
416
0
    else if (m_decl.GetType() == GAAT_STRING)
417
0
    {
418
0
        return Set(std::to_string(value));
419
0
    }
420
0
    else if (m_decl.GetType() == GAAT_INTEGER_LIST && value >= INT_MIN &&
421
0
             value <= INT_MAX && static_cast<int>(value) == value)
422
0
    {
423
0
        return Set(std::vector<int>{static_cast<int>(value)});
424
0
    }
425
0
    else if (m_decl.GetType() == GAAT_REAL_LIST)
426
0
    {
427
0
        return Set(std::vector<double>{value});
428
0
    }
429
0
    else if (m_decl.GetType() == GAAT_STRING_LIST)
430
0
    {
431
0
        return Set(std::vector<std::string>{std::to_string(value)});
432
0
    }
433
0
    else if (m_decl.GetType() != GAAT_REAL)
434
0
    {
435
0
        CPLError(
436
0
            CE_Failure, CPLE_AppDefined,
437
0
            "Calling Set(double) on argument '%s' of type %s is not supported",
438
0
            GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
439
0
        return false;
440
0
    }
441
0
    return SetInternal(value);
442
0
}
443
444
static bool CheckCanSetDatasetObject(const GDALAlgorithmArg *arg)
445
0
{
446
0
    if (arg->IsOutput() && arg->GetDatasetInputFlags() == GADV_NAME &&
447
0
        arg->GetDatasetOutputFlags() == GADV_OBJECT)
448
0
    {
449
0
        CPLError(
450
0
            CE_Failure, CPLE_AppDefined,
451
0
            "Dataset object '%s' is created by algorithm and cannot be set "
452
0
            "as an input.",
453
0
            arg->GetName().c_str());
454
0
        return false;
455
0
    }
456
0
    else if ((arg->GetDatasetInputFlags() & GADV_OBJECT) == 0)
457
0
    {
458
0
        CPLError(CE_Failure, CPLE_AppDefined,
459
0
                 "Dataset%s '%s' must be provided by name, not as object.",
460
0
                 arg->GetMaxCount() > 1 ? "s" : "", arg->GetName().c_str());
461
0
        return false;
462
0
    }
463
464
0
    return true;
465
0
}
466
467
bool GDALAlgorithmArg::Set(GDALDataset *ds)
468
0
{
469
0
    if (m_decl.GetType() != GAAT_DATASET &&
470
0
        m_decl.GetType() != GAAT_DATASET_LIST)
471
0
    {
472
0
        CPLError(CE_Failure, CPLE_AppDefined,
473
0
                 "Calling Set(GDALDataset*, bool) on argument '%s' of type %s "
474
0
                 "is not supported",
475
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
476
0
        return false;
477
0
    }
478
0
    if (!CheckCanSetDatasetObject(this))
479
0
        return false;
480
0
    m_explicitlySet = true;
481
0
    if (m_decl.GetType() == GAAT_DATASET)
482
0
    {
483
0
        auto &val = *std::get<GDALArgDatasetValue *>(m_value);
484
0
        val.Set(ds);
485
0
    }
486
0
    else
487
0
    {
488
0
        CPLAssert(m_decl.GetType() == GAAT_DATASET_LIST);
489
0
        auto &val = *std::get<std::vector<GDALArgDatasetValue> *>(m_value);
490
0
        val.resize(1);
491
0
        val[0].Set(ds);
492
0
    }
493
0
    return RunAllActions();
494
0
}
495
496
bool GDALAlgorithmArg::Set(std::unique_ptr<GDALDataset> ds)
497
0
{
498
0
    if (m_decl.GetType() != GAAT_DATASET)
499
0
    {
500
0
        CPLError(CE_Failure, CPLE_AppDefined,
501
0
                 "Calling Set(GDALDataset*, bool) on argument '%s' of type %s "
502
0
                 "is not supported",
503
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
504
0
        return false;
505
0
    }
506
0
    if (!CheckCanSetDatasetObject(this))
507
0
        return false;
508
0
    m_explicitlySet = true;
509
0
    auto &val = *std::get<GDALArgDatasetValue *>(m_value);
510
0
    val.Set(std::move(ds));
511
0
    return RunAllActions();
512
0
}
513
514
bool GDALAlgorithmArg::SetDatasetName(const std::string &name)
515
0
{
516
0
    if (m_decl.GetType() != GAAT_DATASET)
517
0
    {
518
0
        CPLError(CE_Failure, CPLE_AppDefined,
519
0
                 "Calling SetDatasetName() on argument '%s' of type %s is "
520
0
                 "not supported",
521
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
522
0
        return false;
523
0
    }
524
0
    m_explicitlySet = true;
525
0
    std::get<GDALArgDatasetValue *>(m_value)->Set(name);
526
0
    return RunAllActions();
527
0
}
528
529
bool GDALAlgorithmArg::SetFrom(const GDALArgDatasetValue &other)
530
0
{
531
0
    if (m_decl.GetType() != GAAT_DATASET)
532
0
    {
533
0
        CPLError(CE_Failure, CPLE_AppDefined,
534
0
                 "Calling SetFrom() on argument '%s' of type %s is "
535
0
                 "not supported",
536
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
537
0
        return false;
538
0
    }
539
0
    if (other.GetDatasetRef() && !CheckCanSetDatasetObject(this))
540
0
        return false;
541
0
    m_explicitlySet = true;
542
0
    std::get<GDALArgDatasetValue *>(m_value)->SetFrom(other);
543
0
    return RunAllActions();
544
0
}
545
546
bool GDALAlgorithmArg::Set(const std::vector<std::string> &value)
547
0
{
548
0
    if (m_decl.GetType() == GAAT_INTEGER_LIST)
549
0
    {
550
0
        std::vector<int> v_i;
551
0
        for (const std::string &s : value)
552
0
        {
553
0
            errno = 0;
554
0
            char *endptr = nullptr;
555
0
            const auto v = std::strtoll(s.c_str(), &endptr, 10);
556
0
            if (errno == 0 && v >= INT_MIN && v <= INT_MAX &&
557
0
                endptr == s.c_str() + s.size())
558
0
            {
559
0
                v_i.push_back(static_cast<int>(v));
560
0
            }
561
0
            else
562
0
            {
563
0
                break;
564
0
            }
565
0
        }
566
0
        if (v_i.size() == value.size())
567
0
            return Set(v_i);
568
0
    }
569
0
    else if (m_decl.GetType() == GAAT_REAL_LIST)
570
0
    {
571
0
        std::vector<double> v_d;
572
0
        for (const std::string &s : value)
573
0
        {
574
0
            char *endptr = nullptr;
575
0
            const double v = CPLStrtod(s.c_str(), &endptr);
576
0
            if (endptr == s.c_str() + s.size())
577
0
            {
578
0
                v_d.push_back(v);
579
0
            }
580
0
            else
581
0
            {
582
0
                break;
583
0
            }
584
0
        }
585
0
        if (v_d.size() == value.size())
586
0
            return Set(v_d);
587
0
    }
588
0
    else if ((m_decl.GetType() == GAAT_INTEGER ||
589
0
              m_decl.GetType() == GAAT_REAL ||
590
0
              m_decl.GetType() == GAAT_STRING) &&
591
0
             value.size() == 1)
592
0
    {
593
0
        return Set(value[0]);
594
0
    }
595
0
    else if (m_decl.GetType() == GAAT_DATASET_LIST)
596
0
    {
597
0
        std::vector<GDALArgDatasetValue> dsVector;
598
0
        for (const std::string &s : value)
599
0
            dsVector.emplace_back(s);
600
0
        return Set(std::move(dsVector));
601
0
    }
602
603
0
    if (m_decl.GetType() != GAAT_STRING_LIST)
604
0
    {
605
0
        CPLError(CE_Failure, CPLE_AppDefined,
606
0
                 "Calling Set(const std::vector<std::string> &) on argument "
607
0
                 "'%s' of type %s is not supported",
608
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
609
0
        return false;
610
0
    }
611
612
0
    if (m_decl.IsReadFromFileAtSyntaxAllowed() ||
613
0
        m_decl.IsRemoveSQLCommentsEnabled())
614
0
    {
615
0
        std::vector<std::string> newValue(value);
616
0
        for (auto &s : newValue)
617
0
        {
618
0
            if (!ProcessString(s))
619
0
                return false;
620
0
        }
621
0
        return SetInternal(newValue);
622
0
    }
623
0
    else
624
0
    {
625
0
        return SetInternal(value);
626
0
    }
627
0
}
628
629
bool GDALAlgorithmArg::Set(const std::vector<int> &value)
630
0
{
631
0
    if (m_decl.GetType() == GAAT_REAL_LIST)
632
0
    {
633
0
        std::vector<double> v_d;
634
0
        for (int i : value)
635
0
            v_d.push_back(i);
636
0
        return Set(v_d);
637
0
    }
638
0
    else if (m_decl.GetType() == GAAT_STRING_LIST)
639
0
    {
640
0
        std::vector<std::string> v_s;
641
0
        for (int i : value)
642
0
            v_s.push_back(std::to_string(i));
643
0
        return Set(v_s);
644
0
    }
645
0
    else if ((m_decl.GetType() == GAAT_INTEGER ||
646
0
              m_decl.GetType() == GAAT_REAL ||
647
0
              m_decl.GetType() == GAAT_STRING) &&
648
0
             value.size() == 1)
649
0
    {
650
0
        return Set(value[0]);
651
0
    }
652
653
0
    if (m_decl.GetType() != GAAT_INTEGER_LIST)
654
0
    {
655
0
        CPLError(CE_Failure, CPLE_AppDefined,
656
0
                 "Calling Set(const std::vector<int> &) on argument '%s' of "
657
0
                 "type %s is not supported",
658
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
659
0
        return false;
660
0
    }
661
0
    return SetInternal(value);
662
0
}
663
664
bool GDALAlgorithmArg::Set(const std::vector<double> &value)
665
0
{
666
0
    if (m_decl.GetType() == GAAT_INTEGER_LIST)
667
0
    {
668
0
        std::vector<int> v_i;
669
0
        for (double d : value)
670
0
        {
671
0
            if (d >= INT_MIN && d <= INT_MAX && static_cast<int>(d) == d)
672
0
            {
673
0
                v_i.push_back(static_cast<int>(d));
674
0
            }
675
0
            else
676
0
            {
677
0
                break;
678
0
            }
679
0
        }
680
0
        if (v_i.size() == value.size())
681
0
            return Set(v_i);
682
0
    }
683
0
    else if (m_decl.GetType() == GAAT_STRING_LIST)
684
0
    {
685
0
        std::vector<std::string> v_s;
686
0
        for (double d : value)
687
0
            v_s.push_back(std::to_string(d));
688
0
        return Set(v_s);
689
0
    }
690
0
    else if ((m_decl.GetType() == GAAT_INTEGER ||
691
0
              m_decl.GetType() == GAAT_REAL ||
692
0
              m_decl.GetType() == GAAT_STRING) &&
693
0
             value.size() == 1)
694
0
    {
695
0
        return Set(value[0]);
696
0
    }
697
698
0
    if (m_decl.GetType() != GAAT_REAL_LIST)
699
0
    {
700
0
        CPLError(CE_Failure, CPLE_AppDefined,
701
0
                 "Calling Set(const std::vector<double> &) on argument '%s' of "
702
0
                 "type %s is not supported",
703
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
704
0
        return false;
705
0
    }
706
0
    return SetInternal(value);
707
0
}
708
709
bool GDALAlgorithmArg::Set(std::vector<GDALArgDatasetValue> &&value)
710
0
{
711
0
    if (m_decl.GetType() != GAAT_DATASET_LIST)
712
0
    {
713
0
        CPLError(CE_Failure, CPLE_AppDefined,
714
0
                 "Calling Set(const std::vector<GDALArgDatasetValue> &&) on "
715
0
                 "argument '%s' of type %s is not supported",
716
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
717
0
        return false;
718
0
    }
719
0
    m_explicitlySet = true;
720
0
    *std::get<std::vector<GDALArgDatasetValue> *>(m_value) = std::move(value);
721
0
    return RunAllActions();
722
0
}
723
724
GDALAlgorithmArg &
725
GDALAlgorithmArg::operator=(std::unique_ptr<GDALDataset> value)
726
0
{
727
0
    Set(std::move(value));
728
0
    return *this;
729
0
}
730
731
bool GDALAlgorithmArg::Set(const OGRSpatialReference &value)
732
0
{
733
0
    const char *const apszOptions[] = {"FORMAT=WKT2_2019", nullptr};
734
0
    return Set(value.exportToWkt(apszOptions));
735
0
}
736
737
bool GDALAlgorithmArg::SetFrom(const GDALAlgorithmArg &other)
738
0
{
739
0
    if (m_decl.GetType() != other.GetType())
740
0
    {
741
0
        CPLError(CE_Failure, CPLE_AppDefined,
742
0
                 "Calling SetFrom() on argument '%s' of type %s whereas "
743
0
                 "other argument type is %s is not supported",
744
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()),
745
0
                 GDALAlgorithmArgTypeName(other.GetType()));
746
0
        return false;
747
0
    }
748
749
0
    switch (m_decl.GetType())
750
0
    {
751
0
        case GAAT_BOOLEAN:
752
0
            *std::get<bool *>(m_value) = *std::get<bool *>(other.m_value);
753
0
            break;
754
0
        case GAAT_STRING:
755
0
            *std::get<std::string *>(m_value) =
756
0
                *std::get<std::string *>(other.m_value);
757
0
            break;
758
0
        case GAAT_INTEGER:
759
0
            *std::get<int *>(m_value) = *std::get<int *>(other.m_value);
760
0
            break;
761
0
        case GAAT_REAL:
762
0
            *std::get<double *>(m_value) = *std::get<double *>(other.m_value);
763
0
            break;
764
0
        case GAAT_DATASET:
765
0
            return SetFrom(other.Get<GDALArgDatasetValue>());
766
0
        case GAAT_STRING_LIST:
767
0
            *std::get<std::vector<std::string> *>(m_value) =
768
0
                *std::get<std::vector<std::string> *>(other.m_value);
769
0
            break;
770
0
        case GAAT_INTEGER_LIST:
771
0
            *std::get<std::vector<int> *>(m_value) =
772
0
                *std::get<std::vector<int> *>(other.m_value);
773
0
            break;
774
0
        case GAAT_REAL_LIST:
775
0
            *std::get<std::vector<double> *>(m_value) =
776
0
                *std::get<std::vector<double> *>(other.m_value);
777
0
            break;
778
0
        case GAAT_DATASET_LIST:
779
0
        {
780
0
            std::get<std::vector<GDALArgDatasetValue> *>(m_value)->clear();
781
0
            for (const auto &val :
782
0
                 *std::get<std::vector<GDALArgDatasetValue> *>(other.m_value))
783
0
            {
784
0
                GDALArgDatasetValue v;
785
0
                v.SetFrom(val);
786
0
                std::get<std::vector<GDALArgDatasetValue> *>(m_value)
787
0
                    ->push_back(std::move(v));
788
0
            }
789
0
            break;
790
0
        }
791
0
    }
792
0
    m_explicitlySet = true;
793
0
    return RunAllActions();
794
0
}
795
796
/************************************************************************/
797
/*                  GDALAlgorithmArg::RunAllActions()                   */
798
/************************************************************************/
799
800
bool GDALAlgorithmArg::RunAllActions()
801
0
{
802
0
    if (!RunValidationActions())
803
0
        return false;
804
0
    RunActions();
805
0
    return true;
806
0
}
807
808
/************************************************************************/
809
/*                    GDALAlgorithmArg::RunActions()                    */
810
/************************************************************************/
811
812
void GDALAlgorithmArg::RunActions()
813
0
{
814
0
    for (const auto &f : m_actions)
815
0
        f();
816
0
}
817
818
/************************************************************************/
819
/*                  GDALAlgorithmArg::ValidateChoice()                  */
820
/************************************************************************/
821
822
// Returns the canonical value if matching a valid choice, or empty string
823
// otherwise.
824
std::string GDALAlgorithmArg::ValidateChoice(const std::string &value) const
825
0
{
826
0
    for (const std::string &choice : GetChoices())
827
0
    {
828
0
        if (EQUAL(value.c_str(), choice.c_str()))
829
0
        {
830
0
            return choice;
831
0
        }
832
0
    }
833
834
0
    for (const std::string &choice : GetHiddenChoices())
835
0
    {
836
0
        if (EQUAL(value.c_str(), choice.c_str()))
837
0
        {
838
0
            return choice;
839
0
        }
840
0
    }
841
842
0
    std::string expected;
843
0
    for (const auto &choice : GetChoices())
844
0
    {
845
0
        if (!expected.empty())
846
0
            expected += ", ";
847
0
        expected += '\'';
848
0
        expected += choice;
849
0
        expected += '\'';
850
0
    }
851
0
    if (m_owner && m_owner->IsCalledFromCommandLine() && value == "?")
852
0
    {
853
0
        return "?";
854
0
    }
855
0
    CPLError(CE_Failure, CPLE_IllegalArg,
856
0
             "Invalid value '%s' for string argument '%s'. Should be "
857
0
             "one among %s.",
858
0
             value.c_str(), GetName().c_str(), expected.c_str());
859
0
    return std::string();
860
0
}
861
862
/************************************************************************/
863
/*                 GDALAlgorithmArg::ValidateIntRange()                 */
864
/************************************************************************/
865
866
bool GDALAlgorithmArg::ValidateIntRange(int val) const
867
0
{
868
0
    bool ret = true;
869
870
0
    const auto [minVal, minValIsIncluded] = GetMinValue();
871
0
    if (!std::isnan(minVal))
872
0
    {
873
0
        if (minValIsIncluded && val < minVal)
874
0
        {
875
0
            CPLError(CE_Failure, CPLE_IllegalArg,
876
0
                     "Value of argument '%s' is %d, but should be >= %d",
877
0
                     GetName().c_str(), val, static_cast<int>(minVal));
878
0
            ret = false;
879
0
        }
880
0
        else if (!minValIsIncluded && val <= minVal)
881
0
        {
882
0
            CPLError(CE_Failure, CPLE_IllegalArg,
883
0
                     "Value of argument '%s' is %d, but should be > %d",
884
0
                     GetName().c_str(), val, static_cast<int>(minVal));
885
0
            ret = false;
886
0
        }
887
0
    }
888
889
0
    const auto [maxVal, maxValIsIncluded] = GetMaxValue();
890
0
    if (!std::isnan(maxVal))
891
0
    {
892
893
0
        if (maxValIsIncluded && val > maxVal)
894
0
        {
895
0
            CPLError(CE_Failure, CPLE_IllegalArg,
896
0
                     "Value of argument '%s' is %d, but should be <= %d",
897
0
                     GetName().c_str(), val, static_cast<int>(maxVal));
898
0
            ret = false;
899
0
        }
900
0
        else if (!maxValIsIncluded && val >= maxVal)
901
0
        {
902
0
            CPLError(CE_Failure, CPLE_IllegalArg,
903
0
                     "Value of argument '%s' is %d, but should be < %d",
904
0
                     GetName().c_str(), val, static_cast<int>(maxVal));
905
0
            ret = false;
906
0
        }
907
0
    }
908
909
0
    return ret;
910
0
}
911
912
/************************************************************************/
913
/*                GDALAlgorithmArg::ValidateRealRange()                 */
914
/************************************************************************/
915
916
bool GDALAlgorithmArg::ValidateRealRange(double val) const
917
0
{
918
0
    bool ret = true;
919
920
0
    const auto [minVal, minValIsIncluded] = GetMinValue();
921
0
    if (!std::isnan(minVal))
922
0
    {
923
0
        if (minValIsIncluded && !(val >= minVal))
924
0
        {
925
0
            CPLError(CE_Failure, CPLE_IllegalArg,
926
0
                     "Value of argument '%s' is %g, but should be >= %g",
927
0
                     GetName().c_str(), val, minVal);
928
0
            ret = false;
929
0
        }
930
0
        else if (!minValIsIncluded && !(val > minVal))
931
0
        {
932
0
            CPLError(CE_Failure, CPLE_IllegalArg,
933
0
                     "Value of argument '%s' is %g, but should be > %g",
934
0
                     GetName().c_str(), val, minVal);
935
0
            ret = false;
936
0
        }
937
0
    }
938
939
0
    const auto [maxVal, maxValIsIncluded] = GetMaxValue();
940
0
    if (!std::isnan(maxVal))
941
0
    {
942
943
0
        if (maxValIsIncluded && !(val <= maxVal))
944
0
        {
945
0
            CPLError(CE_Failure, CPLE_IllegalArg,
946
0
                     "Value of argument '%s' is %g, but should be <= %g",
947
0
                     GetName().c_str(), val, maxVal);
948
0
            ret = false;
949
0
        }
950
0
        else if (!maxValIsIncluded && !(val < maxVal))
951
0
        {
952
0
            CPLError(CE_Failure, CPLE_IllegalArg,
953
0
                     "Value of argument '%s' is %g, but should be < %g",
954
0
                     GetName().c_str(), val, maxVal);
955
0
            ret = false;
956
0
        }
957
0
    }
958
959
0
    return ret;
960
0
}
961
962
/************************************************************************/
963
/*                        CheckDuplicateValues()                        */
964
/************************************************************************/
965
966
template <class T>
967
static bool CheckDuplicateValues(const GDALAlgorithmArg *arg,
968
                                 const std::vector<T> &values)
969
0
{
970
0
    auto tmpValues = values;
971
0
    bool bHasDupValues = false;
972
    if constexpr (std::is_floating_point_v<T>)
973
0
    {
974
        // Avoid undefined behavior with NaN values
975
0
        std::sort(tmpValues.begin(), tmpValues.end(),
976
0
                  [](T a, T b)
977
0
                  {
978
0
                      if (std::isnan(a) && !std::isnan(b))
979
0
                          return true;
980
0
                      if (std::isnan(b))
981
0
                          return false;
982
0
                      return a < b;
983
0
                  });
984
985
0
        bHasDupValues =
986
0
            std::adjacent_find(tmpValues.begin(), tmpValues.end(),
987
0
                               [](T a, T b)
988
0
                               {
989
0
                                   if (std::isnan(a) && std::isnan(b))
990
0
                                       return true;
991
0
                                   return a == b;
992
0
                               }) != tmpValues.end();
993
    }
994
    else
995
0
    {
996
0
        std::sort(tmpValues.begin(), tmpValues.end());
997
0
        bHasDupValues = std::adjacent_find(tmpValues.begin(),
998
0
                                           tmpValues.end()) != tmpValues.end();
999
0
    }
1000
0
    if (bHasDupValues)
1001
0
    {
1002
0
        CPLError(CE_Failure, CPLE_AppDefined,
1003
0
                 "'%s' must be a list of unique values.",
1004
0
                 arg->GetName().c_str());
1005
0
        return false;
1006
0
    }
1007
0
    return true;
1008
0
}
Unexecuted instantiation: gdalalgorithm.cpp:bool CheckDuplicateValues<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(GDALAlgorithmArg const*, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&)
Unexecuted instantiation: gdalalgorithm.cpp:bool CheckDuplicateValues<int>(GDALAlgorithmArg const*, std::__1::vector<int, std::__1::allocator<int> > const&)
Unexecuted instantiation: gdalalgorithm.cpp:bool CheckDuplicateValues<double>(GDALAlgorithmArg const*, std::__1::vector<double, std::__1::allocator<double> > const&)
1009
1010
/************************************************************************/
1011
/*               GDALAlgorithmArg::RunValidationActions()               */
1012
/************************************************************************/
1013
1014
bool GDALAlgorithmArg::RunValidationActions()
1015
0
{
1016
0
    bool ret = true;
1017
1018
0
    if (GetType() == GAAT_STRING && !GetChoices().empty())
1019
0
    {
1020
0
        auto &val = Get<std::string>();
1021
0
        std::string validVal = ValidateChoice(val);
1022
0
        if (validVal.empty())
1023
0
            ret = false;
1024
0
        else
1025
0
            val = std::move(validVal);
1026
0
    }
1027
0
    else if (GetType() == GAAT_STRING_LIST && !GetChoices().empty())
1028
0
    {
1029
0
        auto &values = Get<std::vector<std::string>>();
1030
0
        for (std::string &val : values)
1031
0
        {
1032
0
            std::string validVal = ValidateChoice(val);
1033
0
            if (validVal.empty())
1034
0
                ret = false;
1035
0
            else
1036
0
                val = std::move(validVal);
1037
0
        }
1038
0
    }
1039
1040
0
    const auto CheckMinCharCount =
1041
0
        [this, &ret](const std::string &val, int nMinCharCount)
1042
0
    {
1043
0
        if (val.size() < static_cast<size_t>(nMinCharCount))
1044
0
        {
1045
0
            CPLError(CE_Failure, CPLE_IllegalArg,
1046
0
                     "Value of argument '%s' is '%s', but should have at least "
1047
0
                     "%d character%s",
1048
0
                     GetName().c_str(), val.c_str(), nMinCharCount,
1049
0
                     nMinCharCount > 1 ? "s" : "");
1050
0
            ret = false;
1051
0
        }
1052
0
    };
1053
1054
0
    const auto CheckMaxCharCount =
1055
0
        [this, &ret](const std::string &val, int nMaxCharCount)
1056
0
    {
1057
0
        if (val.size() > static_cast<size_t>(nMaxCharCount))
1058
0
        {
1059
0
            CPLError(
1060
0
                CE_Failure, CPLE_IllegalArg,
1061
0
                "Value of argument '%s' is '%s', but should have no more than "
1062
0
                "%d character%s",
1063
0
                GetName().c_str(), val.c_str(), nMaxCharCount,
1064
0
                nMaxCharCount > 1 ? "s" : "");
1065
0
            ret = false;
1066
0
        }
1067
0
    };
1068
1069
0
    switch (GetType())
1070
0
    {
1071
0
        case GAAT_BOOLEAN:
1072
0
            break;
1073
1074
0
        case GAAT_STRING:
1075
0
        {
1076
0
            const auto &val = Get<std::string>();
1077
0
            const int nMinCharCount = GetMinCharCount();
1078
0
            if (nMinCharCount > 0)
1079
0
            {
1080
0
                CheckMinCharCount(val, nMinCharCount);
1081
0
            }
1082
1083
0
            const int nMaxCharCount = GetMaxCharCount();
1084
0
            CheckMaxCharCount(val, nMaxCharCount);
1085
0
            break;
1086
0
        }
1087
1088
0
        case GAAT_STRING_LIST:
1089
0
        {
1090
0
            const int nMinCharCount = GetMinCharCount();
1091
0
            const int nMaxCharCount = GetMaxCharCount();
1092
0
            const auto &values = Get<std::vector<std::string>>();
1093
0
            for (const auto &val : values)
1094
0
            {
1095
0
                if (nMinCharCount > 0)
1096
0
                    CheckMinCharCount(val, nMinCharCount);
1097
0
                CheckMaxCharCount(val, nMaxCharCount);
1098
0
            }
1099
1100
0
            if (!GetDuplicateValuesAllowed() &&
1101
0
                !CheckDuplicateValues(this, values))
1102
0
                ret = false;
1103
0
            break;
1104
0
        }
1105
1106
0
        case GAAT_INTEGER:
1107
0
        {
1108
0
            ret = ValidateIntRange(Get<int>()) && ret;
1109
0
            break;
1110
0
        }
1111
1112
0
        case GAAT_INTEGER_LIST:
1113
0
        {
1114
0
            const auto &values = Get<std::vector<int>>();
1115
0
            for (int v : values)
1116
0
                ret = ValidateIntRange(v) && ret;
1117
1118
0
            if (!GetDuplicateValuesAllowed() &&
1119
0
                !CheckDuplicateValues(this, values))
1120
0
                ret = false;
1121
0
            break;
1122
0
        }
1123
1124
0
        case GAAT_REAL:
1125
0
        {
1126
0
            ret = ValidateRealRange(Get<double>()) && ret;
1127
0
            break;
1128
0
        }
1129
1130
0
        case GAAT_REAL_LIST:
1131
0
        {
1132
0
            const auto &values = Get<std::vector<double>>();
1133
0
            for (double v : values)
1134
0
                ret = ValidateRealRange(v) && ret;
1135
1136
0
            if (!GetDuplicateValuesAllowed() &&
1137
0
                !CheckDuplicateValues(this, values))
1138
0
                ret = false;
1139
0
            break;
1140
0
        }
1141
1142
0
        case GAAT_DATASET:
1143
0
            break;
1144
1145
0
        case GAAT_DATASET_LIST:
1146
0
        {
1147
0
            if (!GetDuplicateValuesAllowed())
1148
0
            {
1149
0
                const auto &values = Get<std::vector<GDALArgDatasetValue>>();
1150
0
                std::vector<std::string> aosValues;
1151
0
                for (const auto &v : values)
1152
0
                {
1153
0
                    const GDALDataset *poDS = v.GetDatasetRef();
1154
0
                    if (poDS)
1155
0
                    {
1156
0
                        auto poDriver = poDS->GetDriver();
1157
                        // The dataset name for a MEM driver is not relevant,
1158
                        // so use the pointer address
1159
0
                        if ((poDriver &&
1160
0
                             EQUAL(poDriver->GetDescription(), "MEM")) ||
1161
0
                            poDS->GetDescription()[0] == 0)
1162
0
                        {
1163
0
                            aosValues.push_back(CPLSPrintf("%p", poDS));
1164
0
                        }
1165
0
                        else
1166
0
                        {
1167
0
                            aosValues.push_back(poDS->GetDescription());
1168
0
                        }
1169
0
                    }
1170
0
                    else
1171
0
                    {
1172
0
                        aosValues.push_back(v.GetName());
1173
0
                    }
1174
0
                }
1175
0
                if (!CheckDuplicateValues(this, aosValues))
1176
0
                    ret = false;
1177
0
            }
1178
0
            break;
1179
0
        }
1180
0
    }
1181
1182
0
    if (GDALAlgorithmArgTypeIsList(GetType()))
1183
0
    {
1184
0
        int valueCount = 0;
1185
0
        if (GetType() == GAAT_STRING_LIST)
1186
0
        {
1187
0
            valueCount =
1188
0
                static_cast<int>(Get<std::vector<std::string>>().size());
1189
0
        }
1190
0
        else if (GetType() == GAAT_INTEGER_LIST)
1191
0
        {
1192
0
            valueCount = static_cast<int>(Get<std::vector<int>>().size());
1193
0
        }
1194
0
        else if (GetType() == GAAT_REAL_LIST)
1195
0
        {
1196
0
            valueCount = static_cast<int>(Get<std::vector<double>>().size());
1197
0
        }
1198
0
        else if (GetType() == GAAT_DATASET_LIST)
1199
0
        {
1200
0
            valueCount = static_cast<int>(
1201
0
                Get<std::vector<GDALArgDatasetValue>>().size());
1202
0
        }
1203
1204
0
        if (valueCount != GetMinCount() && GetMinCount() == GetMaxCount())
1205
0
        {
1206
0
            ReportError(CE_Failure, CPLE_AppDefined,
1207
0
                        "%d value%s been specified for argument '%s', "
1208
0
                        "whereas exactly %d %s expected.",
1209
0
                        valueCount, valueCount > 1 ? "s have" : " has",
1210
0
                        GetName().c_str(), GetMinCount(),
1211
0
                        GetMinCount() > 1 ? "were" : "was");
1212
0
            ret = false;
1213
0
        }
1214
0
        else if (valueCount < GetMinCount())
1215
0
        {
1216
0
            ReportError(CE_Failure, CPLE_AppDefined,
1217
0
                        "Only %d value%s been specified for argument '%s', "
1218
0
                        "whereas at least %d %s expected.",
1219
0
                        valueCount, valueCount > 1 ? "s have" : " has",
1220
0
                        GetName().c_str(), GetMinCount(),
1221
0
                        GetMinCount() > 1 ? "were" : "was");
1222
0
            ret = false;
1223
0
        }
1224
0
        else if (valueCount > GetMaxCount())
1225
0
        {
1226
0
            ReportError(CE_Failure, CPLE_AppDefined,
1227
0
                        "%d value%s been specified for argument '%s', "
1228
0
                        "whereas at most %d %s expected.",
1229
0
                        valueCount, valueCount > 1 ? "s have" : " has",
1230
0
                        GetName().c_str(), GetMaxCount(),
1231
0
                        GetMaxCount() > 1 ? "were" : "was");
1232
0
            ret = false;
1233
0
        }
1234
0
    }
1235
1236
0
    if (ret)
1237
0
    {
1238
0
        for (const auto &f : m_validationActions)
1239
0
        {
1240
0
            if (!f())
1241
0
                ret = false;
1242
0
        }
1243
0
    }
1244
1245
0
    return ret;
1246
0
}
1247
1248
/************************************************************************/
1249
/*                   GDALAlgorithmArg::ReportError()                    */
1250
/************************************************************************/
1251
1252
void GDALAlgorithmArg::ReportError(CPLErr eErrClass, CPLErrorNum err_no,
1253
                                   const char *fmt, ...) const
1254
0
{
1255
0
    va_list args;
1256
0
    va_start(args, fmt);
1257
0
    if (m_owner)
1258
0
    {
1259
0
        m_owner->ReportError(eErrClass, err_no, "%s",
1260
0
                             CPLString().vPrintf(fmt, args).c_str());
1261
0
    }
1262
0
    else
1263
0
    {
1264
0
        CPLError(eErrClass, err_no, "%s",
1265
0
                 CPLString().vPrintf(fmt, args).c_str());
1266
0
    }
1267
0
    va_end(args);
1268
0
}
1269
1270
/************************************************************************/
1271
/*                 GDALAlgorithmArg::GetEscapedString()                 */
1272
/************************************************************************/
1273
1274
/* static */
1275
std::string GDALAlgorithmArg::GetEscapedString(const std::string &s)
1276
0
{
1277
0
    if (s.find_first_of("\" \\,") != std::string::npos &&
1278
0
        !(s.size() > 4 &&
1279
0
          s[0] == GDALAbstractPipelineAlgorithm::OPEN_NESTED_PIPELINE[0] &&
1280
0
          s[1] == ' ' && s[s.size() - 2] == ' ' &&
1281
0
          s.back() == GDALAbstractPipelineAlgorithm::CLOSE_NESTED_PIPELINE[0]))
1282
0
    {
1283
0
        return std::string("\"")
1284
0
            .append(
1285
0
                CPLString(s).replaceAll('\\', "\\\\").replaceAll('"', "\\\""))
1286
0
            .append("\"");
1287
0
    }
1288
0
    else
1289
0
    {
1290
0
        return s;
1291
0
    }
1292
0
}
1293
1294
/************************************************************************/
1295
/*                    GDALAlgorithmArg::Serialize()                     */
1296
/************************************************************************/
1297
1298
bool GDALAlgorithmArg::Serialize(std::string &serializedArg,
1299
                                 bool absolutePath) const
1300
0
{
1301
0
    serializedArg.clear();
1302
1303
0
    if (!IsExplicitlySet())
1304
0
    {
1305
0
        return false;
1306
0
    }
1307
1308
0
    std::string ret = "--";
1309
0
    ret += GetName();
1310
0
    if (GetType() == GAAT_BOOLEAN)
1311
0
    {
1312
0
        serializedArg = std::move(ret);
1313
0
        return true;
1314
0
    }
1315
1316
0
    const auto AddListValueSeparator = [this, &ret]()
1317
0
    {
1318
0
        if (GetPackedValuesAllowed())
1319
0
        {
1320
0
            ret += ',';
1321
0
        }
1322
0
        else
1323
0
        {
1324
0
            ret += " --";
1325
0
            ret += GetName();
1326
0
            ret += ' ';
1327
0
        }
1328
0
    };
1329
1330
0
    const auto MakeAbsolutePath = [](const std::string &filename)
1331
0
    {
1332
0
        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
0
        const auto absPath =
1340
0
            CPLFormFilenameSafe(pszCWD, filename.c_str(), nullptr);
1341
0
        CPLFree(pszCWD);
1342
0
        return absPath;
1343
0
    };
1344
1345
0
    ret += ' ';
1346
0
    switch (GetType())
1347
0
    {
1348
0
        case GAAT_BOOLEAN:
1349
0
            break;
1350
0
        case GAAT_STRING:
1351
0
        {
1352
0
            const auto &val = Get<std::string>();
1353
0
            ret += GetEscapedString(val);
1354
0
            break;
1355
0
        }
1356
0
        case GAAT_INTEGER:
1357
0
        {
1358
0
            ret += CPLSPrintf("%d", Get<int>());
1359
0
            break;
1360
0
        }
1361
0
        case GAAT_REAL:
1362
0
        {
1363
0
            ret += CPLSPrintf("%.17g", Get<double>());
1364
0
            break;
1365
0
        }
1366
0
        case GAAT_DATASET:
1367
0
        {
1368
0
            const auto &val = Get<GDALArgDatasetValue>();
1369
0
            const auto &str = val.GetName();
1370
0
            if (str.empty())
1371
0
            {
1372
0
                return false;
1373
0
            }
1374
0
            ret += GetEscapedString(absolutePath ? MakeAbsolutePath(str) : str);
1375
0
            break;
1376
0
        }
1377
0
        case GAAT_STRING_LIST:
1378
0
        {
1379
0
            const auto &vals = Get<std::vector<std::string>>();
1380
0
            for (size_t i = 0; i < vals.size(); ++i)
1381
0
            {
1382
0
                if (i > 0)
1383
0
                    AddListValueSeparator();
1384
0
                ret += GetEscapedString(vals[i]);
1385
0
            }
1386
0
            break;
1387
0
        }
1388
0
        case GAAT_INTEGER_LIST:
1389
0
        {
1390
0
            const auto &vals = Get<std::vector<int>>();
1391
0
            for (size_t i = 0; i < vals.size(); ++i)
1392
0
            {
1393
0
                if (i > 0)
1394
0
                    AddListValueSeparator();
1395
0
                ret += CPLSPrintf("%d", vals[i]);
1396
0
            }
1397
0
            break;
1398
0
        }
1399
0
        case GAAT_REAL_LIST:
1400
0
        {
1401
0
            const auto &vals = Get<std::vector<double>>();
1402
0
            for (size_t i = 0; i < vals.size(); ++i)
1403
0
            {
1404
0
                if (i > 0)
1405
0
                    AddListValueSeparator();
1406
0
                ret += CPLSPrintf("%.17g", vals[i]);
1407
0
            }
1408
0
            break;
1409
0
        }
1410
0
        case GAAT_DATASET_LIST:
1411
0
        {
1412
0
            const auto &vals = Get<std::vector<GDALArgDatasetValue>>();
1413
0
            for (size_t i = 0; i < vals.size(); ++i)
1414
0
            {
1415
0
                if (i > 0)
1416
0
                    AddListValueSeparator();
1417
0
                const auto &val = vals[i];
1418
0
                const auto &str = val.GetName();
1419
0
                if (str.empty())
1420
0
                {
1421
0
                    return false;
1422
0
                }
1423
0
                ret += GetEscapedString(absolutePath ? MakeAbsolutePath(str)
1424
0
                                                     : str);
1425
0
            }
1426
0
            break;
1427
0
        }
1428
0
    }
1429
1430
0
    serializedArg = std::move(ret);
1431
0
    return true;
1432
0
}
1433
1434
/************************************************************************/
1435
/*                  ~GDALInConstructionAlgorithmArg()                   */
1436
/************************************************************************/
1437
1438
GDALInConstructionAlgorithmArg::~GDALInConstructionAlgorithmArg() = default;
1439
1440
/************************************************************************/
1441
/*              GDALInConstructionAlgorithmArg::AddAlias()              */
1442
/************************************************************************/
1443
1444
GDALInConstructionAlgorithmArg &
1445
GDALInConstructionAlgorithmArg::AddAlias(const std::string &alias)
1446
0
{
1447
0
    m_decl.AddAlias(alias);
1448
0
    if (m_owner)
1449
0
        m_owner->AddAliasFor(this, alias);
1450
0
    return *this;
1451
0
}
1452
1453
/************************************************************************/
1454
/*           GDALInConstructionAlgorithmArg::AddHiddenAlias()           */
1455
/************************************************************************/
1456
1457
GDALInConstructionAlgorithmArg &
1458
GDALInConstructionAlgorithmArg::AddHiddenAlias(const std::string &alias)
1459
0
{
1460
0
    m_decl.AddHiddenAlias(alias);
1461
0
    if (m_owner)
1462
0
        m_owner->AddAliasFor(this, alias);
1463
0
    return *this;
1464
0
}
1465
1466
/************************************************************************/
1467
/*         GDALInConstructionAlgorithmArg::AddShortNameAlias()          */
1468
/************************************************************************/
1469
1470
GDALInConstructionAlgorithmArg &
1471
GDALInConstructionAlgorithmArg::AddShortNameAlias(char shortNameAlias)
1472
0
{
1473
0
    m_decl.AddShortNameAlias(shortNameAlias);
1474
0
    if (m_owner)
1475
0
        m_owner->AddShortNameAliasFor(this, shortNameAlias);
1476
0
    return *this;
1477
0
}
1478
1479
/************************************************************************/
1480
/*           GDALInConstructionAlgorithmArg::SetPositional()            */
1481
/************************************************************************/
1482
1483
GDALInConstructionAlgorithmArg &GDALInConstructionAlgorithmArg::SetPositional()
1484
0
{
1485
0
    m_decl.SetPositional();
1486
0
    if (m_owner)
1487
0
        m_owner->SetPositional(this);
1488
0
    return *this;
1489
0
}
1490
1491
/************************************************************************/
1492
/*              GDALArgDatasetValue::GDALArgDatasetValue()              */
1493
/************************************************************************/
1494
1495
GDALArgDatasetValue::GDALArgDatasetValue(GDALDataset *poDS)
1496
0
    : m_poDS(poDS), m_name(m_poDS ? m_poDS->GetDescription() : std::string()),
1497
0
      m_nameSet(true)
1498
0
{
1499
0
    if (m_poDS)
1500
0
        m_poDS->Reference();
1501
0
}
1502
1503
/************************************************************************/
1504
/*                      GDALArgDatasetValue::Set()                      */
1505
/************************************************************************/
1506
1507
void GDALArgDatasetValue::Set(const std::string &name)
1508
0
{
1509
0
    Close();
1510
0
    m_name = name;
1511
0
    m_nameSet = true;
1512
0
    if (m_ownerArg)
1513
0
        m_ownerArg->NotifyValueSet();
1514
0
}
1515
1516
/************************************************************************/
1517
/*                      GDALArgDatasetValue::Set()                      */
1518
/************************************************************************/
1519
1520
void GDALArgDatasetValue::Set(std::unique_ptr<GDALDataset> poDS)
1521
0
{
1522
0
    Close();
1523
0
    m_poDS = poDS.release();
1524
0
    m_name = m_poDS ? m_poDS->GetDescription() : std::string();
1525
0
    m_nameSet = true;
1526
0
    if (m_ownerArg)
1527
0
        m_ownerArg->NotifyValueSet();
1528
0
}
1529
1530
/************************************************************************/
1531
/*                      GDALArgDatasetValue::Set()                      */
1532
/************************************************************************/
1533
1534
void GDALArgDatasetValue::Set(GDALDataset *poDS)
1535
0
{
1536
0
    Close();
1537
0
    m_poDS = poDS;
1538
0
    if (m_poDS)
1539
0
        m_poDS->Reference();
1540
0
    m_name = m_poDS ? m_poDS->GetDescription() : std::string();
1541
0
    m_nameSet = true;
1542
0
    if (m_ownerArg)
1543
0
        m_ownerArg->NotifyValueSet();
1544
0
}
1545
1546
/************************************************************************/
1547
/*                    GDALArgDatasetValue::SetFrom()                    */
1548
/************************************************************************/
1549
1550
void GDALArgDatasetValue::SetFrom(const GDALArgDatasetValue &other)
1551
0
{
1552
0
    Close();
1553
0
    m_name = other.m_name;
1554
0
    m_nameSet = other.m_nameSet;
1555
0
    m_poDS = other.m_poDS;
1556
0
    if (m_poDS)
1557
0
        m_poDS->Reference();
1558
0
}
1559
1560
/************************************************************************/
1561
/*             GDALArgDatasetValue::~GDALArgDatasetValue()              */
1562
/************************************************************************/
1563
1564
GDALArgDatasetValue::~GDALArgDatasetValue()
1565
0
{
1566
0
    Close();
1567
0
}
1568
1569
/************************************************************************/
1570
/*                     GDALArgDatasetValue::Close()                     */
1571
/************************************************************************/
1572
1573
bool GDALArgDatasetValue::Close()
1574
0
{
1575
0
    bool ret = true;
1576
0
    if (m_poDS && m_poDS->Dereference() == 0)
1577
0
    {
1578
0
        ret = m_poDS->Close() == CE_None;
1579
0
        delete m_poDS;
1580
0
    }
1581
0
    m_poDS = nullptr;
1582
0
    return ret;
1583
0
}
1584
1585
/************************************************************************/
1586
/*                   GDALArgDatasetValue::operator=()                   */
1587
/************************************************************************/
1588
1589
GDALArgDatasetValue &GDALArgDatasetValue::operator=(GDALArgDatasetValue &&other)
1590
0
{
1591
0
    Close();
1592
0
    m_poDS = other.m_poDS;
1593
0
    m_name = other.m_name;
1594
0
    m_nameSet = other.m_nameSet;
1595
0
    other.m_poDS = nullptr;
1596
0
    other.m_name.clear();
1597
0
    other.m_nameSet = false;
1598
0
    return *this;
1599
0
}
1600
1601
/************************************************************************/
1602
/*                  GDALArgDatasetValue::GetDataset()                   */
1603
/************************************************************************/
1604
1605
GDALDataset *GDALArgDatasetValue::GetDatasetIncreaseRefCount()
1606
0
{
1607
0
    if (m_poDS)
1608
0
        m_poDS->Reference();
1609
0
    return m_poDS;
1610
0
}
1611
1612
/************************************************************************/
1613
/*           GDALArgDatasetValue(GDALArgDatasetValue &&other)           */
1614
/************************************************************************/
1615
1616
GDALArgDatasetValue::GDALArgDatasetValue(GDALArgDatasetValue &&other)
1617
0
    : m_poDS(other.m_poDS), m_name(other.m_name), m_nameSet(other.m_nameSet)
1618
0
{
1619
0
    other.m_poDS = nullptr;
1620
0
    other.m_name.clear();
1621
0
}
1622
1623
/************************************************************************/
1624
/*            GDALInConstructionAlgorithmArg::SetIsCRSArg()             */
1625
/************************************************************************/
1626
1627
GDALInConstructionAlgorithmArg &GDALInConstructionAlgorithmArg::SetIsCRSArg(
1628
    bool noneAllowed, const std::vector<std::string> &specialValues)
1629
0
{
1630
0
    if (GetType() != GAAT_STRING)
1631
0
    {
1632
0
        CPLError(CE_Failure, CPLE_AppDefined,
1633
0
                 "SetIsCRSArg() can only be called on a String argument");
1634
0
        return *this;
1635
0
    }
1636
0
    AddValidationAction(
1637
0
        [this, noneAllowed, specialValues]()
1638
0
        {
1639
0
            const std::string &osVal =
1640
0
                static_cast<const GDALInConstructionAlgorithmArg *>(this)
1641
0
                    ->Get<std::string>();
1642
0
            if (osVal == "?" && m_owner && m_owner->IsCalledFromCommandLine())
1643
0
                return true;
1644
1645
0
            if ((!noneAllowed || (osVal != "none" && osVal != "null")) &&
1646
0
                std::find(specialValues.begin(), specialValues.end(), osVal) ==
1647
0
                    specialValues.end())
1648
0
            {
1649
0
                OGRSpatialReference oSRS;
1650
0
                if (oSRS.SetFromUserInput(osVal.c_str()) != OGRERR_NONE)
1651
0
                {
1652
0
                    m_owner->ReportError(CE_Failure, CPLE_AppDefined,
1653
0
                                         "Invalid value for '%s' argument",
1654
0
                                         GetName().c_str());
1655
0
                    return false;
1656
0
                }
1657
0
            }
1658
0
            return true;
1659
0
        });
1660
1661
0
    SetAutoCompleteFunction(
1662
0
        [this, noneAllowed, specialValues](const std::string &currentValue)
1663
0
        {
1664
0
            bool bIsRaster = false;
1665
0
            OGREnvelope sDatasetLongLatEnv;
1666
0
            std::string osCelestialBodyName;
1667
0
            if (GetName() == GDAL_ARG_NAME_OUTPUT_CRS)
1668
0
            {
1669
0
                auto inputArg = m_owner->GetArg(GDAL_ARG_NAME_INPUT);
1670
0
                if (inputArg && inputArg->GetType() == GAAT_DATASET_LIST)
1671
0
                {
1672
0
                    auto &val =
1673
0
                        inputArg->Get<std::vector<GDALArgDatasetValue>>();
1674
0
                    if (val.size() == 1)
1675
0
                    {
1676
0
                        CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
1677
0
                        auto poDS = std::unique_ptr<GDALDataset>(
1678
0
                            GDALDataset::Open(val[0].GetName().c_str()));
1679
0
                        if (poDS)
1680
0
                        {
1681
0
                            bIsRaster = poDS->GetRasterCount() != 0;
1682
0
                            if (auto poCRS = poDS->GetSpatialRef())
1683
0
                            {
1684
0
                                const char *pszCelestialBodyName =
1685
0
                                    poCRS->GetCelestialBodyName();
1686
0
                                if (pszCelestialBodyName)
1687
0
                                    osCelestialBodyName = pszCelestialBodyName;
1688
1689
0
                                if (!pszCelestialBodyName ||
1690
0
                                    !EQUAL(pszCelestialBodyName, "Earth"))
1691
0
                                {
1692
0
                                    OGRSpatialReference oLongLat;
1693
0
                                    oLongLat.CopyGeogCSFrom(poCRS);
1694
0
                                    oLongLat.SetAxisMappingStrategy(
1695
0
                                        OAMS_TRADITIONAL_GIS_ORDER);
1696
0
                                    poDS->GetExtent(&sDatasetLongLatEnv,
1697
0
                                                    &oLongLat);
1698
0
                                }
1699
0
                                else
1700
0
                                {
1701
0
                                    poDS->GetExtentWGS84LongLat(
1702
0
                                        &sDatasetLongLatEnv);
1703
0
                                }
1704
0
                            }
1705
0
                        }
1706
0
                    }
1707
0
                }
1708
0
            }
1709
1710
0
            const auto IsCRSCompatible =
1711
0
                [bIsRaster, &sDatasetLongLatEnv,
1712
0
                 &osCelestialBodyName](const OSRCRSInfo *crsInfo)
1713
0
            {
1714
0
                if (!sDatasetLongLatEnv.IsInit())
1715
0
                    return true;
1716
0
                return crsInfo->eType != OSR_CRS_TYPE_VERTICAL &&
1717
0
                       !(bIsRaster &&
1718
0
                         crsInfo->eType == OSR_CRS_TYPE_GEOCENTRIC) &&
1719
0
                       crsInfo->dfWestLongitudeDeg <
1720
0
                           crsInfo->dfEastLongitudeDeg &&
1721
0
                       sDatasetLongLatEnv.MinX < crsInfo->dfEastLongitudeDeg &&
1722
0
                       sDatasetLongLatEnv.MaxX > crsInfo->dfWestLongitudeDeg &&
1723
0
                       sDatasetLongLatEnv.MinY < crsInfo->dfNorthLatitudeDeg &&
1724
0
                       sDatasetLongLatEnv.MaxY > crsInfo->dfSouthLatitudeDeg &&
1725
0
                       ((!osCelestialBodyName.empty() &&
1726
0
                         crsInfo->pszCelestialBodyName &&
1727
0
                         osCelestialBodyName ==
1728
0
                             crsInfo->pszCelestialBodyName) ||
1729
0
                        (osCelestialBodyName.empty() &&
1730
0
                         !crsInfo->pszCelestialBodyName));
1731
0
            };
1732
1733
0
            std::vector<std::string> oRet;
1734
0
            if (noneAllowed)
1735
0
                oRet.push_back("none");
1736
0
            oRet.insert(oRet.end(), specialValues.begin(), specialValues.end());
1737
0
            if (!currentValue.empty())
1738
0
            {
1739
0
                const CPLStringList aosTokens(
1740
0
                    CSLTokenizeString2(currentValue.c_str(), ":", 0));
1741
0
                int nCount = 0;
1742
0
                std::unique_ptr<OSRCRSInfo *, decltype(&OSRDestroyCRSInfoList)>
1743
0
                    pCRSList(OSRGetCRSInfoListFromDatabase(aosTokens[0],
1744
0
                                                           nullptr, &nCount),
1745
0
                             OSRDestroyCRSInfoList);
1746
0
                std::string osCode;
1747
1748
0
                std::vector<const OSRCRSInfo *> candidates;
1749
0
                for (int i = 0; i < nCount; ++i)
1750
0
                {
1751
0
                    const auto *entry = (pCRSList.get())[i];
1752
0
                    if (!entry->bDeprecated && IsCRSCompatible(entry))
1753
0
                    {
1754
0
                        if (aosTokens.size() == 1 ||
1755
0
                            STARTS_WITH(entry->pszCode, aosTokens[1]))
1756
0
                        {
1757
0
                            if (candidates.empty())
1758
0
                                osCode = entry->pszCode;
1759
0
                            candidates.push_back(entry);
1760
0
                        }
1761
0
                    }
1762
0
                }
1763
0
                if (candidates.size() == 1)
1764
0
                {
1765
0
                    oRet.push_back(std::move(osCode));
1766
0
                }
1767
0
                else
1768
0
                {
1769
0
                    if (sDatasetLongLatEnv.IsInit())
1770
0
                    {
1771
0
                        std::sort(
1772
0
                            candidates.begin(), candidates.end(),
1773
0
                            [](const OSRCRSInfo *a, const OSRCRSInfo *b)
1774
0
                            {
1775
0
                                const double dfXa =
1776
0
                                    a->dfWestLongitudeDeg >
1777
0
                                            a->dfEastLongitudeDeg
1778
0
                                        ? a->dfWestLongitudeDeg -
1779
0
                                              a->dfEastLongitudeDeg
1780
0
                                        : (180 - a->dfWestLongitudeDeg) +
1781
0
                                              (a->dfEastLongitudeDeg - -180);
1782
0
                                const double dfYa = a->dfNorthLatitudeDeg -
1783
0
                                                    a->dfSouthLatitudeDeg;
1784
0
                                const double dfXb =
1785
0
                                    b->dfWestLongitudeDeg >
1786
0
                                            b->dfEastLongitudeDeg
1787
0
                                        ? b->dfWestLongitudeDeg -
1788
0
                                              b->dfEastLongitudeDeg
1789
0
                                        : (180 - b->dfWestLongitudeDeg) +
1790
0
                                              (b->dfEastLongitudeDeg - -180);
1791
0
                                const double dfYb = b->dfNorthLatitudeDeg -
1792
0
                                                    b->dfSouthLatitudeDeg;
1793
0
                                const double diffArea =
1794
0
                                    dfXa * dfYa - dfXb * dfYb;
1795
0
                                if (diffArea < 0)
1796
0
                                    return true;
1797
0
                                if (diffArea == 0)
1798
0
                                {
1799
0
                                    if (std::string_view(a->pszName) ==
1800
0
                                        b->pszName)
1801
0
                                    {
1802
0
                                        if (a->eType ==
1803
0
                                                OSR_CRS_TYPE_GEOGRAPHIC_2D &&
1804
0
                                            b->eType !=
1805
0
                                                OSR_CRS_TYPE_GEOGRAPHIC_2D)
1806
0
                                            return true;
1807
0
                                        if (a->eType ==
1808
0
                                                OSR_CRS_TYPE_GEOGRAPHIC_3D &&
1809
0
                                            b->eType == OSR_CRS_TYPE_GEOCENTRIC)
1810
0
                                            return true;
1811
0
                                        return false;
1812
0
                                    }
1813
0
                                    return std::string_view(a->pszCode) <
1814
0
                                           b->pszCode;
1815
0
                                }
1816
0
                                return false;
1817
0
                            });
1818
0
                    }
1819
1820
0
                    for (const auto *entry : candidates)
1821
0
                    {
1822
0
                        std::string val = std::string(entry->pszCode)
1823
0
                                              .append(" -- ")
1824
0
                                              .append(entry->pszName);
1825
0
                        if (entry->eType == OSR_CRS_TYPE_GEOGRAPHIC_2D)
1826
0
                            val.append(" (geographic 2D)");
1827
0
                        else if (entry->eType == OSR_CRS_TYPE_GEOGRAPHIC_3D)
1828
0
                            val.append(" (geographic 3D)");
1829
0
                        else if (entry->eType == OSR_CRS_TYPE_GEOCENTRIC)
1830
0
                            val.append(" (geocentric)");
1831
0
                        oRet.push_back(std::move(val));
1832
0
                    }
1833
0
                }
1834
0
            }
1835
0
            if (currentValue.empty() || oRet.empty())
1836
0
            {
1837
0
                const CPLStringList aosAuthorities(
1838
0
                    OSRGetAuthorityListFromDatabase());
1839
0
                for (const char *pszAuth : cpl::Iterate(aosAuthorities))
1840
0
                {
1841
0
                    int nCount = 0;
1842
0
                    OSRDestroyCRSInfoList(OSRGetCRSInfoListFromDatabase(
1843
0
                        pszAuth, nullptr, &nCount));
1844
0
                    if (nCount)
1845
0
                        oRet.push_back(std::string(pszAuth).append(":"));
1846
0
                }
1847
0
            }
1848
0
            return oRet;
1849
0
        });
1850
1851
0
    return *this;
1852
0
}
1853
1854
/************************************************************************/
1855
/*                    GDALAlgorithm::GDALAlgorithm()                    */
1856
/************************************************************************/
1857
1858
GDALAlgorithm::GDALAlgorithm(const std::string &name,
1859
                             const std::string &description,
1860
                             const std::string &helpURL)
1861
0
    : m_name(name), m_description(description), m_helpURL(helpURL),
1862
0
      m_helpFullURL(!m_helpURL.empty() && m_helpURL[0] == '/'
1863
0
                        ? "https://gdal.org" + m_helpURL
1864
0
                        : m_helpURL)
1865
0
{
1866
0
    auto &helpArg =
1867
0
        AddArg("help", 'h', _("Display help message and exit"),
1868
0
               &m_helpRequested)
1869
0
            .SetHiddenForAPI()
1870
0
            .SetCategory(GAAC_COMMON)
1871
0
            .AddAction([this]()
1872
0
                       { m_specialActionRequested = m_calledFromCommandLine; });
1873
0
    auto &helpDocArg =
1874
0
        AddArg("help-doc", 0,
1875
0
               _("Display help message for use by documentation"),
1876
0
               &m_helpDocRequested)
1877
0
            .SetHidden()
1878
0
            .AddAction([this]()
1879
0
                       { m_specialActionRequested = m_calledFromCommandLine; });
1880
0
    auto &jsonUsageArg =
1881
0
        AddArg("json-usage", 0, _("Display usage as JSON document and exit"),
1882
0
               &m_JSONUsageRequested)
1883
0
            .SetHiddenForAPI()
1884
0
            .SetCategory(GAAC_COMMON)
1885
0
            .AddAction([this]()
1886
0
                       { m_specialActionRequested = m_calledFromCommandLine; });
1887
0
    AddArg("config", 0, _("Configuration option"), &m_dummyConfigOptions)
1888
0
        .SetMetaVar("<KEY>=<VALUE>")
1889
0
        .SetHiddenForAPI()
1890
0
        .SetCategory(GAAC_COMMON)
1891
0
        .AddAction(
1892
0
            [this]()
1893
0
            {
1894
0
                ReportError(
1895
0
                    CE_Warning, CPLE_AppDefined,
1896
0
                    "Configuration options passed with the 'config' argument "
1897
0
                    "are ignored");
1898
0
            });
1899
1900
0
    AddValidationAction(
1901
0
        [this, &helpArg, &helpDocArg, &jsonUsageArg]()
1902
0
        {
1903
0
            if (!m_calledFromCommandLine && m_specialActionRequested)
1904
0
            {
1905
0
                for (auto &arg : {&helpArg, &helpDocArg, &jsonUsageArg})
1906
0
                {
1907
0
                    if (arg->IsExplicitlySet())
1908
0
                    {
1909
0
                        ReportError(CE_Failure, CPLE_AppDefined,
1910
0
                                    "'%s' argument only available when called "
1911
0
                                    "from command line",
1912
0
                                    arg->GetName().c_str());
1913
0
                        return false;
1914
0
                    }
1915
0
                }
1916
0
            }
1917
0
            return true;
1918
0
        });
1919
0
}
1920
1921
/************************************************************************/
1922
/*                   GDALAlgorithm::~GDALAlgorithm()                    */
1923
/************************************************************************/
1924
1925
0
GDALAlgorithm::~GDALAlgorithm() = default;
1926
1927
/************************************************************************/
1928
/*                    GDALAlgorithm::ParseArgument()                    */
1929
/************************************************************************/
1930
1931
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
0
{
1939
0
    const bool isListArg =
1940
0
        GDALAlgorithmArgTypeIsList(arg->GetType()) && arg->GetMaxCount() > 1;
1941
0
    if (arg->IsExplicitlySet() && !isListArg)
1942
0
    {
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
0
        if (arg->SkipIfAlreadySet())
1946
0
        {
1947
0
            arg->SetSkipIfAlreadySet(false);
1948
0
            return true;
1949
0
        }
1950
1951
0
        ReportError(CE_Failure, CPLE_IllegalArg,
1952
0
                    "Argument '%s' has already been specified.", name.c_str());
1953
0
        return false;
1954
0
    }
1955
1956
0
    if (!arg->GetRepeatedArgAllowed() &&
1957
0
        cpl::contains(inConstructionValues, arg))
1958
0
    {
1959
0
        ReportError(CE_Failure, CPLE_IllegalArg,
1960
0
                    "Argument '%s' has already been specified.", name.c_str());
1961
0
        return false;
1962
0
    }
1963
1964
0
    switch (arg->GetType())
1965
0
    {
1966
0
        case GAAT_BOOLEAN:
1967
0
        {
1968
0
            if (value.empty() || value == "true")
1969
0
                return arg->Set(true);
1970
0
            else if (value == "false")
1971
0
                return arg->Set(false);
1972
0
            else
1973
0
            {
1974
0
                ReportError(
1975
0
                    CE_Failure, CPLE_IllegalArg,
1976
0
                    "Invalid value '%s' for boolean argument '%s'. Should be "
1977
0
                    "'true' or 'false'.",
1978
0
                    value.c_str(), name.c_str());
1979
0
                return false;
1980
0
            }
1981
0
        }
1982
1983
0
        case GAAT_STRING:
1984
0
        {
1985
0
            return arg->Set(value);
1986
0
        }
1987
1988
0
        case GAAT_INTEGER:
1989
0
        {
1990
0
            errno = 0;
1991
0
            char *endptr = nullptr;
1992
0
            const auto val = std::strtol(value.c_str(), &endptr, 10);
1993
0
            if (errno == 0 && endptr &&
1994
0
                endptr == value.c_str() + value.size() && val >= INT_MIN &&
1995
0
                val <= INT_MAX)
1996
0
            {
1997
0
                return arg->Set(static_cast<int>(val));
1998
0
            }
1999
0
            else
2000
0
            {
2001
0
                ReportError(CE_Failure, CPLE_IllegalArg,
2002
0
                            "Expected integer value for argument '%s', "
2003
0
                            "but got '%s'.",
2004
0
                            name.c_str(), value.c_str());
2005
0
                return false;
2006
0
            }
2007
0
        }
2008
2009
0
        case GAAT_REAL:
2010
0
        {
2011
0
            char *endptr = nullptr;
2012
0
            double dfValue = CPLStrtod(value.c_str(), &endptr);
2013
0
            if (endptr != value.c_str() + value.size())
2014
0
            {
2015
0
                ReportError(
2016
0
                    CE_Failure, CPLE_IllegalArg,
2017
0
                    "Expected real value for argument '%s', but got '%s'.",
2018
0
                    name.c_str(), value.c_str());
2019
0
                return false;
2020
0
            }
2021
0
            return arg->Set(dfValue);
2022
0
        }
2023
2024
0
        case GAAT_DATASET:
2025
0
        {
2026
0
            return arg->SetDatasetName(value);
2027
0
        }
2028
2029
0
        case GAAT_STRING_LIST:
2030
0
        {
2031
0
            const CPLStringList aosTokens(
2032
0
                arg->GetPackedValuesAllowed()
2033
0
                    ? CSLTokenizeString2(value.c_str(), ",",
2034
0
                                         CSLT_HONOURSTRINGS |
2035
0
                                             CSLT_PRESERVEQUOTES)
2036
0
                    : CSLAddString(nullptr, value.c_str()));
2037
0
            if (!cpl::contains(inConstructionValues, arg))
2038
0
            {
2039
0
                inConstructionValues[arg] = std::vector<std::string>();
2040
0
            }
2041
0
            auto &valueVector =
2042
0
                std::get<std::vector<std::string>>(inConstructionValues[arg]);
2043
0
            for (const char *v : aosTokens)
2044
0
            {
2045
0
                valueVector.push_back(v);
2046
0
            }
2047
0
            if (arg->GetMaxCount() == 1)
2048
0
            {
2049
0
                bool ret = arg->Set(std::move(valueVector));
2050
0
                inConstructionValues.erase(inConstructionValues.find(arg));
2051
0
                return ret;
2052
0
            }
2053
2054
0
            break;
2055
0
        }
2056
2057
0
        case GAAT_INTEGER_LIST:
2058
0
        {
2059
0
            const CPLStringList aosTokens(
2060
0
                arg->GetPackedValuesAllowed()
2061
0
                    ? CSLTokenizeString2(
2062
0
                          value.c_str(), ",",
2063
0
                          CSLT_HONOURSTRINGS | CSLT_STRIPLEADSPACES |
2064
0
                              CSLT_STRIPENDSPACES | CSLT_ALLOWEMPTYTOKENS)
2065
0
                    : CSLAddString(nullptr, value.c_str()));
2066
0
            if (!cpl::contains(inConstructionValues, arg))
2067
0
            {
2068
0
                inConstructionValues[arg] = std::vector<int>();
2069
0
            }
2070
0
            auto &valueVector =
2071
0
                std::get<std::vector<int>>(inConstructionValues[arg]);
2072
0
            for (const char *v : aosTokens)
2073
0
            {
2074
0
                errno = 0;
2075
0
                char *endptr = nullptr;
2076
0
                const auto val = std::strtol(v, &endptr, 10);
2077
0
                if (errno == 0 && endptr && endptr == v + strlen(v) &&
2078
0
                    val >= INT_MIN && val <= INT_MAX && strlen(v) > 0)
2079
0
                {
2080
0
                    valueVector.push_back(static_cast<int>(val));
2081
0
                }
2082
0
                else
2083
0
                {
2084
0
                    ReportError(
2085
0
                        CE_Failure, CPLE_IllegalArg,
2086
0
                        "Expected list of integer value for argument '%s', "
2087
0
                        "but got '%s'.",
2088
0
                        name.c_str(), value.c_str());
2089
0
                    return false;
2090
0
                }
2091
0
            }
2092
0
            if (arg->GetMaxCount() == 1)
2093
0
            {
2094
0
                bool ret = arg->Set(std::move(valueVector));
2095
0
                inConstructionValues.erase(inConstructionValues.find(arg));
2096
0
                return ret;
2097
0
            }
2098
2099
0
            break;
2100
0
        }
2101
2102
0
        case GAAT_REAL_LIST:
2103
0
        {
2104
0
            const CPLStringList aosTokens(
2105
0
                arg->GetPackedValuesAllowed()
2106
0
                    ? CSLTokenizeString2(
2107
0
                          value.c_str(), ",",
2108
0
                          CSLT_HONOURSTRINGS | CSLT_STRIPLEADSPACES |
2109
0
                              CSLT_STRIPENDSPACES | CSLT_ALLOWEMPTYTOKENS)
2110
0
                    : CSLAddString(nullptr, value.c_str()));
2111
0
            if (!cpl::contains(inConstructionValues, arg))
2112
0
            {
2113
0
                inConstructionValues[arg] = std::vector<double>();
2114
0
            }
2115
0
            auto &valueVector =
2116
0
                std::get<std::vector<double>>(inConstructionValues[arg]);
2117
0
            for (const char *v : aosTokens)
2118
0
            {
2119
0
                char *endptr = nullptr;
2120
0
                double dfValue = CPLStrtod(v, &endptr);
2121
0
                if (strlen(v) == 0 || endptr != v + strlen(v))
2122
0
                {
2123
0
                    ReportError(
2124
0
                        CE_Failure, CPLE_IllegalArg,
2125
0
                        "Expected list of real value for argument '%s', "
2126
0
                        "but got '%s'.",
2127
0
                        name.c_str(), value.c_str());
2128
0
                    return false;
2129
0
                }
2130
0
                valueVector.push_back(dfValue);
2131
0
            }
2132
0
            if (arg->GetMaxCount() == 1)
2133
0
            {
2134
0
                bool ret = arg->Set(std::move(valueVector));
2135
0
                inConstructionValues.erase(inConstructionValues.find(arg));
2136
0
                return ret;
2137
0
            }
2138
2139
0
            break;
2140
0
        }
2141
2142
0
        case GAAT_DATASET_LIST:
2143
0
        {
2144
0
            if (!cpl::contains(inConstructionValues, arg))
2145
0
            {
2146
0
                inConstructionValues[arg] = std::vector<GDALArgDatasetValue>();
2147
0
            }
2148
0
            auto &valueVector = std::get<std::vector<GDALArgDatasetValue>>(
2149
0
                inConstructionValues[arg]);
2150
0
            if (!value.empty() && value[0] == '{' && value.back() == '}')
2151
0
            {
2152
0
                valueVector.push_back(GDALArgDatasetValue(value));
2153
0
            }
2154
0
            else
2155
0
            {
2156
0
                const CPLStringList aosTokens(
2157
0
                    arg->GetPackedValuesAllowed()
2158
0
                        ? CSLTokenizeString2(value.c_str(), ",",
2159
0
                                             CSLT_HONOURSTRINGS |
2160
0
                                                 CSLT_STRIPLEADSPACES)
2161
0
                        : CSLAddString(nullptr, value.c_str()));
2162
0
                for (const char *v : aosTokens)
2163
0
                {
2164
0
                    valueVector.push_back(GDALArgDatasetValue(v));
2165
0
                }
2166
0
            }
2167
0
            if (arg->GetMaxCount() == 1)
2168
0
            {
2169
0
                bool ret = arg->Set(std::move(valueVector));
2170
0
                inConstructionValues.erase(inConstructionValues.find(arg));
2171
0
                return ret;
2172
0
            }
2173
2174
0
            break;
2175
0
        }
2176
0
    }
2177
2178
0
    return true;
2179
0
}
2180
2181
/************************************************************************/
2182
/*                     FormatSuggestionsAsString()                      */
2183
/************************************************************************/
2184
2185
static std::string
2186
FormatSuggestionsAsString(const std::vector<std::string> &suggestions,
2187
                          bool addDashDashPrefix)
2188
0
{
2189
0
    std::string ret;
2190
0
    for (auto [i, suggestion] : cpl::enumerate(suggestions))
2191
0
    {
2192
0
        if (i > 0)
2193
0
        {
2194
0
            ret += (i + 1 < suggestions.size()) ? ", " : " or ";
2195
0
        }
2196
0
        ret += '\'';
2197
0
        if (addDashDashPrefix)
2198
0
            ret += "--";
2199
0
        ret += suggestion;
2200
0
        ret += '\'';
2201
0
    }
2202
0
    return ret;
2203
0
}
2204
2205
/************************************************************************/
2206
/*              GDALAlgorithm::ParseCommandLineArguments()              */
2207
/************************************************************************/
2208
2209
bool GDALAlgorithm::ParseCommandLineArguments(
2210
    const std::vector<std::string> &args)
2211
0
{
2212
0
    if (m_parsedSubStringAlreadyCalled)
2213
0
    {
2214
0
        ReportError(CE_Failure, CPLE_AppDefined,
2215
0
                    "ParseCommandLineArguments() can only be called once per "
2216
0
                    "instance.");
2217
0
        return false;
2218
0
    }
2219
0
    m_parsedSubStringAlreadyCalled = true;
2220
2221
    // AWS like syntax supported too (not advertized)
2222
0
    if (args.size() == 1 && args[0] == "help")
2223
0
    {
2224
0
        auto arg = GetArg("help");
2225
0
        assert(arg);
2226
0
        arg->Set(true);
2227
0
        arg->RunActions();
2228
0
        return true;
2229
0
    }
2230
2231
0
    if (HasSubAlgorithms())
2232
0
    {
2233
0
        if (args.empty())
2234
0
        {
2235
0
            ReportError(CE_Failure, CPLE_AppDefined, "Missing %s name.",
2236
0
                        m_callPath.size() == 1 ? "command" : "subcommand");
2237
0
            return false;
2238
0
        }
2239
0
        if (!args[0].empty() && args[0][0] == '-')
2240
0
        {
2241
            // go on argument parsing
2242
0
        }
2243
0
        else
2244
0
        {
2245
0
            const auto nCounter = CPLGetErrorCounter();
2246
0
            m_selectedSubAlgHolder = InstantiateSubAlgorithm(args[0]);
2247
0
            if (m_selectedSubAlgHolder)
2248
0
            {
2249
0
                m_selectedSubAlg = m_selectedSubAlgHolder.get();
2250
0
                m_selectedSubAlg->SetReferencePathForRelativePaths(
2251
0
                    m_referencePath);
2252
0
                m_selectedSubAlg->m_executionForStreamOutput =
2253
0
                    m_executionForStreamOutput;
2254
0
                m_selectedSubAlg->m_calledFromCommandLine =
2255
0
                    m_calledFromCommandLine;
2256
0
                m_selectedSubAlg->m_skipValidationInParseCommandLine =
2257
0
                    m_skipValidationInParseCommandLine;
2258
0
                bool bRet = m_selectedSubAlg->ParseCommandLineArguments(
2259
0
                    std::vector<std::string>(args.begin() + 1, args.end()));
2260
0
                m_selectedSubAlg->PropagateSpecialActionTo(this);
2261
0
                return bRet;
2262
0
            }
2263
0
            else
2264
0
            {
2265
0
                if (!(CPLGetErrorCounter() == nCounter + 1 &&
2266
0
                      strstr(CPLGetLastErrorMsg(), "Do you mean")))
2267
0
                {
2268
0
                    ReportError(CE_Failure, CPLE_AppDefined,
2269
0
                                "Unknown command: '%s'", args[0].c_str());
2270
0
                }
2271
0
                return false;
2272
0
            }
2273
0
        }
2274
0
    }
2275
2276
0
    std::map<
2277
0
        GDALAlgorithmArg *,
2278
0
        std::variant<std::vector<std::string>, std::vector<int>,
2279
0
                     std::vector<double>, std::vector<GDALArgDatasetValue>>>
2280
0
        inConstructionValues;
2281
2282
0
    std::vector<std::string> lArgs(args);
2283
0
    bool helpValueRequested = false;
2284
0
    for (size_t i = 0; i < lArgs.size(); /* incremented in loop */)
2285
0
    {
2286
0
        const auto &strArg = lArgs[i];
2287
0
        GDALAlgorithmArg *arg = nullptr;
2288
0
        std::string name;
2289
0
        std::string value;
2290
0
        bool hasValue = false;
2291
0
        if (m_calledFromCommandLine && cpl::ends_with(strArg, "=?"))
2292
0
            helpValueRequested = true;
2293
0
        if (strArg.size() >= 2 && strArg[0] == '-' && strArg[1] == '-')
2294
0
        {
2295
0
            const auto equalPos = strArg.find('=');
2296
0
            name = (equalPos != std::string::npos) ? strArg.substr(0, equalPos)
2297
0
                                                   : strArg;
2298
0
            const std::string nameWithoutDash = name.substr(2);
2299
0
            auto iterArg = m_mapLongNameToArg.find(nameWithoutDash);
2300
0
            if (m_arbitraryLongNameArgsAllowed &&
2301
0
                iterArg == m_mapLongNameToArg.end())
2302
0
            {
2303
0
                GetArg(nameWithoutDash);
2304
0
                iterArg = m_mapLongNameToArg.find(nameWithoutDash);
2305
0
            }
2306
0
            if (iterArg == m_mapLongNameToArg.end())
2307
0
            {
2308
0
                const auto suggestions =
2309
0
                    GetSuggestionsForArgumentName(nameWithoutDash);
2310
0
                if (!suggestions.empty())
2311
0
                {
2312
0
                    ReportError(CE_Failure, CPLE_IllegalArg,
2313
0
                                "Option '%s' is unknown. Do you mean %s?",
2314
0
                                name.c_str(),
2315
0
                                FormatSuggestionsAsString(
2316
0
                                    suggestions, /* addDashDashPrefix = */ true)
2317
0
                                    .c_str());
2318
0
                }
2319
0
                else
2320
0
                {
2321
0
                    ReportError(CE_Failure, CPLE_IllegalArg,
2322
0
                                "Option '%s' is unknown.", name.c_str());
2323
0
                }
2324
0
                return false;
2325
0
            }
2326
0
            arg = iterArg->second;
2327
0
            if (equalPos != std::string::npos)
2328
0
            {
2329
0
                hasValue = true;
2330
0
                value = strArg.substr(equalPos + 1);
2331
0
            }
2332
0
        }
2333
0
        else if (strArg.size() >= 2 && strArg[0] == '-' &&
2334
0
                 CPLGetValueType(strArg.c_str()) == CPL_VALUE_STRING)
2335
0
        {
2336
0
            for (size_t j = 1; j < strArg.size(); ++j)
2337
0
            {
2338
0
                name.clear();
2339
0
                name += strArg[j];
2340
0
                const auto iterArg = m_mapShortNameToArg.find(name);
2341
0
                if (iterArg == m_mapShortNameToArg.end())
2342
0
                {
2343
0
                    const std::string nameWithoutDash = strArg.substr(1);
2344
0
                    if (m_mapLongNameToArg.find(nameWithoutDash) !=
2345
0
                        m_mapLongNameToArg.end())
2346
0
                    {
2347
0
                        ReportError(CE_Failure, CPLE_IllegalArg,
2348
0
                                    "Short name option '%s' is unknown. Do you "
2349
0
                                    "mean '--%s' (with leading double dash) ?",
2350
0
                                    name.c_str(), nameWithoutDash.c_str());
2351
0
                    }
2352
0
                    else
2353
0
                    {
2354
0
                        const auto suggestions =
2355
0
                            GetSuggestionsForArgumentName(nameWithoutDash);
2356
0
                        if (!suggestions.empty())
2357
0
                        {
2358
0
                            ReportError(
2359
0
                                CE_Failure, CPLE_IllegalArg,
2360
0
                                "Short name option '%s' is unknown. Do you "
2361
0
                                "mean %s (with leading double dash) ?",
2362
0
                                name.c_str(),
2363
0
                                FormatSuggestionsAsString(
2364
0
                                    suggestions, /* addDashDashPrefix = */ true)
2365
0
                                    .c_str());
2366
0
                        }
2367
0
                        else
2368
0
                        {
2369
0
                            ReportError(CE_Failure, CPLE_IllegalArg,
2370
0
                                        "Short name option '%s' is unknown.",
2371
0
                                        name.c_str());
2372
0
                        }
2373
0
                    }
2374
0
                    return false;
2375
0
                }
2376
0
                arg = iterArg->second;
2377
0
                if (strArg.size() > 2)
2378
0
                {
2379
0
                    if (arg->GetType() != GAAT_BOOLEAN)
2380
0
                    {
2381
0
                        ReportError(CE_Failure, CPLE_IllegalArg,
2382
0
                                    "Invalid argument '%s'. Option '%s' is not "
2383
0
                                    "a boolean option.",
2384
0
                                    strArg.c_str(), name.c_str());
2385
0
                        return false;
2386
0
                    }
2387
2388
0
                    if (!ParseArgument(arg, name, "true", inConstructionValues))
2389
0
                        return false;
2390
0
                }
2391
0
            }
2392
0
            if (strArg.size() > 2)
2393
0
            {
2394
0
                lArgs.erase(lArgs.begin() + i);
2395
0
                continue;
2396
0
            }
2397
0
        }
2398
0
        else
2399
0
        {
2400
0
            ++i;
2401
0
            continue;
2402
0
        }
2403
0
        CPLAssert(arg);
2404
2405
0
        if (arg && arg->GetType() == GAAT_BOOLEAN)
2406
0
        {
2407
0
            if (!hasValue)
2408
0
            {
2409
0
                hasValue = true;
2410
0
                value = "true";
2411
0
            }
2412
0
        }
2413
2414
0
        if (!hasValue)
2415
0
        {
2416
0
            if (i + 1 == lArgs.size())
2417
0
            {
2418
0
                if (m_parseForAutoCompletion)
2419
0
                {
2420
0
                    lArgs.erase(lArgs.begin() + i);
2421
0
                    break;
2422
0
                }
2423
0
                ReportError(
2424
0
                    CE_Failure, CPLE_IllegalArg,
2425
0
                    "Expected value for argument '%s', but ran short of tokens",
2426
0
                    name.c_str());
2427
0
                return false;
2428
0
            }
2429
0
            value = lArgs[i + 1];
2430
0
            lArgs.erase(lArgs.begin() + i + 1);
2431
0
        }
2432
2433
0
        if (arg && !ParseArgument(arg, name, value, inConstructionValues))
2434
0
            return false;
2435
2436
0
        lArgs.erase(lArgs.begin() + i);
2437
0
    }
2438
2439
0
    if (m_specialActionRequested)
2440
0
    {
2441
0
        return true;
2442
0
    }
2443
2444
0
    const auto ProcessInConstructionValues = [&inConstructionValues]()
2445
0
    {
2446
0
        for (auto &[arg, value] : inConstructionValues)
2447
0
        {
2448
0
            if (arg->GetType() == GAAT_STRING_LIST)
2449
0
            {
2450
0
                if (!arg->Set(std::get<std::vector<std::string>>(
2451
0
                        inConstructionValues[arg])))
2452
0
                {
2453
0
                    return false;
2454
0
                }
2455
0
            }
2456
0
            else if (arg->GetType() == GAAT_INTEGER_LIST)
2457
0
            {
2458
0
                if (!arg->Set(
2459
0
                        std::get<std::vector<int>>(inConstructionValues[arg])))
2460
0
                {
2461
0
                    return false;
2462
0
                }
2463
0
            }
2464
0
            else if (arg->GetType() == GAAT_REAL_LIST)
2465
0
            {
2466
0
                if (!arg->Set(std::get<std::vector<double>>(
2467
0
                        inConstructionValues[arg])))
2468
0
                {
2469
0
                    return false;
2470
0
                }
2471
0
            }
2472
0
            else if (arg->GetType() == GAAT_DATASET_LIST)
2473
0
            {
2474
0
                if (!arg->Set(
2475
0
                        std::move(std::get<std::vector<GDALArgDatasetValue>>(
2476
0
                            inConstructionValues[arg]))))
2477
0
                {
2478
0
                    return false;
2479
0
                }
2480
0
            }
2481
0
        }
2482
0
        return true;
2483
0
    };
2484
2485
    // Process positional arguments that have not been set through their
2486
    // option name.
2487
0
    size_t i = 0;
2488
0
    size_t iCurPosArg = 0;
2489
2490
    // Special case for <INPUT> <AUXILIARY>... <OUTPUT>
2491
0
    if (m_positionalArgs.size() == 3 &&
2492
0
        (m_positionalArgs[0]->IsRequired() ||
2493
0
         m_positionalArgs[0]->GetMinCount() == 1) &&
2494
0
        m_positionalArgs[0]->GetMaxCount() == 1 &&
2495
0
        (m_positionalArgs[1]->IsRequired() ||
2496
0
         m_positionalArgs[1]->GetMinCount() == 1) &&
2497
        /* Second argument may have several occurrences */
2498
0
        m_positionalArgs[1]->GetMaxCount() >= 1 &&
2499
0
        (m_positionalArgs[2]->IsRequired() ||
2500
0
         m_positionalArgs[2]->GetMinCount() == 1) &&
2501
0
        m_positionalArgs[2]->GetMaxCount() == 1 &&
2502
0
        !m_positionalArgs[0]->IsExplicitlySet() &&
2503
0
        !m_positionalArgs[1]->IsExplicitlySet() &&
2504
0
        !m_positionalArgs[2]->IsExplicitlySet())
2505
0
    {
2506
0
        if (lArgs.size() - i < 3)
2507
0
        {
2508
0
            ReportError(CE_Failure, CPLE_AppDefined,
2509
0
                        "Not enough positional values.");
2510
0
            return false;
2511
0
        }
2512
0
        bool ok = ParseArgument(m_positionalArgs[0],
2513
0
                                m_positionalArgs[0]->GetName().c_str(),
2514
0
                                lArgs[i], inConstructionValues);
2515
0
        if (ok)
2516
0
        {
2517
0
            ++i;
2518
0
            for (; i + 1 < lArgs.size() && ok; ++i)
2519
0
            {
2520
0
                ok = ParseArgument(m_positionalArgs[1],
2521
0
                                   m_positionalArgs[1]->GetName().c_str(),
2522
0
                                   lArgs[i], inConstructionValues);
2523
0
            }
2524
0
        }
2525
0
        if (ok)
2526
0
        {
2527
0
            ok = ParseArgument(m_positionalArgs[2],
2528
0
                               m_positionalArgs[2]->GetName().c_str(), lArgs[i],
2529
0
                               inConstructionValues);
2530
0
            ++i;
2531
0
        }
2532
0
        if (!ok)
2533
0
        {
2534
0
            ProcessInConstructionValues();
2535
0
            return false;
2536
0
        }
2537
0
    }
2538
2539
0
    if (m_inputDatasetCanBeOmitted && m_positionalArgs.size() >= 1 &&
2540
0
        !m_positionalArgs[0]->IsExplicitlySet() &&
2541
0
        m_positionalArgs[0]->GetName() == GDAL_ARG_NAME_INPUT &&
2542
0
        (m_positionalArgs[0]->GetType() == GAAT_DATASET ||
2543
0
         m_positionalArgs[0]->GetType() == GAAT_DATASET_LIST))
2544
0
    {
2545
0
        ++iCurPosArg;
2546
0
    }
2547
2548
0
    while (i < lArgs.size() && iCurPosArg < m_positionalArgs.size())
2549
0
    {
2550
0
        GDALAlgorithmArg *arg = m_positionalArgs[iCurPosArg];
2551
0
        while (arg->IsExplicitlySet())
2552
0
        {
2553
0
            ++iCurPosArg;
2554
0
            if (iCurPosArg == m_positionalArgs.size())
2555
0
                break;
2556
0
            arg = m_positionalArgs[iCurPosArg];
2557
0
        }
2558
0
        if (iCurPosArg == m_positionalArgs.size())
2559
0
        {
2560
0
            break;
2561
0
        }
2562
0
        if (GDALAlgorithmArgTypeIsList(arg->GetType()) &&
2563
0
            arg->GetMinCount() != arg->GetMaxCount())
2564
0
        {
2565
0
            if (iCurPosArg == 0)
2566
0
            {
2567
0
                size_t nCountAtEnd = 0;
2568
0
                for (size_t j = 1; j < m_positionalArgs.size(); j++)
2569
0
                {
2570
0
                    const auto *otherArg = m_positionalArgs[j];
2571
0
                    if (GDALAlgorithmArgTypeIsList(otherArg->GetType()))
2572
0
                    {
2573
0
                        if (otherArg->GetMinCount() != otherArg->GetMaxCount())
2574
0
                        {
2575
0
                            ReportError(
2576
0
                                CE_Failure, CPLE_AppDefined,
2577
0
                                "Ambiguity in definition of positional "
2578
0
                                "argument "
2579
0
                                "'%s' given it has a varying number of values, "
2580
0
                                "but follows argument '%s' which also has a "
2581
0
                                "varying number of values",
2582
0
                                otherArg->GetName().c_str(),
2583
0
                                arg->GetName().c_str());
2584
0
                            ProcessInConstructionValues();
2585
0
                            return false;
2586
0
                        }
2587
0
                        nCountAtEnd += otherArg->GetMinCount();
2588
0
                    }
2589
0
                    else
2590
0
                    {
2591
0
                        if (!otherArg->IsRequired())
2592
0
                        {
2593
0
                            ReportError(
2594
0
                                CE_Failure, CPLE_AppDefined,
2595
0
                                "Ambiguity in definition of positional "
2596
0
                                "argument "
2597
0
                                "'%s', given it is not required but follows "
2598
0
                                "argument '%s' which has a varying number of "
2599
0
                                "values",
2600
0
                                otherArg->GetName().c_str(),
2601
0
                                arg->GetName().c_str());
2602
0
                            ProcessInConstructionValues();
2603
0
                            return false;
2604
0
                        }
2605
0
                        nCountAtEnd++;
2606
0
                    }
2607
0
                }
2608
0
                if (lArgs.size() < nCountAtEnd)
2609
0
                {
2610
0
                    ReportError(CE_Failure, CPLE_AppDefined,
2611
0
                                "Not enough positional values.");
2612
0
                    ProcessInConstructionValues();
2613
0
                    return false;
2614
0
                }
2615
0
                for (; i < lArgs.size() - nCountAtEnd; ++i)
2616
0
                {
2617
0
                    if (!ParseArgument(arg, arg->GetName().c_str(), lArgs[i],
2618
0
                                       inConstructionValues))
2619
0
                    {
2620
0
                        ProcessInConstructionValues();
2621
0
                        return false;
2622
0
                    }
2623
0
                }
2624
0
            }
2625
0
            else if (iCurPosArg == m_positionalArgs.size() - 1)
2626
0
            {
2627
0
                for (; i < lArgs.size(); ++i)
2628
0
                {
2629
0
                    if (!ParseArgument(arg, arg->GetName().c_str(), lArgs[i],
2630
0
                                       inConstructionValues))
2631
0
                    {
2632
0
                        ProcessInConstructionValues();
2633
0
                        return false;
2634
0
                    }
2635
0
                }
2636
0
            }
2637
0
            else
2638
0
            {
2639
0
                ReportError(CE_Failure, CPLE_AppDefined,
2640
0
                            "Ambiguity in definition of positional arguments: "
2641
0
                            "arguments with varying number of values must be "
2642
0
                            "first or last one.");
2643
0
                return false;
2644
0
            }
2645
0
        }
2646
0
        else
2647
0
        {
2648
0
            if (lArgs.size() - i < static_cast<size_t>(arg->GetMaxCount()))
2649
0
            {
2650
0
                ReportError(CE_Failure, CPLE_AppDefined,
2651
0
                            "Not enough positional values.");
2652
0
                return false;
2653
0
            }
2654
0
            const size_t iMax = i + arg->GetMaxCount();
2655
0
            for (; i < iMax; ++i)
2656
0
            {
2657
0
                if (!ParseArgument(arg, arg->GetName().c_str(), lArgs[i],
2658
0
                                   inConstructionValues))
2659
0
                {
2660
0
                    ProcessInConstructionValues();
2661
0
                    return false;
2662
0
                }
2663
0
            }
2664
0
        }
2665
0
        ++iCurPosArg;
2666
0
    }
2667
2668
0
    if (i < lArgs.size())
2669
0
    {
2670
0
        ReportError(CE_Failure, CPLE_AppDefined,
2671
0
                    "Positional values starting at '%s' are not expected.",
2672
0
                    lArgs[i].c_str());
2673
0
        return false;
2674
0
    }
2675
2676
0
    if (!ProcessInConstructionValues())
2677
0
    {
2678
0
        return false;
2679
0
    }
2680
2681
    // Skip to first unset positional argument.
2682
0
    while (iCurPosArg < m_positionalArgs.size() &&
2683
0
           m_positionalArgs[iCurPosArg]->IsExplicitlySet())
2684
0
    {
2685
0
        ++iCurPosArg;
2686
0
    }
2687
    // Check if this positional argument is required.
2688
0
    if (iCurPosArg < m_positionalArgs.size() && !helpValueRequested &&
2689
0
        (GDALAlgorithmArgTypeIsList(m_positionalArgs[iCurPosArg]->GetType())
2690
0
             ? m_positionalArgs[iCurPosArg]->GetMinCount() > 0
2691
0
             : m_positionalArgs[iCurPosArg]->IsRequired()))
2692
0
    {
2693
0
        ReportError(CE_Failure, CPLE_AppDefined,
2694
0
                    "Positional arguments starting at '%s' have not been "
2695
0
                    "specified.",
2696
0
                    m_positionalArgs[iCurPosArg]->GetMetaVar().c_str());
2697
0
        return false;
2698
0
    }
2699
2700
0
    if (m_calledFromCommandLine)
2701
0
    {
2702
0
        for (auto &arg : m_args)
2703
0
        {
2704
0
            if (arg->IsExplicitlySet() &&
2705
0
                ((arg->GetType() == GAAT_STRING &&
2706
0
                  arg->Get<std::string>() == "?") ||
2707
0
                 (arg->GetType() == GAAT_STRING_LIST &&
2708
0
                  arg->Get<std::vector<std::string>>().size() == 1 &&
2709
0
                  arg->Get<std::vector<std::string>>()[0] == "?")))
2710
0
            {
2711
0
                {
2712
0
                    CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
2713
0
                    ValidateArguments();
2714
0
                }
2715
2716
0
                auto choices = arg->GetChoices();
2717
0
                if (choices.empty())
2718
0
                    choices = arg->GetAutoCompleteChoices(std::string());
2719
0
                if (!choices.empty())
2720
0
                {
2721
0
                    if (choices.size() == 1)
2722
0
                    {
2723
0
                        ReportError(
2724
0
                            CE_Failure, CPLE_AppDefined,
2725
0
                            "Single potential value for argument '%s' is '%s'",
2726
0
                            arg->GetName().c_str(), choices.front().c_str());
2727
0
                    }
2728
0
                    else
2729
0
                    {
2730
0
                        std::string msg("Potential values for argument '");
2731
0
                        msg += arg->GetName();
2732
0
                        msg += "' are:";
2733
0
                        for (const auto &v : choices)
2734
0
                        {
2735
0
                            msg += "\n- ";
2736
0
                            msg += v;
2737
0
                        }
2738
0
                        ReportError(CE_Failure, CPLE_AppDefined, "%s",
2739
0
                                    msg.c_str());
2740
0
                    }
2741
0
                    return false;
2742
0
                }
2743
0
            }
2744
0
        }
2745
0
    }
2746
2747
0
    return m_skipValidationInParseCommandLine || ValidateArguments();
2748
0
}
2749
2750
/************************************************************************/
2751
/*                     GDALAlgorithm::ReportError()                     */
2752
/************************************************************************/
2753
2754
//! @cond Doxygen_Suppress
2755
void GDALAlgorithm::ReportError(CPLErr eErrClass, CPLErrorNum err_no,
2756
                                const char *fmt, ...) const
2757
0
{
2758
0
    va_list args;
2759
0
    va_start(args, fmt);
2760
0
    CPLError(eErrClass, err_no, "%s",
2761
0
             std::string(m_name)
2762
0
                 .append(": ")
2763
0
                 .append(CPLString().vPrintf(fmt, args))
2764
0
                 .c_str());
2765
0
    va_end(args);
2766
0
}
2767
2768
//! @endcond
2769
2770
/************************************************************************/
2771
/*                  GDALAlgorithm::ProcessDatasetArg()                  */
2772
/************************************************************************/
2773
2774
bool GDALAlgorithm::ProcessDatasetArg(GDALAlgorithmArg *arg,
2775
                                      GDALAlgorithm *algForOutput)
2776
0
{
2777
0
    bool ret = true;
2778
2779
0
    const auto updateArg = algForOutput->GetArg(GDAL_ARG_NAME_UPDATE);
2780
0
    const bool hasUpdateArg = updateArg && updateArg->GetType() == GAAT_BOOLEAN;
2781
0
    const bool update = hasUpdateArg && updateArg->Get<bool>();
2782
2783
0
    const auto appendArg = algForOutput->GetArg(GDAL_ARG_NAME_APPEND);
2784
0
    const bool hasAppendArg = appendArg && appendArg->GetType() == GAAT_BOOLEAN;
2785
0
    const bool append = hasAppendArg && appendArg->Get<bool>();
2786
2787
0
    const auto overwriteArg = algForOutput->GetArg(GDAL_ARG_NAME_OVERWRITE);
2788
0
    const bool overwrite =
2789
0
        (arg->IsOutput() && overwriteArg &&
2790
0
         overwriteArg->GetType() == GAAT_BOOLEAN && overwriteArg->Get<bool>());
2791
2792
0
    auto outputArg = algForOutput->GetArg(GDAL_ARG_NAME_OUTPUT);
2793
0
    auto &val = [arg]() -> GDALArgDatasetValue &
2794
0
    {
2795
0
        if (arg->GetType() == GAAT_DATASET_LIST)
2796
0
            return arg->Get<std::vector<GDALArgDatasetValue>>()[0];
2797
0
        else
2798
0
            return arg->Get<GDALArgDatasetValue>();
2799
0
    }();
2800
0
    const bool onlyInputSpecifiedInUpdateAndOutputNotRequired =
2801
0
        arg->GetName() == GDAL_ARG_NAME_INPUT && outputArg &&
2802
0
        !outputArg->IsExplicitlySet() && !outputArg->IsRequired() && update &&
2803
0
        !overwrite;
2804
2805
    // Used for nested pipelines
2806
0
    const auto oIterDatasetNameToDataset =
2807
0
        val.IsNameSet() ? m_oMapDatasetNameToDataset.find(val.GetName())
2808
0
                        : m_oMapDatasetNameToDataset.end();
2809
2810
0
    if (!val.GetDatasetRef() && !val.IsNameSet())
2811
0
    {
2812
0
        ReportError(CE_Failure, CPLE_AppDefined,
2813
0
                    "Argument '%s' has no dataset object or dataset name.",
2814
0
                    arg->GetName().c_str());
2815
0
        ret = false;
2816
0
    }
2817
0
    else if (val.GetDatasetRef() && !CheckCanSetDatasetObject(arg))
2818
0
    {
2819
0
        return false;
2820
0
    }
2821
0
    else if (m_inputDatasetCanBeOmitted &&
2822
0
             val.GetName() == GDAL_DATASET_PIPELINE_PLACEHOLDER_VALUE &&
2823
0
             !arg->IsOutput())
2824
0
    {
2825
0
        return true;
2826
0
    }
2827
0
    else if (!val.GetDatasetRef() &&
2828
0
             (arg->AutoOpenDataset() ||
2829
0
              oIterDatasetNameToDataset != m_oMapDatasetNameToDataset.end()) &&
2830
0
             (!arg->IsOutput() || (arg == outputArg && update && !overwrite) ||
2831
0
              onlyInputSpecifiedInUpdateAndOutputNotRequired))
2832
0
    {
2833
0
        int flags = arg->GetDatasetType();
2834
0
        bool assignToOutputArg = false;
2835
2836
        // Check if input and output parameters point to the same
2837
        // filename (for vector datasets)
2838
0
        if (arg->GetName() == GDAL_ARG_NAME_INPUT && update && !overwrite &&
2839
0
            outputArg && outputArg->GetType() == GAAT_DATASET)
2840
0
        {
2841
0
            auto &outputVal = outputArg->Get<GDALArgDatasetValue>();
2842
0
            if (!outputVal.GetDatasetRef() &&
2843
0
                outputVal.GetName() == val.GetName() &&
2844
0
                (outputArg->GetDatasetInputFlags() & GADV_OBJECT) != 0)
2845
0
            {
2846
0
                assignToOutputArg = true;
2847
0
                flags |= GDAL_OF_UPDATE | GDAL_OF_VERBOSE_ERROR;
2848
0
            }
2849
0
            else if (onlyInputSpecifiedInUpdateAndOutputNotRequired)
2850
0
            {
2851
0
                flags |= GDAL_OF_UPDATE | GDAL_OF_VERBOSE_ERROR;
2852
0
            }
2853
0
        }
2854
2855
0
        if (!arg->IsOutput() || arg->GetDatasetInputFlags() == GADV_NAME)
2856
0
            flags |= GDAL_OF_VERBOSE_ERROR;
2857
0
        if ((arg == outputArg || !outputArg) && update)
2858
0
        {
2859
0
            flags |= GDAL_OF_UPDATE;
2860
0
            if (!append)
2861
0
                flags |= GDAL_OF_VERBOSE_ERROR;
2862
0
        }
2863
2864
0
        const auto readOnlyArg = GetArg(GDAL_ARG_NAME_READ_ONLY);
2865
0
        const bool readOnly =
2866
0
            (readOnlyArg && readOnlyArg->GetType() == GAAT_BOOLEAN &&
2867
0
             readOnlyArg->Get<bool>());
2868
0
        if (readOnly)
2869
0
            flags &= ~GDAL_OF_UPDATE;
2870
2871
0
        CPLStringList aosOpenOptions;
2872
0
        CPLStringList aosAllowedDrivers;
2873
0
        if (arg->IsInput())
2874
0
        {
2875
0
            if (arg == outputArg)
2876
0
            {
2877
0
                if (update && !overwrite)
2878
0
                {
2879
0
                    const auto ooArg = GetArg(GDAL_ARG_NAME_OUTPUT_OPEN_OPTION);
2880
0
                    if (ooArg && ooArg->GetType() == GAAT_STRING_LIST)
2881
0
                        aosOpenOptions = CPLStringList(
2882
0
                            ooArg->Get<std::vector<std::string>>());
2883
0
                }
2884
0
            }
2885
0
            else
2886
0
            {
2887
0
                const auto ooArg = GetArg(GDAL_ARG_NAME_OPEN_OPTION);
2888
0
                if (ooArg && ooArg->GetType() == GAAT_STRING_LIST)
2889
0
                    aosOpenOptions =
2890
0
                        CPLStringList(ooArg->Get<std::vector<std::string>>());
2891
2892
0
                const auto ifArg = GetArg(GDAL_ARG_NAME_INPUT_FORMAT);
2893
0
                if (ifArg && ifArg->GetType() == GAAT_STRING_LIST)
2894
0
                    aosAllowedDrivers =
2895
0
                        CPLStringList(ifArg->Get<std::vector<std::string>>());
2896
0
            }
2897
0
        }
2898
2899
0
        std::string osDatasetName = val.GetName();
2900
0
        if (!m_referencePath.empty())
2901
0
        {
2902
0
            osDatasetName = GDALDataset::BuildFilename(
2903
0
                osDatasetName.c_str(), m_referencePath.c_str(), true);
2904
0
        }
2905
0
        if (osDatasetName == "-" && (flags & GDAL_OF_UPDATE) == 0)
2906
0
            osDatasetName = "/vsistdin/";
2907
2908
        // Handle special case of overview delete in GTiff which would fail
2909
        // if it is COG without IGNORE_COG_LAYOUT_BREAK=YES open option.
2910
0
        if ((flags & GDAL_OF_UPDATE) != 0 && m_callPath.size() == 4 &&
2911
0
            m_callPath[2] == "overview" && m_callPath[3] == "delete" &&
2912
0
            aosOpenOptions.FetchNameValue("IGNORE_COG_LAYOUT_BREAK") == nullptr)
2913
0
        {
2914
0
            CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
2915
0
            GDALDriverH hDrv =
2916
0
                GDALIdentifyDriver(osDatasetName.c_str(), nullptr);
2917
0
            if (hDrv && EQUAL(GDALGetDescription(hDrv), "GTiff"))
2918
0
            {
2919
                // Cleaning does not break COG layout
2920
0
                aosOpenOptions.SetNameValue("IGNORE_COG_LAYOUT_BREAK", "YES");
2921
0
            }
2922
0
        }
2923
2924
0
        GDALDataset *poDS;
2925
0
        CPLErrorAccumulator oAccumulator;
2926
0
        {
2927
0
            auto oContext = oAccumulator.InstallForCurrentScope();
2928
2929
0
            poDS = oIterDatasetNameToDataset != m_oMapDatasetNameToDataset.end()
2930
0
                       ? oIterDatasetNameToDataset->second
2931
0
                       : GDALDataset::Open(osDatasetName.c_str(), flags,
2932
0
                                           aosAllowedDrivers.List(),
2933
0
                                           aosOpenOptions.List());
2934
2935
0
            if (!poDS && aosAllowedDrivers.empty() && aosOpenOptions.empty() &&
2936
0
                !arg->IsOutput() && arg->GetDatasetType() & GDAL_OF_VECTOR)
2937
0
            {
2938
0
                auto [poWktGeom, eErr] = OGRGeometryFactory::createFromWkt(
2939
0
                    osDatasetName.c_str(), nullptr);
2940
0
                if (eErr == OGRERR_NONE)
2941
0
                {
2942
0
                    auto poMemDS = std::make_unique<MEMDataset>();
2943
0
                    auto *poLayer = poMemDS->CreateLayer(
2944
0
                        "layer", poWktGeom->getSpatialReference(),
2945
0
                        poWktGeom->getGeometryType());
2946
2947
0
                    auto poFeatureDefn = poLayer->GetLayerDefn();
2948
0
                    OGRFeature oFeature(poFeatureDefn);
2949
2950
0
                    oFeature.SetGeometry(std::move(poWktGeom));
2951
0
                    if (poLayer->CreateFeature(&oFeature) == OGRERR_NONE)
2952
0
                    {
2953
0
                        poDS = poMemDS.release();
2954
0
                        oAccumulator.ClearErrors();
2955
0
                    }
2956
0
                }
2957
0
            }
2958
2959
            // Retry with PostGIS vector driver
2960
0
            if (!poDS && (flags & (GDAL_OF_RASTER | GDAL_OF_VECTOR)) != 0 &&
2961
0
                cpl::starts_with(osDatasetName, "PG:") &&
2962
0
                GetGDALDriverManager()->GetDriverByName("PostGISRaster") &&
2963
0
                aosAllowedDrivers.empty() && aosOpenOptions.empty())
2964
0
            {
2965
0
                oAccumulator.ClearErrors();
2966
0
                poDS = GDALDataset::Open(
2967
0
                    osDatasetName.c_str(), flags & ~GDAL_OF_RASTER,
2968
0
                    aosAllowedDrivers.List(), aosOpenOptions.List());
2969
0
            }
2970
0
        }
2971
0
        oAccumulator.ReplayErrors();
2972
2973
0
        if (poDS)
2974
0
        {
2975
0
            if (oIterDatasetNameToDataset != m_oMapDatasetNameToDataset.end())
2976
0
            {
2977
0
                if (arg->GetType() == GAAT_DATASET)
2978
0
                    arg->Get<GDALArgDatasetValue>().Set(poDS->GetDescription());
2979
0
                poDS->Reference();
2980
0
                m_oMapDatasetNameToDataset.erase(oIterDatasetNameToDataset);
2981
0
            }
2982
2983
            // A bit of a hack for situations like 'gdal raster clip --like "PG:..."'
2984
            // where the PG: dataset will be first opened with the PostGISRaster
2985
            // driver whereas the PostgreSQL (vector) one is actually wanted.
2986
0
            if (poDS->GetRasterCount() == 0 && (flags & GDAL_OF_RASTER) != 0 &&
2987
0
                (flags & GDAL_OF_VECTOR) != 0 && aosAllowedDrivers.empty() &&
2988
0
                aosOpenOptions.empty())
2989
0
            {
2990
0
                auto poDrv = poDS->GetDriver();
2991
0
                if (poDrv && EQUAL(poDrv->GetDescription(), "PostGISRaster"))
2992
0
                {
2993
                    // Retry with PostgreSQL (vector) driver
2994
0
                    std::unique_ptr<GDALDataset> poTmpDS(GDALDataset::Open(
2995
0
                        osDatasetName.c_str(), flags & ~GDAL_OF_RASTER));
2996
0
                    if (poTmpDS)
2997
0
                    {
2998
0
                        poDS->ReleaseRef();
2999
0
                        poDS = poTmpDS.release();
3000
0
                    }
3001
0
                }
3002
0
            }
3003
3004
0
            if (assignToOutputArg)
3005
0
            {
3006
                // Avoid opening twice the same datasource if it is both
3007
                // the input and output.
3008
                // Known to cause problems with at least FGdb, SQLite
3009
                // and GPKG drivers. See #4270
3010
                // Restrict to those 3 drivers. For example it is known
3011
                // to break with the PG driver due to the way it
3012
                // manages transactions.
3013
0
                auto poDriver = poDS->GetDriver();
3014
0
                if (poDriver && (EQUAL(poDriver->GetDescription(), "FileGDB") ||
3015
0
                                 EQUAL(poDriver->GetDescription(), "SQLite") ||
3016
0
                                 EQUAL(poDriver->GetDescription(), "GPKG")))
3017
0
                {
3018
0
                    outputArg->Get<GDALArgDatasetValue>().Set(poDS);
3019
0
                }
3020
0
            }
3021
0
            val.SetDatasetOpenedByAlgorithm();
3022
0
            val.Set(poDS);
3023
0
            poDS->ReleaseRef();
3024
0
        }
3025
0
        else if (!append)
3026
0
        {
3027
0
            ret = false;
3028
0
        }
3029
0
    }
3030
3031
    // Deal with overwriting the output dataset
3032
0
    if (ret && arg == outputArg && val.GetDatasetRef() == nullptr)
3033
0
    {
3034
0
        if (!append)
3035
0
        {
3036
            // If outputting to MEM, do not try to erase a real file of the same name!
3037
0
            const auto outputFormatArg =
3038
0
                algForOutput->GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
3039
0
            if (!(outputFormatArg &&
3040
0
                  outputFormatArg->GetType() == GAAT_STRING &&
3041
0
                  (EQUAL(outputFormatArg->Get<std::string>().c_str(), "MEM") ||
3042
0
                   EQUAL(outputFormatArg->Get<std::string>().c_str(),
3043
0
                         "stream") ||
3044
0
                   EQUAL(outputFormatArg->Get<std::string>().c_str(),
3045
0
                         "Memory"))))
3046
0
            {
3047
0
                const char *pszType = "";
3048
0
                GDALDriver *poDriver = nullptr;
3049
0
                if (!val.GetName().empty() &&
3050
0
                    GDALDoesFileOrDatasetExist(val.GetName().c_str(), &pszType,
3051
0
                                               &poDriver))
3052
0
                {
3053
0
                    if (!overwrite)
3054
0
                    {
3055
0
                        std::string options;
3056
0
                        if (algForOutput->GetArg(GDAL_ARG_NAME_OVERWRITE_LAYER))
3057
0
                        {
3058
0
                            options += "--";
3059
0
                            options += GDAL_ARG_NAME_OVERWRITE_LAYER;
3060
0
                        }
3061
0
                        if (hasAppendArg)
3062
0
                        {
3063
0
                            if (!options.empty())
3064
0
                                options += '/';
3065
0
                            options += "--";
3066
0
                            options += GDAL_ARG_NAME_APPEND;
3067
0
                        }
3068
0
                        if (hasUpdateArg)
3069
0
                        {
3070
0
                            if (!options.empty())
3071
0
                                options += '/';
3072
0
                            options += "--";
3073
0
                            options += GDAL_ARG_NAME_UPDATE;
3074
0
                        }
3075
3076
0
                        if (poDriver)
3077
0
                        {
3078
0
                            const char *pszPrefix = poDriver->GetMetadataItem(
3079
0
                                GDAL_DMD_CONNECTION_PREFIX);
3080
0
                            if (pszPrefix &&
3081
0
                                STARTS_WITH_CI(val.GetName().c_str(),
3082
0
                                               pszPrefix))
3083
0
                            {
3084
0
                                bool bExists = false;
3085
0
                                {
3086
0
                                    CPLErrorStateBackuper oBackuper(
3087
0
                                        CPLQuietErrorHandler);
3088
0
                                    bExists = std::unique_ptr<GDALDataset>(
3089
0
                                                  GDALDataset::Open(
3090
0
                                                      val.GetName().c_str())) !=
3091
0
                                              nullptr;
3092
0
                                }
3093
0
                                if (bExists)
3094
0
                                {
3095
0
                                    if (!options.empty())
3096
0
                                        options = " You may specify the " +
3097
0
                                                  options + " option.";
3098
0
                                    ReportError(CE_Failure, CPLE_AppDefined,
3099
0
                                                "%s '%s' already exists.%s",
3100
0
                                                pszType, val.GetName().c_str(),
3101
0
                                                options.c_str());
3102
0
                                    return false;
3103
0
                                }
3104
3105
0
                                return true;
3106
0
                            }
3107
0
                        }
3108
3109
0
                        if (!options.empty())
3110
0
                            options = '/' + options;
3111
0
                        ReportError(
3112
0
                            CE_Failure, CPLE_AppDefined,
3113
0
                            "%s '%s' already exists. You may specify the "
3114
0
                            "--overwrite%s option.",
3115
0
                            pszType, val.GetName().c_str(), options.c_str());
3116
0
                        return false;
3117
0
                    }
3118
0
                    else if (EQUAL(pszType, "File"))
3119
0
                    {
3120
0
                        if (VSIUnlink(val.GetName().c_str()) != 0)
3121
0
                        {
3122
0
                            ReportError(CE_Failure, CPLE_AppDefined,
3123
0
                                        "Deleting %s failed: %s",
3124
0
                                        val.GetName().c_str(),
3125
0
                                        VSIStrerror(errno));
3126
0
                            return false;
3127
0
                        }
3128
0
                    }
3129
0
                    else if (EQUAL(pszType, "Directory"))
3130
0
                    {
3131
                        // We don't want the user to accidentally erase a non-GDAL dataset
3132
0
                        ReportError(CE_Failure, CPLE_AppDefined,
3133
0
                                    "Directory '%s' already exists, but is not "
3134
0
                                    "recognized as a valid GDAL dataset. "
3135
0
                                    "Please manually delete it before retrying",
3136
0
                                    val.GetName().c_str());
3137
0
                        return false;
3138
0
                    }
3139
0
                    else if (poDriver)
3140
0
                    {
3141
0
                        bool bDeleteOK;
3142
0
                        {
3143
0
                            CPLErrorStateBackuper oBackuper(
3144
0
                                CPLQuietErrorHandler);
3145
0
                            bDeleteOK = (poDriver->Delete(
3146
0
                                             val.GetName().c_str()) == CE_None);
3147
0
                        }
3148
0
                        VSIStatBufL sStat;
3149
0
                        if (!bDeleteOK &&
3150
0
                            VSIStatL(val.GetName().c_str(), &sStat) == 0)
3151
0
                        {
3152
0
                            if (VSI_ISDIR(sStat.st_mode))
3153
0
                            {
3154
                                // We don't want the user to accidentally erase a non-GDAL dataset
3155
0
                                ReportError(
3156
0
                                    CE_Failure, CPLE_AppDefined,
3157
0
                                    "Directory '%s' already exists, but is not "
3158
0
                                    "recognized as a valid GDAL dataset. "
3159
0
                                    "Please manually delete it before retrying",
3160
0
                                    val.GetName().c_str());
3161
0
                                return false;
3162
0
                            }
3163
0
                            else if (VSIUnlink(val.GetName().c_str()) != 0)
3164
0
                            {
3165
0
                                ReportError(CE_Failure, CPLE_AppDefined,
3166
0
                                            "Deleting %s failed: %s",
3167
0
                                            val.GetName().c_str(),
3168
0
                                            VSIStrerror(errno));
3169
0
                                return false;
3170
0
                            }
3171
0
                        }
3172
0
                    }
3173
0
                }
3174
0
            }
3175
0
        }
3176
0
    }
3177
3178
    // If outputting to stdout, automatically turn off progress bar
3179
0
    if (arg == outputArg && val.GetName() == "/vsistdout/")
3180
0
    {
3181
0
        auto quietArg = GetArg(GDAL_ARG_NAME_QUIET);
3182
0
        if (quietArg && quietArg->GetType() == GAAT_BOOLEAN)
3183
0
            quietArg->Set(true);
3184
0
    }
3185
3186
0
    return ret;
3187
0
}
3188
3189
/************************************************************************/
3190
/*                  GDALAlgorithm::ValidateArguments()                  */
3191
/************************************************************************/
3192
3193
bool GDALAlgorithm::ValidateArguments()
3194
0
{
3195
0
    if (m_selectedSubAlg)
3196
0
        return m_selectedSubAlg->ValidateArguments();
3197
3198
0
    if (m_specialActionRequested)
3199
0
        return true;
3200
3201
0
    m_arbitraryLongNameArgsAllowed = false;
3202
3203
    // If only --output=format=MEM/stream is specified and not --output,
3204
    // then set empty name for --output.
3205
0
    auto outputArg = GetArg(GDAL_ARG_NAME_OUTPUT);
3206
0
    auto outputFormatArg = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
3207
0
    if (outputArg && outputFormatArg && outputFormatArg->IsExplicitlySet() &&
3208
0
        !outputArg->IsExplicitlySet() &&
3209
0
        outputFormatArg->GetType() == GAAT_STRING &&
3210
0
        (EQUAL(outputFormatArg->Get<std::string>().c_str(), "MEM") ||
3211
0
         EQUAL(outputFormatArg->Get<std::string>().c_str(), "stream")) &&
3212
0
        outputArg->GetType() == GAAT_DATASET &&
3213
0
        (outputArg->GetDatasetInputFlags() & GADV_NAME))
3214
0
    {
3215
0
        outputArg->Get<GDALArgDatasetValue>().Set("");
3216
0
    }
3217
3218
    // The method may emit several errors if several constraints are not met.
3219
0
    bool ret = true;
3220
0
    std::map<std::string, std::string> mutualExclusionGroupUsed;
3221
0
    std::map<std::string, std::vector<std::string>> mutualDependencyGroupUsed;
3222
0
    for (auto &arg : m_args)
3223
0
    {
3224
        // Check mutually exclusive/dependent arguments
3225
0
        if (arg->IsExplicitlySet())
3226
0
        {
3227
3228
0
            const auto &mutualExclusionGroup = arg->GetMutualExclusionGroup();
3229
0
            if (!mutualExclusionGroup.empty())
3230
0
            {
3231
0
                auto oIter =
3232
0
                    mutualExclusionGroupUsed.find(mutualExclusionGroup);
3233
0
                if (oIter != mutualExclusionGroupUsed.end())
3234
0
                {
3235
0
                    ret = false;
3236
0
                    ReportError(
3237
0
                        CE_Failure, CPLE_AppDefined,
3238
0
                        "Argument '%s' is mutually exclusive with '%s'.",
3239
0
                        arg->GetName().c_str(), oIter->second.c_str());
3240
0
                }
3241
0
                else
3242
0
                {
3243
0
                    mutualExclusionGroupUsed[mutualExclusionGroup] =
3244
0
                        arg->GetName();
3245
0
                }
3246
0
            }
3247
3248
0
            const auto &mutualDependencyGroup = arg->GetMutualDependencyGroup();
3249
0
            if (!mutualDependencyGroup.empty())
3250
0
            {
3251
0
                if (mutualDependencyGroupUsed.find(mutualDependencyGroup) ==
3252
0
                    mutualDependencyGroupUsed.end())
3253
0
                {
3254
0
                    mutualDependencyGroupUsed[mutualDependencyGroup] = {
3255
0
                        arg->GetName()};
3256
0
                }
3257
0
                else
3258
0
                {
3259
0
                    mutualDependencyGroupUsed[mutualDependencyGroup].push_back(
3260
0
                        arg->GetName());
3261
0
                }
3262
0
            }
3263
3264
            // Check direct dependencies
3265
0
            for (const auto &dependency : arg->GetDirectDependencies())
3266
0
            {
3267
0
                auto depArg = GetArg(dependency);
3268
0
                if (!depArg)
3269
0
                {
3270
0
                    ret = false;
3271
0
                    ReportError(CE_Failure, CPLE_AppDefined,
3272
0
                                "Argument '%s' depends on argument '%s' that "
3273
0
                                "is not defined.",
3274
0
                                arg->GetName().c_str(), dependency.c_str());
3275
0
                }
3276
0
                else if (!depArg->IsExplicitlySet())
3277
0
                {
3278
0
                    ret = false;
3279
0
                    ReportError(CE_Failure, CPLE_AppDefined,
3280
0
                                "Argument '%s' depends on argument '%s' that "
3281
0
                                "has not been specified.",
3282
0
                                arg->GetName().c_str(),
3283
0
                                depArg->GetName().c_str());
3284
0
                }
3285
0
            }
3286
0
        }
3287
3288
0
        if (arg->IsRequired() && !arg->IsExplicitlySet() &&
3289
0
            !arg->HasDefaultValue())
3290
0
        {
3291
0
            bool emitError = true;
3292
0
            const auto &mutualExclusionGroup = arg->GetMutualExclusionGroup();
3293
0
            if (!mutualExclusionGroup.empty())
3294
0
            {
3295
0
                for (const auto &otherArg : m_args)
3296
0
                {
3297
0
                    if (otherArg->GetMutualExclusionGroup() ==
3298
0
                            mutualExclusionGroup &&
3299
0
                        otherArg->IsExplicitlySet())
3300
0
                    {
3301
0
                        emitError = false;
3302
0
                        break;
3303
0
                    }
3304
0
                }
3305
0
            }
3306
0
            if (emitError && !(m_inputDatasetCanBeOmitted &&
3307
0
                               arg->GetName() == GDAL_ARG_NAME_INPUT &&
3308
0
                               (arg->GetType() == GAAT_DATASET ||
3309
0
                                arg->GetType() == GAAT_DATASET_LIST)))
3310
0
            {
3311
0
                ReportError(CE_Failure, CPLE_AppDefined,
3312
0
                            "Required argument '%s' has not been specified.",
3313
0
                            arg->GetName().c_str());
3314
0
                ret = false;
3315
0
            }
3316
0
        }
3317
0
        else if (arg->IsExplicitlySet() && arg->GetType() == GAAT_DATASET)
3318
0
        {
3319
0
            if (!ProcessDatasetArg(arg.get(), this))
3320
0
                ret = false;
3321
0
        }
3322
3323
0
        if (arg->IsExplicitlySet() && arg->GetType() == GAAT_DATASET_LIST)
3324
0
        {
3325
0
            auto &listVal = arg->Get<std::vector<GDALArgDatasetValue>>();
3326
0
            if (listVal.size() == 1)
3327
0
            {
3328
0
                if (!ProcessDatasetArg(arg.get(), this))
3329
0
                    ret = false;
3330
0
            }
3331
0
            else
3332
0
            {
3333
0
                for (auto &val : listVal)
3334
0
                {
3335
0
                    if (val.GetDatasetRef())
3336
0
                    {
3337
0
                        if (!CheckCanSetDatasetObject(arg.get()))
3338
0
                        {
3339
0
                            ret = false;
3340
0
                        }
3341
0
                        continue;
3342
0
                    }
3343
3344
0
                    if (val.GetName().empty())
3345
0
                    {
3346
0
                        ReportError(CE_Failure, CPLE_AppDefined,
3347
0
                                    "Argument '%s' has no dataset object or "
3348
0
                                    "dataset name.",
3349
0
                                    arg->GetName().c_str());
3350
0
                        ret = false;
3351
0
                        continue;
3352
0
                    }
3353
3354
0
                    auto oIter = m_oMapDatasetNameToDataset.find(val.GetName());
3355
0
                    if (oIter != m_oMapDatasetNameToDataset.end())
3356
0
                    {
3357
0
                        auto poDS = oIter->second;
3358
0
                        val.SetDatasetOpenedByAlgorithm();
3359
0
                        val.Set(poDS);
3360
0
                        m_oMapDatasetNameToDataset.erase(oIter);
3361
0
                        continue;
3362
0
                    }
3363
3364
0
                    if (!arg->AutoOpenDataset())
3365
0
                        continue;
3366
3367
0
                    int flags = arg->GetDatasetType() | GDAL_OF_VERBOSE_ERROR;
3368
3369
0
                    CPLStringList aosOpenOptions;
3370
0
                    CPLStringList aosAllowedDrivers;
3371
0
                    if (arg->GetName() == GDAL_ARG_NAME_INPUT)
3372
0
                    {
3373
0
                        const auto ooArg = GetArg(GDAL_ARG_NAME_OPEN_OPTION);
3374
0
                        if (ooArg && ooArg->GetType() == GAAT_STRING_LIST)
3375
0
                        {
3376
0
                            aosOpenOptions = CPLStringList(
3377
0
                                ooArg->Get<std::vector<std::string>>());
3378
0
                        }
3379
3380
0
                        const auto ifArg = GetArg(GDAL_ARG_NAME_INPUT_FORMAT);
3381
0
                        if (ifArg && ifArg->GetType() == GAAT_STRING_LIST)
3382
0
                        {
3383
0
                            aosAllowedDrivers = CPLStringList(
3384
0
                                ifArg->Get<std::vector<std::string>>());
3385
0
                        }
3386
3387
0
                        const auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
3388
0
                        if (updateArg && updateArg->GetType() == GAAT_BOOLEAN &&
3389
0
                            updateArg->Get<bool>())
3390
0
                        {
3391
0
                            flags |= GDAL_OF_UPDATE;
3392
0
                        }
3393
0
                    }
3394
3395
0
                    auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
3396
0
                        val.GetName().c_str(), flags, aosAllowedDrivers.List(),
3397
0
                        aosOpenOptions.List()));
3398
0
                    if (poDS)
3399
0
                    {
3400
0
                        val.Set(std::move(poDS));
3401
0
                    }
3402
0
                    else
3403
0
                    {
3404
0
                        ret = false;
3405
0
                    }
3406
0
                }
3407
0
            }
3408
0
        }
3409
3410
0
        if (arg->IsExplicitlySet() && !arg->RunValidationActions())
3411
0
        {
3412
0
            ret = false;
3413
0
        }
3414
0
    }
3415
3416
    // Check mutual dependency groups
3417
0
    std::vector<std::string> processedGroups;
3418
    // Loop through group map and check there are not required args in the group that are not set
3419
0
    for (const auto &[groupName, argNames] : mutualDependencyGroupUsed)
3420
0
    {
3421
0
        if (std::find(processedGroups.begin(), processedGroups.end(),
3422
0
                      groupName) != processedGroups.end())
3423
0
            continue;
3424
0
        std::vector<std::string> missingArgs;
3425
0
        for (auto &arg : m_args)
3426
0
        {
3427
0
            const auto &mutualDependencyGroup = arg->GetMutualDependencyGroup();
3428
0
            if (mutualDependencyGroup == groupName &&
3429
0
                std::find(argNames.begin(), argNames.end(), arg->GetName()) ==
3430
0
                    argNames.end())
3431
0
            {
3432
0
                missingArgs.push_back(arg->GetName());
3433
0
            }
3434
0
        }
3435
0
        if (!missingArgs.empty())
3436
0
        {
3437
0
            ret = false;
3438
0
            std::string missingArgsStr;
3439
0
            for (const auto &missingArg : missingArgs)
3440
0
            {
3441
0
                if (!missingArgsStr.empty())
3442
0
                    missingArgsStr += ", ";
3443
0
                missingArgsStr += missingArg;
3444
0
            }
3445
0
            std::string givenArgsStr;
3446
0
            for (const auto &givenArg : argNames)
3447
0
            {
3448
0
                if (!givenArgsStr.empty())
3449
0
                    givenArgsStr += ", ";
3450
0
                givenArgsStr += givenArg;
3451
0
            }
3452
0
            ReportError(CE_Failure, CPLE_AppDefined,
3453
0
                        "Argument(s) '%s' require(s) that the following "
3454
0
                        "argument(s) are also specified: %s.",
3455
0
                        givenArgsStr.c_str(), missingArgsStr.c_str());
3456
0
        }
3457
0
        processedGroups.push_back(groupName);
3458
0
    }
3459
3460
0
    for (const auto &f : m_validationActions)
3461
0
    {
3462
0
        if (!f())
3463
0
            ret = false;
3464
0
    }
3465
3466
0
    return ret;
3467
0
}
3468
3469
/************************************************************************/
3470
/*                GDALAlgorithm::InstantiateSubAlgorithm                */
3471
/************************************************************************/
3472
3473
std::unique_ptr<GDALAlgorithm>
3474
GDALAlgorithm::InstantiateSubAlgorithm(const std::string &name,
3475
                                       bool suggestionAllowed) const
3476
0
{
3477
0
    auto ret = m_subAlgRegistry.Instantiate(name);
3478
0
    auto childCallPath = m_callPath;
3479
0
    childCallPath.push_back(name);
3480
0
    if (!ret)
3481
0
    {
3482
0
        ret = GDALGlobalAlgorithmRegistry::GetSingleton()
3483
0
                  .InstantiateDeclaredSubAlgorithm(childCallPath);
3484
0
    }
3485
0
    if (ret)
3486
0
    {
3487
0
        ret->SetCallPath(childCallPath);
3488
0
    }
3489
0
    else if (suggestionAllowed)
3490
0
    {
3491
0
        std::string bestCandidate;
3492
0
        size_t bestDistance = std::numeric_limits<size_t>::max();
3493
0
        for (const std::string &candidate : GetSubAlgorithmNames())
3494
0
        {
3495
0
            const size_t distance =
3496
0
                CPLLevenshteinDistance(name.c_str(), candidate.c_str(),
3497
0
                                       /* transpositionAllowed = */ true);
3498
0
            if (distance < bestDistance)
3499
0
            {
3500
0
                bestCandidate = candidate;
3501
0
                bestDistance = distance;
3502
0
            }
3503
0
            else if (distance == bestDistance)
3504
0
            {
3505
0
                bestCandidate.clear();
3506
0
            }
3507
0
        }
3508
0
        if (!bestCandidate.empty() && bestDistance <= 2)
3509
0
        {
3510
0
            CPLError(CE_Failure, CPLE_AppDefined,
3511
0
                     "Algorithm '%s' is unknown. Do you mean '%s'?",
3512
0
                     name.c_str(), bestCandidate.c_str());
3513
0
        }
3514
0
    }
3515
0
    return ret;
3516
0
}
3517
3518
/************************************************************************/
3519
/*            GDALAlgorithm::GetSuggestionForArgumentName()             */
3520
/************************************************************************/
3521
3522
std::string
3523
GDALAlgorithm::GetSuggestionForArgumentName(const std::string &osName) const
3524
0
{
3525
0
    if (osName.size() >= 3)
3526
0
    {
3527
0
        std::string bestCandidate;
3528
0
        size_t bestDistance = std::numeric_limits<size_t>::max();
3529
0
        for (const auto &[key, value] : m_mapLongNameToArg)
3530
0
        {
3531
0
            CPL_IGNORE_RET_VAL(value);
3532
0
            const size_t distance = CPLLevenshteinDistance(
3533
0
                osName.c_str(), key.c_str(), /* transpositionAllowed = */ true);
3534
0
            if (distance < bestDistance)
3535
0
            {
3536
0
                bestCandidate = key;
3537
0
                bestDistance = distance;
3538
0
            }
3539
0
            else if (distance == bestDistance)
3540
0
            {
3541
0
                bestCandidate.clear();
3542
0
            }
3543
0
        }
3544
0
        if (!bestCandidate.empty() &&
3545
0
            bestDistance <= (bestCandidate.size() >= 4U ? 2U : 1U))
3546
0
        {
3547
0
            return bestCandidate;
3548
0
        }
3549
0
    }
3550
0
    return std::string();
3551
0
}
3552
3553
/************************************************************************/
3554
/*            GDALAlgorithm::GetSuggestionsForArgumentName()            */
3555
/************************************************************************/
3556
3557
std::vector<std::string>
3558
GDALAlgorithm::GetSuggestionsForArgumentName(const std::string &osName) const
3559
0
{
3560
0
    std::vector<std::string> ret;
3561
0
    std::string suggestion = GetSuggestionForArgumentName(osName);
3562
0
    if (!suggestion.empty())
3563
0
    {
3564
0
        ret.push_back(std::move(suggestion));
3565
0
    }
3566
0
    else if (osName.size() >= 3)
3567
0
    {
3568
        // e.g "crs" for reproject will match "input-crs" and "target-crs"
3569
0
        const std::string dashName = std::string("-").append(osName);
3570
0
        for (const auto &arg : m_args)
3571
0
        {
3572
0
            if (cpl::ends_with(arg->GetName(), dashName))
3573
0
            {
3574
0
                ret.push_back(arg->GetName());
3575
0
            }
3576
0
        }
3577
0
    }
3578
0
    return ret;
3579
0
}
3580
3581
/************************************************************************/
3582
/*         GDALAlgorithm::IsKnownOutputRelatedBooleanArgName()          */
3583
/************************************************************************/
3584
3585
/* static */
3586
bool GDALAlgorithm::IsKnownOutputRelatedBooleanArgName(std::string_view osName)
3587
0
{
3588
0
    return osName == GDAL_ARG_NAME_APPEND || osName == GDAL_ARG_NAME_UPDATE ||
3589
0
           osName == GDAL_ARG_NAME_OVERWRITE ||
3590
0
           osName == GDAL_ARG_NAME_OVERWRITE_LAYER;
3591
0
}
3592
3593
/************************************************************************/
3594
/*                   GDALAlgorithm::HasOutputString()                   */
3595
/************************************************************************/
3596
3597
bool GDALAlgorithm::HasOutputString() const
3598
0
{
3599
0
    auto outputStringArg = GetArg(GDAL_ARG_NAME_OUTPUT_STRING);
3600
0
    return outputStringArg && outputStringArg->IsOutput();
3601
0
}
3602
3603
/************************************************************************/
3604
/*                       GDALAlgorithm::GetArg()                        */
3605
/************************************************************************/
3606
3607
GDALAlgorithmArg *GDALAlgorithm::GetArg(const std::string &osName,
3608
                                        bool suggestionAllowed, bool isConst)
3609
0
{
3610
0
    const auto nPos = osName.find_first_not_of('-');
3611
0
    if (nPos == std::string::npos)
3612
0
        return nullptr;
3613
0
    std::string osKey = osName.substr(nPos);
3614
0
    {
3615
0
        const auto oIter = m_mapLongNameToArg.find(osKey);
3616
0
        if (oIter != m_mapLongNameToArg.end())
3617
0
            return oIter->second;
3618
0
    }
3619
0
    {
3620
0
        const auto oIter = m_mapShortNameToArg.find(osKey);
3621
0
        if (oIter != m_mapShortNameToArg.end())
3622
0
            return oIter->second;
3623
0
    }
3624
3625
0
    if (!isConst && m_arbitraryLongNameArgsAllowed)
3626
0
    {
3627
0
        const auto nDotPos = osKey.find('.');
3628
0
        const std::string osKeyEnd =
3629
0
            nDotPos == std::string::npos ? osKey : osKey.substr(nDotPos + 1);
3630
0
        if (IsKnownOutputRelatedBooleanArgName(osKeyEnd))
3631
0
        {
3632
0
            m_arbitraryLongNameArgsValuesBool.emplace_back(
3633
0
                std::make_unique<bool>());
3634
0
            AddArg(osKey, 0, std::string("User-provided argument ") + osKey,
3635
0
                   m_arbitraryLongNameArgsValuesBool.back().get())
3636
0
                .SetUserProvided();
3637
0
        }
3638
0
        else
3639
0
        {
3640
0
            const std::string osKeyInit = osKey;
3641
0
            if (osKey == "oo")
3642
0
                osKey = GDAL_ARG_NAME_OPEN_OPTION;
3643
0
            else if (osKey == "co")
3644
0
                osKey = GDAL_ARG_NAME_CREATION_OPTION;
3645
0
            else if (osKey == "of")
3646
0
                osKey = GDAL_ARG_NAME_OUTPUT_FORMAT;
3647
0
            else if (osKey == "if")
3648
0
                osKey = GDAL_ARG_NAME_INPUT_FORMAT;
3649
0
            m_arbitraryLongNameArgsValuesStr.emplace_back(
3650
0
                std::make_unique<std::string>());
3651
0
            auto &arg =
3652
0
                AddArg(osKey, 0, std::string("User-provided argument ") + osKey,
3653
0
                       m_arbitraryLongNameArgsValuesStr.back().get())
3654
0
                    .SetUserProvided();
3655
0
            if (osKey != osKeyInit)
3656
0
                arg.AddAlias(osKeyInit);
3657
0
        }
3658
0
        const auto oIter = m_mapLongNameToArg.find(osKey);
3659
0
        CPLAssert(oIter != m_mapLongNameToArg.end());
3660
0
        return oIter->second;
3661
0
    }
3662
3663
0
    if (suggestionAllowed)
3664
0
    {
3665
0
        const auto suggestions = GetSuggestionsForArgumentName(osName);
3666
0
        if (!suggestions.empty())
3667
0
        {
3668
0
            CPLError(CE_Failure, CPLE_AppDefined,
3669
0
                     "Argument '%s' is unknown. Do you mean %s?",
3670
0
                     osName.c_str(),
3671
0
                     FormatSuggestionsAsString(suggestions,
3672
0
                                               /* addDashDashPrefix = */ false)
3673
0
                         .c_str());
3674
0
        }
3675
0
    }
3676
3677
0
    return nullptr;
3678
0
}
3679
3680
/************************************************************************/
3681
/*                     GDALAlgorithm::AddAliasFor()                     */
3682
/************************************************************************/
3683
3684
//! @cond Doxygen_Suppress
3685
void GDALAlgorithm::AddAliasFor(GDALInConstructionAlgorithmArg *arg,
3686
                                const std::string &alias)
3687
0
{
3688
0
    if (cpl::contains(m_mapLongNameToArg, alias))
3689
0
    {
3690
0
        ReportError(CE_Failure, CPLE_AppDefined, "Name '%s' already declared.",
3691
0
                    alias.c_str());
3692
0
    }
3693
0
    else
3694
0
    {
3695
0
        m_mapLongNameToArg[alias] = arg;
3696
0
    }
3697
0
}
3698
3699
//! @endcond
3700
3701
/************************************************************************/
3702
/*                GDALAlgorithm::AddShortNameAliasFor()                 */
3703
/************************************************************************/
3704
3705
//! @cond Doxygen_Suppress
3706
void GDALAlgorithm::AddShortNameAliasFor(GDALInConstructionAlgorithmArg *arg,
3707
                                         char shortNameAlias)
3708
0
{
3709
0
    std::string alias;
3710
0
    alias += shortNameAlias;
3711
0
    if (cpl::contains(m_mapShortNameToArg, alias))
3712
0
    {
3713
0
        ReportError(CE_Failure, CPLE_AppDefined,
3714
0
                    "Short name '%s' already declared.", alias.c_str());
3715
0
    }
3716
0
    else
3717
0
    {
3718
0
        m_mapShortNameToArg[alias] = arg;
3719
0
    }
3720
0
}
3721
3722
//! @endcond
3723
3724
/************************************************************************/
3725
/*                    GDALAlgorithm::SetPositional()                    */
3726
/************************************************************************/
3727
3728
//! @cond Doxygen_Suppress
3729
void GDALAlgorithm::SetPositional(GDALInConstructionAlgorithmArg *arg)
3730
0
{
3731
0
    CPLAssert(std::find(m_positionalArgs.begin(), m_positionalArgs.end(),
3732
0
                        arg) == m_positionalArgs.end());
3733
0
    m_positionalArgs.push_back(arg);
3734
0
}
3735
3736
//! @endcond
3737
3738
/************************************************************************/
3739
/*                  GDALAlgorithm::HasSubAlgorithms()                   */
3740
/************************************************************************/
3741
3742
bool GDALAlgorithm::HasSubAlgorithms() const
3743
0
{
3744
0
    if (!m_subAlgRegistry.empty())
3745
0
        return true;
3746
0
    return !GDALGlobalAlgorithmRegistry::GetSingleton()
3747
0
                .GetDeclaredSubAlgorithmNames(m_callPath)
3748
0
                .empty();
3749
0
}
3750
3751
/************************************************************************/
3752
/*                GDALAlgorithm::GetSubAlgorithmNames()                 */
3753
/************************************************************************/
3754
3755
std::vector<std::string> GDALAlgorithm::GetSubAlgorithmNames() const
3756
0
{
3757
0
    std::vector<std::string> ret = m_subAlgRegistry.GetNames();
3758
0
    const auto other = GDALGlobalAlgorithmRegistry::GetSingleton()
3759
0
                           .GetDeclaredSubAlgorithmNames(m_callPath);
3760
0
    ret.insert(ret.end(), other.begin(), other.end());
3761
0
    if (!other.empty())
3762
0
        std::sort(ret.begin(), ret.end());
3763
0
    return ret;
3764
0
}
3765
3766
/************************************************************************/
3767
/*                       GDALAlgorithm::AddArg()                        */
3768
/************************************************************************/
3769
3770
GDALInConstructionAlgorithmArg &
3771
GDALAlgorithm::AddArg(std::unique_ptr<GDALInConstructionAlgorithmArg> arg)
3772
0
{
3773
0
    auto argRaw = arg.get();
3774
0
    const auto &longName = argRaw->GetName();
3775
0
    if (!longName.empty())
3776
0
    {
3777
0
        if (longName[0] == '-')
3778
0
        {
3779
0
            ReportError(CE_Failure, CPLE_AppDefined,
3780
0
                        "Long name '%s' should not start with '-'",
3781
0
                        longName.c_str());
3782
0
        }
3783
0
        if (longName.find('=') != std::string::npos)
3784
0
        {
3785
0
            ReportError(CE_Failure, CPLE_AppDefined,
3786
0
                        "Long name '%s' should not contain a '=' character",
3787
0
                        longName.c_str());
3788
0
        }
3789
0
        if (cpl::contains(m_mapLongNameToArg, longName))
3790
0
        {
3791
0
            ReportError(CE_Failure, CPLE_AppDefined,
3792
0
                        "Long name '%s' already declared", longName.c_str());
3793
0
        }
3794
0
        m_mapLongNameToArg[longName] = argRaw;
3795
0
    }
3796
0
    const auto &shortName = argRaw->GetShortName();
3797
0
    if (!shortName.empty())
3798
0
    {
3799
0
        if (shortName.size() != 1 ||
3800
0
            !((shortName[0] >= 'a' && shortName[0] <= 'z') ||
3801
0
              (shortName[0] >= 'A' && shortName[0] <= 'Z') ||
3802
0
              (shortName[0] >= '0' && shortName[0] <= '9')))
3803
0
        {
3804
0
            ReportError(CE_Failure, CPLE_AppDefined,
3805
0
                        "Short name '%s' should be a single letter or digit",
3806
0
                        shortName.c_str());
3807
0
        }
3808
0
        if (cpl::contains(m_mapShortNameToArg, shortName))
3809
0
        {
3810
0
            ReportError(CE_Failure, CPLE_AppDefined,
3811
0
                        "Short name '%s' already declared", shortName.c_str());
3812
0
        }
3813
0
        m_mapShortNameToArg[shortName] = argRaw;
3814
0
    }
3815
0
    m_args.emplace_back(std::move(arg));
3816
0
    return *(
3817
0
        cpl::down_cast<GDALInConstructionAlgorithmArg *>(m_args.back().get()));
3818
0
}
3819
3820
GDALInConstructionAlgorithmArg &
3821
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3822
                      const std::string &helpMessage, bool *pValue)
3823
0
{
3824
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3825
0
        this,
3826
0
        GDALAlgorithmArgDecl(longName, chShortName, helpMessage, GAAT_BOOLEAN),
3827
0
        pValue));
3828
0
}
3829
3830
GDALInConstructionAlgorithmArg &
3831
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3832
                      const std::string &helpMessage, std::string *pValue)
3833
0
{
3834
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3835
0
        this,
3836
0
        GDALAlgorithmArgDecl(longName, chShortName, helpMessage, GAAT_STRING),
3837
0
        pValue));
3838
0
}
3839
3840
GDALInConstructionAlgorithmArg &
3841
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3842
                      const std::string &helpMessage, int *pValue)
3843
0
{
3844
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3845
0
        this,
3846
0
        GDALAlgorithmArgDecl(longName, chShortName, helpMessage, GAAT_INTEGER),
3847
0
        pValue));
3848
0
}
3849
3850
GDALInConstructionAlgorithmArg &
3851
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3852
                      const std::string &helpMessage, double *pValue)
3853
0
{
3854
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3855
0
        this,
3856
0
        GDALAlgorithmArgDecl(longName, chShortName, helpMessage, GAAT_REAL),
3857
0
        pValue));
3858
0
}
3859
3860
GDALInConstructionAlgorithmArg &
3861
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3862
                      const std::string &helpMessage,
3863
                      GDALArgDatasetValue *pValue, GDALArgDatasetType type)
3864
0
{
3865
0
    auto &arg = AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3866
0
                           this,
3867
0
                           GDALAlgorithmArgDecl(longName, chShortName,
3868
0
                                                helpMessage, GAAT_DATASET),
3869
0
                           pValue))
3870
0
                    .SetDatasetType(type);
3871
0
    pValue->SetOwnerArgument(&arg);
3872
0
    return arg;
3873
0
}
3874
3875
GDALInConstructionAlgorithmArg &
3876
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3877
                      const std::string &helpMessage,
3878
                      std::vector<std::string> *pValue)
3879
0
{
3880
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3881
0
        this,
3882
0
        GDALAlgorithmArgDecl(longName, chShortName, helpMessage,
3883
0
                             GAAT_STRING_LIST),
3884
0
        pValue));
3885
0
}
3886
3887
GDALInConstructionAlgorithmArg &
3888
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3889
                      const std::string &helpMessage, std::vector<int> *pValue)
3890
0
{
3891
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3892
0
        this,
3893
0
        GDALAlgorithmArgDecl(longName, chShortName, helpMessage,
3894
0
                             GAAT_INTEGER_LIST),
3895
0
        pValue));
3896
0
}
3897
3898
GDALInConstructionAlgorithmArg &
3899
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3900
                      const std::string &helpMessage,
3901
                      std::vector<double> *pValue)
3902
0
{
3903
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3904
0
        this,
3905
0
        GDALAlgorithmArgDecl(longName, chShortName, helpMessage,
3906
0
                             GAAT_REAL_LIST),
3907
0
        pValue));
3908
0
}
3909
3910
GDALInConstructionAlgorithmArg &
3911
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3912
                      const std::string &helpMessage,
3913
                      std::vector<GDALArgDatasetValue> *pValue,
3914
                      GDALArgDatasetType type)
3915
0
{
3916
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3917
0
                      this,
3918
0
                      GDALAlgorithmArgDecl(longName, chShortName, helpMessage,
3919
0
                                           GAAT_DATASET_LIST),
3920
0
                      pValue))
3921
0
        .SetDatasetType(type);
3922
0
}
3923
3924
/************************************************************************/
3925
/*                            MsgOrDefault()                            */
3926
/************************************************************************/
3927
3928
inline const char *MsgOrDefault(const char *helpMessage,
3929
                                const char *defaultMessage)
3930
0
{
3931
0
    return helpMessage && helpMessage[0] ? helpMessage : defaultMessage;
3932
0
}
3933
3934
/************************************************************************/
3935
/*         GDALAlgorithm::SetAutoCompleteFunctionForFilename()          */
3936
/************************************************************************/
3937
3938
/* static */
3939
void GDALAlgorithm::SetAutoCompleteFunctionForFilename(
3940
    GDALInConstructionAlgorithmArg &arg, GDALArgDatasetType type)
3941
0
{
3942
0
    arg.SetAutoCompleteFunction(
3943
0
        [&arg,
3944
0
         type](const std::string &currentValue) -> std::vector<std::string>
3945
0
        {
3946
0
            std::vector<std::string> oRet;
3947
3948
0
            if (arg.IsHidden())
3949
0
                return oRet;
3950
3951
0
            {
3952
0
                CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
3953
0
                VSIStatBufL sStat;
3954
0
                if (!currentValue.empty() && currentValue.back() != '/' &&
3955
0
                    VSIStatL(currentValue.c_str(), &sStat) == 0)
3956
0
                {
3957
0
                    return oRet;
3958
0
                }
3959
0
            }
3960
3961
0
            auto poDM = GetGDALDriverManager();
3962
0
            std::set<std::string> oExtensions;
3963
0
            if (type)
3964
0
            {
3965
0
                for (int i = 0; i < poDM->GetDriverCount(); ++i)
3966
0
                {
3967
0
                    auto poDriver = poDM->GetDriver(i);
3968
0
                    if (((type & GDAL_OF_RASTER) != 0 &&
3969
0
                         poDriver->GetMetadataItem(GDAL_DCAP_RASTER)) ||
3970
0
                        ((type & GDAL_OF_VECTOR) != 0 &&
3971
0
                         poDriver->GetMetadataItem(GDAL_DCAP_VECTOR)) ||
3972
0
                        ((type & GDAL_OF_MULTIDIM_RASTER) != 0 &&
3973
0
                         poDriver->GetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER)))
3974
0
                    {
3975
0
                        const char *pszExtensions =
3976
0
                            poDriver->GetMetadataItem(GDAL_DMD_EXTENSIONS);
3977
0
                        if (pszExtensions)
3978
0
                        {
3979
0
                            const CPLStringList aosExts(
3980
0
                                CSLTokenizeString2(pszExtensions, " ", 0));
3981
0
                            for (const char *pszExt : cpl::Iterate(aosExts))
3982
0
                                oExtensions.insert(CPLString(pszExt).tolower());
3983
0
                        }
3984
0
                    }
3985
0
                }
3986
0
            }
3987
3988
0
            std::string osDir;
3989
0
            const CPLStringList aosVSIPrefixes(VSIGetFileSystemsPrefixes());
3990
0
            std::string osPrefix;
3991
0
            if (STARTS_WITH(currentValue.c_str(), "/vsi"))
3992
0
            {
3993
0
                for (const char *pszPrefix : cpl::Iterate(aosVSIPrefixes))
3994
0
                {
3995
0
                    if (STARTS_WITH(currentValue.c_str(), pszPrefix))
3996
0
                    {
3997
0
                        osPrefix = pszPrefix;
3998
0
                        break;
3999
0
                    }
4000
0
                }
4001
0
                if (osPrefix.empty())
4002
0
                    return aosVSIPrefixes;
4003
0
                if (currentValue == osPrefix)
4004
0
                    osDir = osPrefix;
4005
0
            }
4006
0
            if (osDir.empty())
4007
0
            {
4008
0
                osDir = CPLGetDirnameSafe(currentValue.c_str());
4009
0
                if (!osPrefix.empty() && osDir.size() < osPrefix.size())
4010
0
                    osDir = std::move(osPrefix);
4011
0
            }
4012
4013
0
            auto psDir = VSIOpenDir(osDir.c_str(), 0, nullptr);
4014
0
            const std::string osSep = VSIGetDirectorySeparator(osDir.c_str());
4015
0
            if (currentValue.empty())
4016
0
                osDir.clear();
4017
0
            const std::string currentFilename =
4018
0
                CPLGetFilename(currentValue.c_str());
4019
0
            if (psDir)
4020
0
            {
4021
0
                while (const VSIDIREntry *psEntry = VSIGetNextDirEntry(psDir))
4022
0
                {
4023
0
                    if ((currentFilename.empty() ||
4024
0
                         STARTS_WITH(psEntry->pszName,
4025
0
                                     currentFilename.c_str())) &&
4026
0
                        strcmp(psEntry->pszName, ".") != 0 &&
4027
0
                        strcmp(psEntry->pszName, "..") != 0 &&
4028
0
                        (oExtensions.empty() ||
4029
0
                         !strstr(psEntry->pszName, ".aux.xml")))
4030
0
                    {
4031
0
                        if (oExtensions.empty() ||
4032
0
                            cpl::contains(
4033
0
                                oExtensions,
4034
0
                                CPLString(CPLGetExtensionSafe(psEntry->pszName))
4035
0
                                    .tolower()) ||
4036
0
                            VSI_ISDIR(psEntry->nMode))
4037
0
                        {
4038
0
                            std::string osVal;
4039
0
                            if (osDir.empty() || osDir == ".")
4040
0
                                osVal = psEntry->pszName;
4041
0
                            else
4042
0
                                osVal = CPLFormFilenameSafe(
4043
0
                                    osDir.c_str(), psEntry->pszName, nullptr);
4044
0
                            if (VSI_ISDIR(psEntry->nMode))
4045
0
                                osVal += osSep;
4046
0
                            oRet.push_back(std::move(osVal));
4047
0
                        }
4048
0
                    }
4049
0
                }
4050
0
                VSICloseDir(psDir);
4051
0
            }
4052
0
            return oRet;
4053
0
        });
4054
0
}
4055
4056
/************************************************************************/
4057
/*                 GDALAlgorithm::AddInputDatasetArg()                  */
4058
/************************************************************************/
4059
4060
GDALInConstructionAlgorithmArg &GDALAlgorithm::AddInputDatasetArg(
4061
    GDALArgDatasetValue *pValue, GDALArgDatasetType type,
4062
    bool positionalAndRequired, const char *helpMessage)
4063
0
{
4064
0
    auto &arg = AddArg(
4065
0
        GDAL_ARG_NAME_INPUT, 'i',
4066
0
        MsgOrDefault(helpMessage,
4067
0
                     CPLSPrintf("Input %s dataset",
4068
0
                                GDALAlgorithmArgDatasetTypeName(type).c_str())),
4069
0
        pValue, type);
4070
0
    if (positionalAndRequired)
4071
0
        arg.SetPositional().SetRequired();
4072
4073
0
    SetAutoCompleteFunctionForFilename(arg, type);
4074
4075
0
    AddValidationAction(
4076
0
        [pValue]()
4077
0
        {
4078
0
            if (pValue->GetName() == "-")
4079
0
                pValue->Set("/vsistdin/");
4080
0
            return true;
4081
0
        });
4082
4083
0
    return arg;
4084
0
}
4085
4086
/************************************************************************/
4087
/*                 GDALAlgorithm::AddInputDatasetArg()                  */
4088
/************************************************************************/
4089
4090
GDALInConstructionAlgorithmArg &GDALAlgorithm::AddInputDatasetArg(
4091
    std::vector<GDALArgDatasetValue> *pValue, GDALArgDatasetType type,
4092
    bool positionalAndRequired, const char *helpMessage)
4093
0
{
4094
0
    auto &arg =
4095
0
        AddArg(GDAL_ARG_NAME_INPUT, 'i',
4096
0
               MsgOrDefault(
4097
0
                   helpMessage,
4098
0
                   CPLSPrintf("Input %s datasets",
4099
0
                              GDALAlgorithmArgDatasetTypeName(type).c_str())),
4100
0
               pValue, type)
4101
0
            .SetPackedValuesAllowed(false);
4102
0
    if (positionalAndRequired)
4103
0
        arg.SetPositional().SetRequired();
4104
4105
0
    SetAutoCompleteFunctionForFilename(arg, type);
4106
4107
0
    AddValidationAction(
4108
0
        [pValue]()
4109
0
        {
4110
0
            for (auto &val : *pValue)
4111
0
            {
4112
0
                if (val.GetName() == "-")
4113
0
                    val.Set("/vsistdin/");
4114
0
            }
4115
0
            return true;
4116
0
        });
4117
0
    return arg;
4118
0
}
4119
4120
/************************************************************************/
4121
/*                 GDALAlgorithm::AddOutputDatasetArg()                 */
4122
/************************************************************************/
4123
4124
GDALInConstructionAlgorithmArg &GDALAlgorithm::AddOutputDatasetArg(
4125
    GDALArgDatasetValue *pValue, GDALArgDatasetType type,
4126
    bool positionalAndRequired, const char *helpMessage)
4127
0
{
4128
0
    auto &arg =
4129
0
        AddArg(GDAL_ARG_NAME_OUTPUT, 'o',
4130
0
               MsgOrDefault(
4131
0
                   helpMessage,
4132
0
                   CPLSPrintf("Output %s dataset",
4133
0
                              GDALAlgorithmArgDatasetTypeName(type).c_str())),
4134
0
               pValue, type)
4135
0
            .SetIsInput(true)
4136
0
            .SetIsOutput(true)
4137
0
            .SetDatasetInputFlags(GADV_NAME)
4138
0
            .SetDatasetOutputFlags(GADV_OBJECT);
4139
0
    if (positionalAndRequired)
4140
0
        arg.SetPositional().SetRequired();
4141
4142
0
    AddValidationAction(
4143
0
        [this, &arg, pValue]()
4144
0
        {
4145
0
            if (pValue->GetName() == "-")
4146
0
                pValue->Set("/vsistdout/");
4147
4148
0
            auto outputFormatArg = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
4149
0
            if (outputFormatArg && outputFormatArg->GetType() == GAAT_STRING &&
4150
0
                (!outputFormatArg->IsExplicitlySet() ||
4151
0
                 outputFormatArg->Get<std::string>().empty()) &&
4152
0
                arg.IsExplicitlySet())
4153
0
            {
4154
0
                const auto vrtCompatible =
4155
0
                    outputFormatArg->GetMetadataItem(GAAMDI_VRT_COMPATIBLE);
4156
0
                if (vrtCompatible && !vrtCompatible->empty() &&
4157
0
                    vrtCompatible->front() == "false" &&
4158
0
                    EQUAL(
4159
0
                        CPLGetExtensionSafe(pValue->GetName().c_str()).c_str(),
4160
0
                        "VRT"))
4161
0
                {
4162
0
                    ReportError(
4163
0
                        CE_Failure, CPLE_NotSupported,
4164
0
                        "VRT output is not supported.%s",
4165
0
                        outputFormatArg->GetDescription().find("GDALG") !=
4166
0
                                std::string::npos
4167
0
                            ? " Consider using the GDALG driver instead (files "
4168
0
                              "with .gdalg.json extension)"
4169
0
                            : "");
4170
0
                    return false;
4171
0
                }
4172
0
                else if (pValue->GetName().size() > strlen(".gdalg.json") &&
4173
0
                         EQUAL(pValue->GetName()
4174
0
                                   .substr(pValue->GetName().size() -
4175
0
                                           strlen(".gdalg.json"))
4176
0
                                   .c_str(),
4177
0
                               ".gdalg.json") &&
4178
0
                         outputFormatArg->GetDescription().find("GDALG") ==
4179
0
                             std::string::npos)
4180
0
                {
4181
0
                    ReportError(CE_Failure, CPLE_NotSupported,
4182
0
                                "GDALG output is not supported");
4183
0
                    return false;
4184
0
                }
4185
0
            }
4186
0
            return true;
4187
0
        });
4188
4189
0
    return arg;
4190
0
}
4191
4192
/************************************************************************/
4193
/*                   GDALAlgorithm::AddOverwriteArg()                   */
4194
/************************************************************************/
4195
4196
GDALInConstructionAlgorithmArg &
4197
GDALAlgorithm::AddOverwriteArg(bool *pValue, const char *helpMessage)
4198
0
{
4199
0
    return AddArg(
4200
0
               GDAL_ARG_NAME_OVERWRITE, 0,
4201
0
               MsgOrDefault(
4202
0
                   helpMessage,
4203
0
                   _("Whether overwriting existing output dataset is allowed")),
4204
0
               pValue)
4205
0
        .SetDefault(false);
4206
0
}
4207
4208
/************************************************************************/
4209
/*                GDALAlgorithm::AddOverwriteLayerArg()                 */
4210
/************************************************************************/
4211
4212
GDALInConstructionAlgorithmArg &
4213
GDALAlgorithm::AddOverwriteLayerArg(bool *pValue, const char *helpMessage)
4214
0
{
4215
0
    AddValidationAction(
4216
0
        [this]
4217
0
        {
4218
0
            auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
4219
0
            if (!(updateArg && updateArg->GetType() == GAAT_BOOLEAN))
4220
0
            {
4221
0
                ReportError(CE_Failure, CPLE_AppDefined,
4222
0
                            "--update argument must exist for "
4223
0
                            "--overwrite-layer, even if hidden");
4224
0
                return false;
4225
0
            }
4226
0
            return true;
4227
0
        });
4228
0
    return AddArg(
4229
0
               GDAL_ARG_NAME_OVERWRITE_LAYER, 0,
4230
0
               MsgOrDefault(
4231
0
                   helpMessage,
4232
0
                   _("Whether overwriting existing output layer is allowed")),
4233
0
               pValue)
4234
0
        .SetDefault(false)
4235
0
        .AddAction(
4236
0
            [this]
4237
0
            {
4238
0
                auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
4239
0
                if (updateArg && updateArg->GetType() == GAAT_BOOLEAN)
4240
0
                {
4241
0
                    updateArg->Set(true);
4242
0
                }
4243
0
            });
4244
0
}
4245
4246
/************************************************************************/
4247
/*                    GDALAlgorithm::AddUpdateArg()                     */
4248
/************************************************************************/
4249
4250
GDALInConstructionAlgorithmArg &
4251
GDALAlgorithm::AddUpdateArg(bool *pValue, const char *helpMessage)
4252
0
{
4253
0
    return AddArg(GDAL_ARG_NAME_UPDATE, 0,
4254
0
                  MsgOrDefault(
4255
0
                      helpMessage,
4256
0
                      _("Whether to open existing dataset in update mode")),
4257
0
                  pValue)
4258
0
        .SetDefault(false);
4259
0
}
4260
4261
/************************************************************************/
4262
/*                  GDALAlgorithm::AddAppendLayerArg()                  */
4263
/************************************************************************/
4264
4265
GDALInConstructionAlgorithmArg &
4266
GDALAlgorithm::AddAppendLayerArg(bool *pValue, const char *helpMessage)
4267
0
{
4268
0
    AddValidationAction(
4269
0
        [this]
4270
0
        {
4271
0
            auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
4272
0
            if (!(updateArg && updateArg->GetType() == GAAT_BOOLEAN))
4273
0
            {
4274
0
                ReportError(CE_Failure, CPLE_AppDefined,
4275
0
                            "--update argument must exist for --append, even "
4276
0
                            "if hidden");
4277
0
                return false;
4278
0
            }
4279
0
            return true;
4280
0
        });
4281
0
    return AddArg(GDAL_ARG_NAME_APPEND, 0,
4282
0
                  MsgOrDefault(
4283
0
                      helpMessage,
4284
0
                      _("Whether appending to existing layer is allowed")),
4285
0
                  pValue)
4286
0
        .SetDefault(false)
4287
0
        .AddAction(
4288
0
            [this]
4289
0
            {
4290
0
                auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
4291
0
                if (updateArg && updateArg->GetType() == GAAT_BOOLEAN)
4292
0
                {
4293
0
                    updateArg->Set(true);
4294
0
                }
4295
0
            });
4296
0
}
4297
4298
/************************************************************************/
4299
/*                GDALAlgorithm::AddOptionsSuggestions()                */
4300
/************************************************************************/
4301
4302
/* static */
4303
bool GDALAlgorithm::AddOptionsSuggestions(const char *pszXML, int datasetType,
4304
                                          const std::string &currentValue,
4305
                                          std::vector<std::string> &oRet)
4306
0
{
4307
0
    if (!pszXML)
4308
0
        return false;
4309
0
    CPLXMLTreeCloser poTree(CPLParseXMLString(pszXML));
4310
0
    if (!poTree)
4311
0
        return false;
4312
4313
0
    std::string typedOptionName = currentValue;
4314
0
    const auto posEqual = typedOptionName.find('=');
4315
0
    std::string typedValue;
4316
0
    if (posEqual != 0 && posEqual != std::string::npos)
4317
0
    {
4318
0
        typedValue = currentValue.substr(posEqual + 1);
4319
0
        typedOptionName.resize(posEqual);
4320
0
    }
4321
4322
0
    for (const CPLXMLNode *psChild = poTree.get()->psChild; psChild;
4323
0
         psChild = psChild->psNext)
4324
0
    {
4325
0
        const char *pszName = CPLGetXMLValue(psChild, "name", nullptr);
4326
0
        if (pszName && typedOptionName == pszName &&
4327
0
            (strcmp(psChild->pszValue, "Option") == 0 ||
4328
0
             strcmp(psChild->pszValue, "Argument") == 0))
4329
0
        {
4330
0
            const char *pszType = CPLGetXMLValue(psChild, "type", "");
4331
0
            const char *pszMin = CPLGetXMLValue(psChild, "min", nullptr);
4332
0
            const char *pszMax = CPLGetXMLValue(psChild, "max", nullptr);
4333
0
            if (EQUAL(pszType, "string-select"))
4334
0
            {
4335
0
                for (const CPLXMLNode *psChild2 = psChild->psChild; psChild2;
4336
0
                     psChild2 = psChild2->psNext)
4337
0
                {
4338
0
                    if (EQUAL(psChild2->pszValue, "Value"))
4339
0
                    {
4340
0
                        oRet.push_back(CPLGetXMLValue(psChild2, "", ""));
4341
0
                    }
4342
0
                }
4343
0
            }
4344
0
            else if (EQUAL(pszType, "boolean"))
4345
0
            {
4346
0
                if (typedValue == "YES" || typedValue == "NO")
4347
0
                {
4348
0
                    oRet.push_back(currentValue);
4349
0
                    return true;
4350
0
                }
4351
0
                oRet.push_back("NO");
4352
0
                oRet.push_back("YES");
4353
0
            }
4354
0
            else if (EQUAL(pszType, "int"))
4355
0
            {
4356
0
                if (pszMin && pszMax && atoi(pszMax) - atoi(pszMin) > 0 &&
4357
0
                    atoi(pszMax) - atoi(pszMin) < 25)
4358
0
                {
4359
0
                    const int nMax = atoi(pszMax);
4360
0
                    for (int i = atoi(pszMin); i <= nMax; ++i)
4361
0
                        oRet.push_back(std::to_string(i));
4362
0
                }
4363
0
            }
4364
4365
0
            if (oRet.empty())
4366
0
            {
4367
0
                if (pszMin && pszMax)
4368
0
                {
4369
0
                    oRet.push_back(std::string("##"));
4370
0
                    oRet.push_back(std::string("validity range: [")
4371
0
                                       .append(pszMin)
4372
0
                                       .append(",")
4373
0
                                       .append(pszMax)
4374
0
                                       .append("]"));
4375
0
                }
4376
0
                else if (pszMin)
4377
0
                {
4378
0
                    oRet.push_back(std::string("##"));
4379
0
                    oRet.push_back(
4380
0
                        std::string("validity range: >= ").append(pszMin));
4381
0
                }
4382
0
                else if (pszMax)
4383
0
                {
4384
0
                    oRet.push_back(std::string("##"));
4385
0
                    oRet.push_back(
4386
0
                        std::string("validity range: <= ").append(pszMax));
4387
0
                }
4388
0
                else if (const char *pszDescription =
4389
0
                             CPLGetXMLValue(psChild, "description", nullptr))
4390
0
                {
4391
0
                    oRet.push_back(std::string("##"));
4392
0
                    oRet.push_back(std::string("type: ")
4393
0
                                       .append(pszType)
4394
0
                                       .append(", description: ")
4395
0
                                       .append(pszDescription));
4396
0
                }
4397
0
            }
4398
4399
0
            return true;
4400
0
        }
4401
0
    }
4402
4403
0
    for (const CPLXMLNode *psChild = poTree.get()->psChild; psChild;
4404
0
         psChild = psChild->psNext)
4405
0
    {
4406
0
        const char *pszName = CPLGetXMLValue(psChild, "name", nullptr);
4407
0
        if (pszName && (strcmp(psChild->pszValue, "Option") == 0 ||
4408
0
                        strcmp(psChild->pszValue, "Argument") == 0))
4409
0
        {
4410
0
            const char *pszScope = CPLGetXMLValue(psChild, "scope", nullptr);
4411
0
            if (!pszScope ||
4412
0
                (EQUAL(pszScope, "raster") &&
4413
0
                 (datasetType & GDAL_OF_RASTER) != 0) ||
4414
0
                (EQUAL(pszScope, "vector") &&
4415
0
                 (datasetType & GDAL_OF_VECTOR) != 0))
4416
0
            {
4417
0
                oRet.push_back(std::string(pszName).append("="));
4418
0
            }
4419
0
        }
4420
0
    }
4421
4422
0
    return false;
4423
0
}
4424
4425
/************************************************************************/
4426
/*             GDALAlgorithm::OpenOptionCompleteFunction()              */
4427
/************************************************************************/
4428
4429
//! @cond Doxygen_Suppress
4430
std::vector<std::string>
4431
GDALAlgorithm::OpenOptionCompleteFunction(const std::string &currentValue) const
4432
0
{
4433
0
    std::vector<std::string> oRet;
4434
4435
0
    int datasetType = GDAL_OF_RASTER | GDAL_OF_VECTOR | GDAL_OF_MULTIDIM_RASTER;
4436
0
    auto inputArg = GetArg(GDAL_ARG_NAME_INPUT);
4437
0
    if (inputArg && (inputArg->GetType() == GAAT_DATASET ||
4438
0
                     inputArg->GetType() == GAAT_DATASET_LIST))
4439
0
    {
4440
0
        datasetType = inputArg->GetDatasetType();
4441
0
    }
4442
4443
0
    auto inputFormat = GetArg(GDAL_ARG_NAME_INPUT_FORMAT);
4444
0
    if (inputFormat && inputFormat->GetType() == GAAT_STRING_LIST &&
4445
0
        inputFormat->IsExplicitlySet())
4446
0
    {
4447
0
        const auto &aosAllowedDrivers =
4448
0
            inputFormat->Get<std::vector<std::string>>();
4449
0
        if (aosAllowedDrivers.size() == 1)
4450
0
        {
4451
0
            auto poDriver = GetGDALDriverManager()->GetDriverByName(
4452
0
                aosAllowedDrivers[0].c_str());
4453
0
            if (poDriver)
4454
0
            {
4455
0
                AddOptionsSuggestions(
4456
0
                    poDriver->GetMetadataItem(GDAL_DMD_OPENOPTIONLIST),
4457
0
                    datasetType, currentValue, oRet);
4458
0
            }
4459
0
            return oRet;
4460
0
        }
4461
0
    }
4462
4463
0
    const auto AddSuggestions = [datasetType, &currentValue,
4464
0
                                 &oRet](const GDALArgDatasetValue &datasetValue)
4465
0
    {
4466
0
        auto poDM = GetGDALDriverManager();
4467
4468
0
        const auto &osDSName = datasetValue.GetName();
4469
0
        const std::string osExt = CPLGetExtensionSafe(osDSName.c_str());
4470
0
        if (!osExt.empty())
4471
0
        {
4472
0
            std::set<std::string> oVisitedExtensions;
4473
0
            for (int i = 0; i < poDM->GetDriverCount(); ++i)
4474
0
            {
4475
0
                auto poDriver = poDM->GetDriver(i);
4476
0
                if (((datasetType & GDAL_OF_RASTER) != 0 &&
4477
0
                     poDriver->GetMetadataItem(GDAL_DCAP_RASTER)) ||
4478
0
                    ((datasetType & GDAL_OF_VECTOR) != 0 &&
4479
0
                     poDriver->GetMetadataItem(GDAL_DCAP_VECTOR)) ||
4480
0
                    ((datasetType & GDAL_OF_MULTIDIM_RASTER) != 0 &&
4481
0
                     poDriver->GetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER)))
4482
0
                {
4483
0
                    const char *pszExtensions =
4484
0
                        poDriver->GetMetadataItem(GDAL_DMD_EXTENSIONS);
4485
0
                    if (pszExtensions)
4486
0
                    {
4487
0
                        const CPLStringList aosExts(
4488
0
                            CSLTokenizeString2(pszExtensions, " ", 0));
4489
0
                        for (const char *pszExt : cpl::Iterate(aosExts))
4490
0
                        {
4491
0
                            if (EQUAL(pszExt, osExt.c_str()) &&
4492
0
                                !cpl::contains(oVisitedExtensions, pszExt))
4493
0
                            {
4494
0
                                oVisitedExtensions.insert(pszExt);
4495
0
                                if (AddOptionsSuggestions(
4496
0
                                        poDriver->GetMetadataItem(
4497
0
                                            GDAL_DMD_OPENOPTIONLIST),
4498
0
                                        datasetType, currentValue, oRet))
4499
0
                                {
4500
0
                                    return;
4501
0
                                }
4502
0
                                break;
4503
0
                            }
4504
0
                        }
4505
0
                    }
4506
0
                }
4507
0
            }
4508
0
        }
4509
0
    };
4510
4511
0
    if (inputArg && inputArg->GetType() == GAAT_DATASET)
4512
0
    {
4513
0
        auto &datasetValue = inputArg->Get<GDALArgDatasetValue>();
4514
0
        AddSuggestions(datasetValue);
4515
0
    }
4516
0
    else if (inputArg && inputArg->GetType() == GAAT_DATASET_LIST)
4517
0
    {
4518
0
        auto &datasetValues = inputArg->Get<std::vector<GDALArgDatasetValue>>();
4519
0
        if (datasetValues.size() == 1)
4520
0
            AddSuggestions(datasetValues[0]);
4521
0
    }
4522
4523
0
    return oRet;
4524
0
}
4525
4526
//! @endcond
4527
4528
/************************************************************************/
4529
/*                  GDALAlgorithm::AddOpenOptionsArg()                  */
4530
/************************************************************************/
4531
4532
GDALInConstructionAlgorithmArg &
4533
GDALAlgorithm::AddOpenOptionsArg(std::vector<std::string> *pValue,
4534
                                 const char *helpMessage)
4535
0
{
4536
0
    auto &arg = AddArg(GDAL_ARG_NAME_OPEN_OPTION, 0,
4537
0
                       MsgOrDefault(helpMessage, _("Open options")), pValue)
4538
0
                    .AddAlias("oo")
4539
0
                    .SetMetaVar("<KEY>=<VALUE>")
4540
0
                    .SetPackedValuesAllowed(false)
4541
0
                    .SetCategory(GAAC_ADVANCED);
4542
4543
0
    arg.AddValidationAction([this, &arg]()
4544
0
                            { return ParseAndValidateKeyValue(arg); });
4545
4546
0
    arg.SetAutoCompleteFunction(
4547
0
        [this](const std::string &currentValue)
4548
0
        { return OpenOptionCompleteFunction(currentValue); });
4549
4550
0
    return arg;
4551
0
}
4552
4553
/************************************************************************/
4554
/*               GDALAlgorithm::AddOutputOpenOptionsArg()               */
4555
/************************************************************************/
4556
4557
GDALInConstructionAlgorithmArg &
4558
GDALAlgorithm::AddOutputOpenOptionsArg(std::vector<std::string> *pValue,
4559
                                       const char *helpMessage)
4560
0
{
4561
0
    auto &arg =
4562
0
        AddArg(GDAL_ARG_NAME_OUTPUT_OPEN_OPTION, 0,
4563
0
               MsgOrDefault(helpMessage, _("Output open options")), pValue)
4564
0
            .AddAlias("output-oo")
4565
0
            .SetMetaVar("<KEY>=<VALUE>")
4566
0
            .SetPackedValuesAllowed(false)
4567
0
            .SetCategory(GAAC_ADVANCED);
4568
4569
0
    arg.AddValidationAction([this, &arg]()
4570
0
                            { return ParseAndValidateKeyValue(arg); });
4571
4572
0
    arg.SetAutoCompleteFunction(
4573
0
        [this](const std::string &currentValue)
4574
0
        { return OpenOptionCompleteFunction(currentValue); });
4575
4576
0
    return arg;
4577
0
}
4578
4579
/************************************************************************/
4580
/*                           ValidateFormat()                           */
4581
/************************************************************************/
4582
4583
bool GDALAlgorithm::ValidateFormat(const GDALAlgorithmArg &arg,
4584
                                   bool bStreamAllowed,
4585
                                   bool bGDALGAllowed) const
4586
0
{
4587
0
    if (arg.GetChoices().empty())
4588
0
    {
4589
0
        const auto Validate =
4590
0
            [this, &arg, bStreamAllowed, bGDALGAllowed](const std::string &val)
4591
0
        {
4592
0
            if (const auto extraFormats =
4593
0
                    arg.GetMetadataItem(GAAMDI_EXTRA_FORMATS))
4594
0
            {
4595
0
                for (const auto &extraFormat : *extraFormats)
4596
0
                {
4597
0
                    if (EQUAL(val.c_str(), extraFormat.c_str()))
4598
0
                        return true;
4599
0
                }
4600
0
            }
4601
4602
0
            if (bStreamAllowed && EQUAL(val.c_str(), "stream"))
4603
0
                return true;
4604
4605
0
            if (EQUAL(val.c_str(), "GDALG") &&
4606
0
                arg.GetName() == GDAL_ARG_NAME_OUTPUT_FORMAT)
4607
0
            {
4608
0
                if (bGDALGAllowed)
4609
0
                {
4610
0
                    return true;
4611
0
                }
4612
0
                else
4613
0
                {
4614
0
                    ReportError(CE_Failure, CPLE_NotSupported,
4615
0
                                "GDALG output is not supported.");
4616
0
                    return false;
4617
0
                }
4618
0
            }
4619
4620
0
            const auto vrtCompatible =
4621
0
                arg.GetMetadataItem(GAAMDI_VRT_COMPATIBLE);
4622
0
            if (vrtCompatible && !vrtCompatible->empty() &&
4623
0
                vrtCompatible->front() == "false" && EQUAL(val.c_str(), "VRT"))
4624
0
            {
4625
0
                ReportError(CE_Failure, CPLE_NotSupported,
4626
0
                            "VRT output is not supported.%s",
4627
0
                            bGDALGAllowed
4628
0
                                ? " Consider using the GDALG driver instead "
4629
0
                                  "(files with .gdalg.json extension)."
4630
0
                                : "");
4631
0
                return false;
4632
0
            }
4633
4634
0
            const auto allowedFormats =
4635
0
                arg.GetMetadataItem(GAAMDI_ALLOWED_FORMATS);
4636
0
            if (allowedFormats && !allowedFormats->empty() &&
4637
0
                std::find(allowedFormats->begin(), allowedFormats->end(),
4638
0
                          val) != allowedFormats->end())
4639
0
            {
4640
0
                return true;
4641
0
            }
4642
4643
0
            const auto excludedFormats =
4644
0
                arg.GetMetadataItem(GAAMDI_EXCLUDED_FORMATS);
4645
0
            if (excludedFormats && !excludedFormats->empty() &&
4646
0
                std::find(excludedFormats->begin(), excludedFormats->end(),
4647
0
                          val) != excludedFormats->end())
4648
0
            {
4649
0
                ReportError(CE_Failure, CPLE_NotSupported,
4650
0
                            "%s output is not supported.", val.c_str());
4651
0
                return false;
4652
0
            }
4653
4654
0
            auto hDriver = GDALGetDriverByName(val.c_str());
4655
0
            if (!hDriver)
4656
0
            {
4657
0
                auto poMissingDriver =
4658
0
                    GetGDALDriverManager()->GetHiddenDriverByName(val.c_str());
4659
0
                if (poMissingDriver)
4660
0
                {
4661
0
                    const std::string msg =
4662
0
                        GDALGetMessageAboutMissingPluginDriver(poMissingDriver);
4663
0
                    ReportError(CE_Failure, CPLE_AppDefined,
4664
0
                                "Invalid value for argument '%s'. Driver '%s' "
4665
0
                                "not found but is known. However plugin %s",
4666
0
                                arg.GetName().c_str(), val.c_str(),
4667
0
                                msg.c_str());
4668
0
                }
4669
0
                else
4670
0
                {
4671
0
                    ReportError(CE_Failure, CPLE_AppDefined,
4672
0
                                "Invalid value for argument '%s'. Driver '%s' "
4673
0
                                "does not exist.",
4674
0
                                arg.GetName().c_str(), val.c_str());
4675
0
                }
4676
0
                return false;
4677
0
            }
4678
4679
0
            const auto caps = arg.GetMetadataItem(GAAMDI_REQUIRED_CAPABILITIES);
4680
0
            if (caps)
4681
0
            {
4682
0
                for (const std::string &cap : *caps)
4683
0
                {
4684
0
                    const char *pszVal =
4685
0
                        GDALGetMetadataItem(hDriver, cap.c_str(), nullptr);
4686
0
                    if (!(pszVal && pszVal[0]))
4687
0
                    {
4688
0
                        if (cap == GDAL_DCAP_CREATECOPY &&
4689
0
                            std::find(caps->begin(), caps->end(),
4690
0
                                      GDAL_DCAP_RASTER) != caps->end() &&
4691
0
                            GDALGetMetadataItem(hDriver, GDAL_DCAP_RASTER,
4692
0
                                                nullptr) &&
4693
0
                            GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATE,
4694
0
                                                nullptr))
4695
0
                        {
4696
                            // if it supports Create, it supports CreateCopy
4697
0
                        }
4698
0
                        else if (cap == GDAL_DMD_EXTENSIONS)
4699
0
                        {
4700
0
                            ReportError(
4701
0
                                CE_Failure, CPLE_AppDefined,
4702
0
                                "Invalid value for argument '%s'. Driver '%s' "
4703
0
                                "does "
4704
0
                                "not advertise any file format extension.",
4705
0
                                arg.GetName().c_str(), val.c_str());
4706
0
                            return false;
4707
0
                        }
4708
0
                        else
4709
0
                        {
4710
0
                            if (cap == GDAL_DCAP_CREATE)
4711
0
                            {
4712
0
                                auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
4713
0
                                if (updateArg &&
4714
0
                                    updateArg->GetType() == GAAT_BOOLEAN &&
4715
0
                                    updateArg->IsExplicitlySet())
4716
0
                                {
4717
0
                                    continue;
4718
0
                                }
4719
4720
0
                                ReportError(
4721
0
                                    CE_Failure, CPLE_AppDefined,
4722
0
                                    "Invalid value for argument '%s'. "
4723
0
                                    "Driver '%s' does not have write support.",
4724
0
                                    arg.GetName().c_str(), val.c_str());
4725
0
                                return false;
4726
0
                            }
4727
0
                            else
4728
0
                            {
4729
0
                                ReportError(
4730
0
                                    CE_Failure, CPLE_AppDefined,
4731
0
                                    "Invalid value for argument '%s'. Driver "
4732
0
                                    "'%s' "
4733
0
                                    "does "
4734
0
                                    "not expose the required '%s' capability.",
4735
0
                                    arg.GetName().c_str(), val.c_str(),
4736
0
                                    cap.c_str());
4737
0
                                return false;
4738
0
                            }
4739
0
                        }
4740
0
                    }
4741
0
                }
4742
0
            }
4743
0
            return true;
4744
0
        };
4745
4746
0
        if (arg.GetType() == GAAT_STRING)
4747
0
        {
4748
0
            return Validate(arg.Get<std::string>());
4749
0
        }
4750
0
        else if (arg.GetType() == GAAT_STRING_LIST)
4751
0
        {
4752
0
            for (const auto &val : arg.Get<std::vector<std::string>>())
4753
0
            {
4754
0
                if (!Validate(val))
4755
0
                    return false;
4756
0
            }
4757
0
        }
4758
0
    }
4759
4760
0
    return true;
4761
0
}
4762
4763
/************************************************************************/
4764
/*                     FormatAutoCompleteFunction()                     */
4765
/************************************************************************/
4766
4767
/* static */
4768
std::vector<std::string> GDALAlgorithm::FormatAutoCompleteFunction(
4769
    const GDALAlgorithmArg &arg, bool /* bStreamAllowed */, bool bGDALGAllowed)
4770
0
{
4771
0
    std::vector<std::string> res;
4772
0
    auto poDM = GetGDALDriverManager();
4773
0
    const auto vrtCompatible = arg.GetMetadataItem(GAAMDI_VRT_COMPATIBLE);
4774
0
    const auto allowedFormats = arg.GetMetadataItem(GAAMDI_ALLOWED_FORMATS);
4775
0
    const auto excludedFormats = arg.GetMetadataItem(GAAMDI_EXCLUDED_FORMATS);
4776
0
    const auto caps = arg.GetMetadataItem(GAAMDI_REQUIRED_CAPABILITIES);
4777
0
    if (auto extraFormats = arg.GetMetadataItem(GAAMDI_EXTRA_FORMATS))
4778
0
        res = std::move(*extraFormats);
4779
0
    for (int i = 0; i < poDM->GetDriverCount(); ++i)
4780
0
    {
4781
0
        auto poDriver = poDM->GetDriver(i);
4782
4783
0
        if (vrtCompatible && !vrtCompatible->empty() &&
4784
0
            vrtCompatible->front() == "false" &&
4785
0
            EQUAL(poDriver->GetDescription(), "VRT"))
4786
0
        {
4787
            // do nothing
4788
0
        }
4789
0
        else if (allowedFormats && !allowedFormats->empty() &&
4790
0
                 std::find(allowedFormats->begin(), allowedFormats->end(),
4791
0
                           poDriver->GetDescription()) != allowedFormats->end())
4792
0
        {
4793
0
            res.push_back(poDriver->GetDescription());
4794
0
        }
4795
0
        else if (excludedFormats && !excludedFormats->empty() &&
4796
0
                 std::find(excludedFormats->begin(), excludedFormats->end(),
4797
0
                           poDriver->GetDescription()) !=
4798
0
                     excludedFormats->end())
4799
0
        {
4800
0
            continue;
4801
0
        }
4802
0
        else if (caps)
4803
0
        {
4804
0
            bool ok = true;
4805
0
            for (const std::string &cap : *caps)
4806
0
            {
4807
0
                if (cap == GDAL_ALG_DCAP_RASTER_OR_MULTIDIM_RASTER)
4808
0
                {
4809
0
                    if (!poDriver->GetMetadataItem(GDAL_DCAP_RASTER) &&
4810
0
                        !poDriver->GetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER))
4811
0
                    {
4812
0
                        ok = false;
4813
0
                        break;
4814
0
                    }
4815
0
                }
4816
0
                else if (const char *pszVal =
4817
0
                             poDriver->GetMetadataItem(cap.c_str());
4818
0
                         pszVal && pszVal[0])
4819
0
                {
4820
0
                }
4821
0
                else if (cap == GDAL_DCAP_CREATECOPY &&
4822
0
                         (std::find(caps->begin(), caps->end(),
4823
0
                                    GDAL_DCAP_RASTER) != caps->end() &&
4824
0
                          poDriver->GetMetadataItem(GDAL_DCAP_RASTER)) &&
4825
0
                         poDriver->GetMetadataItem(GDAL_DCAP_CREATE))
4826
0
                {
4827
                    // if it supports Create, it supports CreateCopy
4828
0
                }
4829
0
                else
4830
0
                {
4831
0
                    ok = false;
4832
0
                    break;
4833
0
                }
4834
0
            }
4835
0
            if (ok)
4836
0
            {
4837
0
                res.push_back(poDriver->GetDescription());
4838
0
            }
4839
0
        }
4840
0
    }
4841
0
    if (bGDALGAllowed)
4842
0
        res.push_back("GDALG");
4843
0
    return res;
4844
0
}
4845
4846
/************************************************************************/
4847
/*                 GDALAlgorithm::AddInputFormatsArg()                  */
4848
/************************************************************************/
4849
4850
GDALInConstructionAlgorithmArg &
4851
GDALAlgorithm::AddInputFormatsArg(std::vector<std::string> *pValue,
4852
                                  const char *helpMessage)
4853
0
{
4854
0
    auto &arg = AddArg(GDAL_ARG_NAME_INPUT_FORMAT, 0,
4855
0
                       MsgOrDefault(helpMessage, _("Input formats")), pValue)
4856
0
                    .AddAlias("if")
4857
0
                    .SetCategory(GAAC_ADVANCED);
4858
0
    arg.AddValidationAction([this, &arg]()
4859
0
                            { return ValidateFormat(arg, false, false); });
4860
0
    arg.SetAutoCompleteFunction(
4861
0
        [&arg](const std::string &)
4862
0
        { return FormatAutoCompleteFunction(arg, false, false); });
4863
0
    return arg;
4864
0
}
4865
4866
/************************************************************************/
4867
/*                 GDALAlgorithm::AddOutputFormatArg()                  */
4868
/************************************************************************/
4869
4870
GDALInConstructionAlgorithmArg &
4871
GDALAlgorithm::AddOutputFormatArg(std::string *pValue, bool bStreamAllowed,
4872
                                  bool bGDALGAllowed, const char *helpMessage)
4873
0
{
4874
0
    auto &arg = AddArg(GDAL_ARG_NAME_OUTPUT_FORMAT, 'f',
4875
0
                       MsgOrDefault(helpMessage,
4876
0
                                    bGDALGAllowed
4877
0
                                        ? _("Output format (\"GDALG\" allowed)")
4878
0
                                        : _("Output format")),
4879
0
                       pValue)
4880
0
                    .AddAlias("of")
4881
0
                    .AddAlias("format");
4882
0
    arg.AddValidationAction(
4883
0
        [this, &arg, bStreamAllowed, bGDALGAllowed]()
4884
0
        { return ValidateFormat(arg, bStreamAllowed, bGDALGAllowed); });
4885
0
    arg.SetAutoCompleteFunction(
4886
0
        [&arg, bStreamAllowed, bGDALGAllowed](const std::string &)
4887
0
        {
4888
0
            return FormatAutoCompleteFunction(arg, bStreamAllowed,
4889
0
                                              bGDALGAllowed);
4890
0
        });
4891
0
    return arg;
4892
0
}
4893
4894
/************************************************************************/
4895
/*                GDALAlgorithm::AddOutputDataTypeArg()                 */
4896
/************************************************************************/
4897
GDALInConstructionAlgorithmArg &
4898
GDALAlgorithm::AddOutputDataTypeArg(std::string *pValue,
4899
                                    const char *helpMessage)
4900
0
{
4901
0
    auto &arg =
4902
0
        AddArg(GDAL_ARG_NAME_OUTPUT_DATA_TYPE, 0,
4903
0
               MsgOrDefault(helpMessage, _("Output data type")), pValue)
4904
0
            .AddAlias("ot")
4905
0
            .AddAlias("datatype")
4906
0
            .AddMetadataItem("type", {"GDALDataType"})
4907
0
            .SetChoices("UInt8", "Int8", "UInt16", "Int16", "UInt32", "Int32",
4908
0
                        "UInt64", "Int64", "CInt16", "CInt32", "Float16",
4909
0
                        "Float32", "Float64", "CFloat32", "CFloat64")
4910
0
            .SetHiddenChoices("Byte");
4911
0
    return arg;
4912
0
}
4913
4914
/************************************************************************/
4915
/*                    GDALAlgorithm::AddNodataArg()                     */
4916
/************************************************************************/
4917
4918
GDALInConstructionAlgorithmArg &
4919
GDALAlgorithm::AddNodataArg(std::string *pValue, bool noneAllowed,
4920
                            const std::string &optionName,
4921
                            const char *helpMessage)
4922
0
{
4923
0
    auto &arg = AddArg(
4924
0
        optionName, 0,
4925
0
        MsgOrDefault(helpMessage,
4926
0
                     noneAllowed
4927
0
                         ? _("Assign a specified nodata value to output bands "
4928
0
                             "('none', numeric value, 'nan', 'inf', '-inf')")
4929
0
                         : _("Assign a specified nodata value to output bands "
4930
0
                             "(numeric value, 'nan', 'inf', '-inf')")),
4931
0
        pValue);
4932
0
    arg.AddValidationAction(
4933
0
        [this, pValue, noneAllowed, optionName]()
4934
0
        {
4935
0
            if (!(noneAllowed && EQUAL(pValue->c_str(), "none")))
4936
0
            {
4937
0
                char *endptr = nullptr;
4938
0
                CPLStrtod(pValue->c_str(), &endptr);
4939
0
                if (endptr != pValue->c_str() + pValue->size())
4940
0
                {
4941
0
                    ReportError(CE_Failure, CPLE_IllegalArg,
4942
0
                                "Value of '%s' should be %sa "
4943
0
                                "numeric value, 'nan', 'inf' or '-inf'",
4944
0
                                optionName.c_str(),
4945
0
                                noneAllowed ? "'none', " : "");
4946
0
                    return false;
4947
0
                }
4948
0
            }
4949
0
            return true;
4950
0
        });
4951
0
    return arg;
4952
0
}
4953
4954
/************************************************************************/
4955
/*                 GDALAlgorithm::AddOutputStringArg()                  */
4956
/************************************************************************/
4957
4958
GDALInConstructionAlgorithmArg &
4959
GDALAlgorithm::AddOutputStringArg(std::string *pValue, const char *helpMessage)
4960
0
{
4961
0
    return AddArg(
4962
0
               GDAL_ARG_NAME_OUTPUT_STRING, 0,
4963
0
               MsgOrDefault(helpMessage,
4964
0
                            _("Output string, in which the result is placed")),
4965
0
               pValue)
4966
0
        .SetHiddenForCLI()
4967
0
        .SetIsInput(false)
4968
0
        .SetIsOutput(true);
4969
0
}
4970
4971
/************************************************************************/
4972
/*                    GDALAlgorithm::AddStdoutArg()                     */
4973
/************************************************************************/
4974
4975
GDALInConstructionAlgorithmArg &
4976
GDALAlgorithm::AddStdoutArg(bool *pValue, const char *helpMessage)
4977
0
{
4978
0
    return AddArg(GDAL_ARG_NAME_STDOUT, 0,
4979
0
                  MsgOrDefault(helpMessage,
4980
0
                               _("Directly output on stdout. If enabled, "
4981
0
                                 "output-string will be empty")),
4982
0
                  pValue)
4983
0
        .SetHidden();
4984
0
}
4985
4986
/************************************************************************/
4987
/*                   GDALAlgorithm::AddLayerNameArg()                   */
4988
/************************************************************************/
4989
4990
GDALInConstructionAlgorithmArg &
4991
GDALAlgorithm::AddLayerNameArg(std::string *pValue, const char *helpMessage)
4992
0
{
4993
0
    return AddArg(GDAL_ARG_NAME_INPUT_LAYER, 'l',
4994
0
                  MsgOrDefault(helpMessage, _("Input layer name")), pValue);
4995
0
}
4996
4997
/************************************************************************/
4998
/*                   GDALAlgorithm::AddArrayNameArg()                   */
4999
/************************************************************************/
5000
5001
GDALInConstructionAlgorithmArg &
5002
GDALAlgorithm::AddArrayNameArg(std::string *pValue, const char *helpMessage)
5003
0
{
5004
0
    return AddArg("array", 0, MsgOrDefault(helpMessage, _("Array name")),
5005
0
                  pValue)
5006
0
        .SetAutoCompleteFunction([this](const std::string &)
5007
0
                                 { return AutoCompleteArrayName(); });
5008
0
}
5009
5010
/************************************************************************/
5011
/*                   GDALAlgorithm::AddArrayNameArg()                   */
5012
/************************************************************************/
5013
5014
GDALInConstructionAlgorithmArg &
5015
GDALAlgorithm::AddArrayNameArg(std::vector<std::string> *pValue,
5016
                               const char *helpMessage)
5017
0
{
5018
0
    return AddArg("array", 0, MsgOrDefault(helpMessage, _("Array name(s)")),
5019
0
                  pValue)
5020
0
        .SetAutoCompleteFunction([this](const std::string &)
5021
0
                                 { return AutoCompleteArrayName(); });
5022
0
}
5023
5024
/************************************************************************/
5025
/*                GDALAlgorithm::AutoCompleteArrayName()                */
5026
/************************************************************************/
5027
5028
std::vector<std::string> GDALAlgorithm::AutoCompleteArrayName() const
5029
0
{
5030
0
    std::vector<std::string> ret;
5031
0
    std::string osDSName;
5032
0
    auto inputArg = GetArg(GDAL_ARG_NAME_INPUT);
5033
0
    if (inputArg && inputArg->GetType() == GAAT_DATASET_LIST)
5034
0
    {
5035
0
        auto &inputDatasets = inputArg->Get<std::vector<GDALArgDatasetValue>>();
5036
0
        if (!inputDatasets.empty())
5037
0
        {
5038
0
            osDSName = inputDatasets[0].GetName();
5039
0
        }
5040
0
    }
5041
0
    else if (inputArg && inputArg->GetType() == GAAT_DATASET)
5042
0
    {
5043
0
        auto &inputDataset = inputArg->Get<GDALArgDatasetValue>();
5044
0
        osDSName = inputDataset.GetName();
5045
0
    }
5046
5047
0
    if (!osDSName.empty())
5048
0
    {
5049
0
        CPLStringList aosAllowedDrivers;
5050
0
        const auto ifArg = GetArg(GDAL_ARG_NAME_INPUT_FORMAT);
5051
0
        if (ifArg && ifArg->GetType() == GAAT_STRING_LIST)
5052
0
            aosAllowedDrivers =
5053
0
                CPLStringList(ifArg->Get<std::vector<std::string>>());
5054
5055
0
        CPLStringList aosOpenOptions;
5056
0
        const auto ooArg = GetArg(GDAL_ARG_NAME_OPEN_OPTION);
5057
0
        if (ooArg && ooArg->GetType() == GAAT_STRING_LIST)
5058
0
            aosOpenOptions =
5059
0
                CPLStringList(ooArg->Get<std::vector<std::string>>());
5060
5061
0
        if (auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
5062
0
                osDSName.c_str(), GDAL_OF_MULTIDIM_RASTER,
5063
0
                aosAllowedDrivers.List(), aosOpenOptions.List(), nullptr)))
5064
0
        {
5065
0
            if (auto poRG = poDS->GetRootGroup())
5066
0
            {
5067
0
                ret = poRG->GetMDArrayFullNamesRecursive();
5068
0
            }
5069
0
        }
5070
0
    }
5071
5072
0
    return ret;
5073
0
}
5074
5075
/************************************************************************/
5076
/*                  GDALAlgorithm::AddMemorySizeArg()                   */
5077
/************************************************************************/
5078
5079
GDALInConstructionAlgorithmArg &
5080
GDALAlgorithm::AddMemorySizeArg(size_t *pValue, std::string *pStrValue,
5081
                                const std::string &optionName,
5082
                                const char *helpMessage)
5083
0
{
5084
0
    return AddArg(optionName, 0, helpMessage, pStrValue)
5085
0
        .SetDefault(*pStrValue)
5086
0
        .AddValidationAction(
5087
0
            [this, pValue, pStrValue]()
5088
0
            {
5089
0
                CPLDebug("GDAL", "StrValue `%s`", pStrValue->c_str());
5090
0
                GIntBig nBytes;
5091
0
                bool bUnitSpecified;
5092
0
                if (CPLParseMemorySize(pStrValue->c_str(), &nBytes,
5093
0
                                       &bUnitSpecified) != CE_None)
5094
0
                {
5095
0
                    return false;
5096
0
                }
5097
0
                if (!bUnitSpecified)
5098
0
                {
5099
0
                    ReportError(CE_Failure, CPLE_AppDefined,
5100
0
                                "Memory size must have a unit or be a "
5101
0
                                "percentage of usable RAM (2GB, 5%%, etc.)");
5102
0
                    return false;
5103
0
                }
5104
                if constexpr (sizeof(std::uint64_t) > sizeof(size_t))
5105
                {
5106
                    // -1 to please CoverityScan
5107
                    if (static_cast<std::uint64_t>(nBytes) >
5108
                        std::numeric_limits<size_t>::max() - 1U)
5109
                    {
5110
                        ReportError(CE_Failure, CPLE_AppDefined,
5111
                                    "Memory size %s is too large.",
5112
                                    pStrValue->c_str());
5113
                        return false;
5114
                    }
5115
                }
5116
5117
0
                *pValue = static_cast<size_t>(nBytes);
5118
0
                return true;
5119
0
            });
5120
0
}
5121
5122
/************************************************************************/
5123
/*                GDALAlgorithm::AddOutputLayerNameArg()                */
5124
/************************************************************************/
5125
5126
GDALInConstructionAlgorithmArg &
5127
GDALAlgorithm::AddOutputLayerNameArg(std::string *pValue,
5128
                                     const char *helpMessage)
5129
0
{
5130
0
    return AddArg(GDAL_ARG_NAME_OUTPUT_LAYER, 0,
5131
0
                  MsgOrDefault(helpMessage, _("Output layer name")), pValue);
5132
0
}
5133
5134
/************************************************************************/
5135
/*                   GDALAlgorithm::AddLayerNameArg()                   */
5136
/************************************************************************/
5137
5138
GDALInConstructionAlgorithmArg &
5139
GDALAlgorithm::AddLayerNameArg(std::vector<std::string> *pValue,
5140
                               const char *helpMessage)
5141
0
{
5142
0
    return AddArg(GDAL_ARG_NAME_INPUT_LAYER, 'l',
5143
0
                  MsgOrDefault(helpMessage, _("Input layer name")), pValue);
5144
0
}
5145
5146
/************************************************************************/
5147
/*                 GDALAlgorithm::AddGeometryTypeArg()                  */
5148
/************************************************************************/
5149
5150
GDALInConstructionAlgorithmArg &
5151
GDALAlgorithm::AddGeometryTypeArg(std::string *pValue, const char *helpMessage)
5152
0
{
5153
0
    return AddArg("geometry-type", 0,
5154
0
                  MsgOrDefault(helpMessage, _("Geometry type")), pValue)
5155
0
        .SetAutoCompleteFunction(
5156
0
            [](const std::string &currentValue)
5157
0
            {
5158
0
                std::vector<std::string> oRet;
5159
0
                for (const char *type :
5160
0
                     {"GEOMETRY", "POINT", "LINESTRING", "POLYGON",
5161
0
                      "MULTIPOINT", "MULTILINESTRING", "MULTIPOLYGON",
5162
0
                      "GEOMETRYCOLLECTION", "CURVE", "CIRCULARSTRING",
5163
0
                      "COMPOUNDCURVE", "SURFACE", "CURVEPOLYGON", "MULTICURVE",
5164
0
                      "MULTISURFACE", "POLYHEDRALSURFACE", "TIN"})
5165
0
                {
5166
0
                    if (currentValue.empty() ||
5167
0
                        STARTS_WITH(type, currentValue.c_str()))
5168
0
                    {
5169
0
                        oRet.push_back(type);
5170
0
                        oRet.push_back(std::string(type).append("Z"));
5171
0
                        oRet.push_back(std::string(type).append("M"));
5172
0
                        oRet.push_back(std::string(type).append("ZM"));
5173
0
                    }
5174
0
                }
5175
0
                return oRet;
5176
0
            })
5177
0
        .AddValidationAction(
5178
0
            [this, pValue]()
5179
0
            {
5180
0
                if (wkbFlatten(OGRFromOGCGeomType(pValue->c_str())) ==
5181
0
                        wkbUnknown &&
5182
0
                    !STARTS_WITH_CI(pValue->c_str(), "GEOMETRY"))
5183
0
                {
5184
0
                    ReportError(CE_Failure, CPLE_AppDefined,
5185
0
                                "Invalid geometry type '%s'", pValue->c_str());
5186
0
                    return false;
5187
0
                }
5188
0
                return true;
5189
0
            });
5190
0
}
5191
5192
/************************************************************************/
5193
/*         GDALAlgorithm::SetAutoCompleteFunctionForLayerName()         */
5194
/************************************************************************/
5195
5196
/* static */
5197
void GDALAlgorithm::SetAutoCompleteFunctionForLayerName(
5198
    GDALInConstructionAlgorithmArg &layerArg, GDALAlgorithmArg &datasetArg)
5199
0
{
5200
0
    CPLAssert(datasetArg.GetType() == GAAT_DATASET ||
5201
0
              datasetArg.GetType() == GAAT_DATASET_LIST);
5202
5203
0
    layerArg.SetAutoCompleteFunction(
5204
0
        [&datasetArg](const std::string &currentValue)
5205
0
        {
5206
0
            std::vector<std::string> ret;
5207
0
            CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
5208
0
            GDALArgDatasetValue *dsVal = nullptr;
5209
0
            if (datasetArg.GetType() == GAAT_DATASET)
5210
0
            {
5211
0
                dsVal = &(datasetArg.Get<GDALArgDatasetValue>());
5212
0
            }
5213
0
            else
5214
0
            {
5215
0
                auto &val = datasetArg.Get<std::vector<GDALArgDatasetValue>>();
5216
0
                if (val.size() == 1)
5217
0
                {
5218
0
                    dsVal = &val[0];
5219
0
                }
5220
0
            }
5221
0
            if (dsVal && !dsVal->GetName().empty())
5222
0
            {
5223
0
                auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
5224
0
                    dsVal->GetName().c_str(), GDAL_OF_VECTOR));
5225
0
                if (poDS)
5226
0
                {
5227
0
                    for (auto &&poLayer : poDS->GetLayers())
5228
0
                    {
5229
0
                        if (currentValue == poLayer->GetDescription())
5230
0
                        {
5231
0
                            ret.clear();
5232
0
                            ret.push_back(poLayer->GetDescription());
5233
0
                            break;
5234
0
                        }
5235
0
                        ret.push_back(poLayer->GetDescription());
5236
0
                    }
5237
0
                }
5238
0
            }
5239
0
            return ret;
5240
0
        });
5241
0
}
5242
5243
/************************************************************************/
5244
/*         GDALAlgorithm::SetAutoCompleteFunctionForFieldName()         */
5245
/************************************************************************/
5246
5247
void GDALAlgorithm::SetAutoCompleteFunctionForFieldName(
5248
    GDALInConstructionAlgorithmArg &fieldArg,
5249
    const GDALAlgorithmArg *layerNameArg, bool attributeFields,
5250
    bool geometryFields, std::vector<GDALArgDatasetValue> &datasetArg,
5251
    const std::vector<std::string> &extraValues,
5252
    std::function<bool(const OGRFieldDefn *)> filterFn)
5253
0
{
5254
5255
0
    fieldArg.SetAutoCompleteFunction(
5256
0
        [&datasetArg, layerNameArg, attributeFields, geometryFields,
5257
0
         extraValues,
5258
0
         filterFn = std::move(filterFn)](const std::string &currentValue)
5259
0
        {
5260
0
            std::set<std::string> ret{};
5261
0
            if (!datasetArg.empty())
5262
0
            {
5263
0
                CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
5264
5265
0
                const auto getLayerFields =
5266
0
                    [&ret, &currentValue, attributeFields, geometryFields,
5267
0
                     &extraValues, &filterFn](const OGRLayer *poLayer)
5268
0
                {
5269
0
                    const auto poDefn = poLayer->GetLayerDefn();
5270
0
                    if (attributeFields)
5271
0
                    {
5272
0
                        for (const auto poFieldDefn : poDefn->GetFields())
5273
0
                        {
5274
0
                            if (filterFn && !filterFn(poFieldDefn))
5275
0
                            {
5276
0
                                continue;
5277
0
                            }
5278
5279
0
                            const char *fieldName = poFieldDefn->GetNameRef();
5280
5281
0
                            if (currentValue == fieldName)
5282
0
                            {
5283
0
                                ret.clear();
5284
0
                                ret.insert(fieldName);
5285
0
                                break;
5286
0
                            }
5287
0
                            ret.insert(fieldName);
5288
0
                        }
5289
0
                    }
5290
0
                    if (geometryFields)
5291
0
                    {
5292
0
                        for (const auto poFieldDefn : poDefn->GetGeomFields())
5293
0
                        {
5294
0
                            const char *fieldName = poFieldDefn->GetNameRef();
5295
0
                            if (fieldName[0] == 0)
5296
0
                                fieldName = OGR_GEOMETRY_DEFAULT_NON_EMPTY_NAME;
5297
0
                            if (currentValue == fieldName)
5298
0
                            {
5299
0
                                ret.clear();
5300
0
                                ret.insert(fieldName);
5301
0
                                break;
5302
0
                            }
5303
0
                            ret.insert(fieldName);
5304
0
                        }
5305
0
                    }
5306
0
                    for (const auto &value : extraValues)
5307
0
                    {
5308
0
                        if (currentValue == value)
5309
0
                        {
5310
0
                            ret.clear();
5311
0
                            ret.insert(value);
5312
0
                            break;
5313
0
                        }
5314
0
                        ret.insert(value);
5315
0
                    }
5316
0
                };
5317
5318
0
                const GDALArgDatasetValue &dsVal = datasetArg[0];
5319
5320
0
                if (!dsVal.GetName().empty())
5321
0
                {
5322
0
                    auto poDS = std::unique_ptr<GDALDataset>(
5323
0
                        GDALDataset::Open(dsVal.GetName().c_str(),
5324
0
                                          GDAL_OF_VECTOR | GDAL_OF_READONLY));
5325
0
                    if (poDS)
5326
0
                    {
5327
0
                        std::vector<std::string> layerNames;
5328
0
                        if (layerNameArg && layerNameArg->IsExplicitlySet())
5329
0
                        {
5330
0
                            if (layerNameArg->GetType() == GAAT_STRING_LIST)
5331
0
                            {
5332
0
                                layerNames =
5333
0
                                    layerNameArg
5334
0
                                        ->Get<std::vector<std::string>>();
5335
0
                            }
5336
0
                            else if (layerNameArg->GetType() == GAAT_STRING)
5337
0
                            {
5338
0
                                layerNames.push_back(
5339
0
                                    layerNameArg->Get<std::string>());
5340
0
                            }
5341
0
                        }
5342
0
                        if (layerNames.empty())
5343
0
                        {
5344
                            // Loop through all layers
5345
0
                            for (const auto *poLayer : poDS->GetLayers())
5346
0
                            {
5347
0
                                getLayerFields(poLayer);
5348
0
                            }
5349
0
                        }
5350
0
                        else
5351
0
                        {
5352
0
                            for (const std::string &layerName : layerNames)
5353
0
                            {
5354
0
                                const auto poLayer =
5355
0
                                    poDS->GetLayerByName(layerName.c_str());
5356
0
                                if (poLayer)
5357
0
                                {
5358
0
                                    getLayerFields(poLayer);
5359
0
                                }
5360
0
                            }
5361
0
                        }
5362
0
                    }
5363
0
                }
5364
0
            }
5365
0
            std::vector<std::string> retVector(ret.begin(), ret.end());
5366
0
            return retVector;
5367
0
        });
5368
0
}
5369
5370
/************************************************************************/
5371
/*                   GDALAlgorithm::AddFieldNameArg()                   */
5372
/************************************************************************/
5373
5374
GDALInConstructionAlgorithmArg &
5375
GDALAlgorithm::AddFieldNameArg(std::string *pValue, const char *helpMessage)
5376
0
{
5377
0
    return AddArg("field-name", 0, MsgOrDefault(helpMessage, _("Field name")),
5378
0
                  pValue);
5379
0
}
5380
5381
/************************************************************************/
5382
/*                GDALAlgorithm::ParseFieldDefinition()                 */
5383
/************************************************************************/
5384
bool GDALAlgorithm::ParseFieldDefinition(const std::string &posStrDef,
5385
                                         OGRFieldDefn *poFieldDefn,
5386
                                         std::string *posError)
5387
0
{
5388
0
    static const std::regex re(
5389
0
        R"(^([^:]+):([^(\s]+)(?:\((\d+)(?:,(\d+))?\))?$)");
5390
0
    std::smatch match;
5391
0
    if (std::regex_match(posStrDef, match, re))
5392
0
    {
5393
0
        const std::string name = match[1];
5394
0
        const std::string type = match[2];
5395
0
        const int width = match[3].matched ? std::stoi(match[3]) : 0;
5396
0
        const int precision = match[4].matched ? std::stoi(match[4]) : 0;
5397
0
        poFieldDefn->SetName(name.c_str());
5398
5399
0
        const auto typeEnum{OGRFieldDefn::GetFieldTypeByName(type.c_str())};
5400
0
        if (typeEnum == OFTString && !EQUAL(type.c_str(), "String"))
5401
0
        {
5402
0
            if (posError)
5403
0
                *posError = "Unsupported field type: " + type;
5404
5405
0
            return false;
5406
0
        }
5407
0
        poFieldDefn->SetType(typeEnum);
5408
0
        poFieldDefn->SetWidth(width);
5409
0
        poFieldDefn->SetPrecision(precision);
5410
0
        return true;
5411
0
    }
5412
5413
0
    if (posError)
5414
0
        *posError = "Invalid field definition format. Expected "
5415
0
                    "<NAME>:<TYPE>[(<WIDTH>[,<PRECISION>])]";
5416
5417
0
    return false;
5418
0
}
5419
5420
/************************************************************************/
5421
/*                GDALAlgorithm::AddFieldDefinitionArg()                */
5422
/************************************************************************/
5423
5424
GDALInConstructionAlgorithmArg &
5425
GDALAlgorithm::AddFieldDefinitionArg(std::vector<std::string> *pValues,
5426
                                     std::vector<OGRFieldDefn> *pFieldDefns,
5427
                                     const char *helpMessage)
5428
0
{
5429
0
    auto &arg =
5430
0
        AddArg("field", 0, MsgOrDefault(helpMessage, _("Field definition")),
5431
0
               pValues)
5432
0
            .SetMetaVar("<NAME>:<TYPE>[(<WIDTH>[,<PRECISION>])]")
5433
0
            .SetPackedValuesAllowed(true)
5434
0
            .SetRepeatedArgAllowed(true);
5435
5436
0
    auto validationFunction = [this, pFieldDefns, pValues]()
5437
0
    {
5438
0
        pFieldDefns->clear();
5439
0
        for (const auto &strValue : *pValues)
5440
0
        {
5441
0
            OGRFieldDefn fieldDefn("", OFTString);
5442
0
            std::string error;
5443
0
            if (!GDALAlgorithm::ParseFieldDefinition(strValue, &fieldDefn,
5444
0
                                                     &error))
5445
0
            {
5446
0
                ReportError(CE_Failure, CPLE_AppDefined, "%s", error.c_str());
5447
0
                return false;
5448
0
            }
5449
            // Check uniqueness of field names
5450
0
            for (const auto &existingFieldDefn : *pFieldDefns)
5451
0
            {
5452
0
                if (EQUAL(existingFieldDefn.GetNameRef(),
5453
0
                          fieldDefn.GetNameRef()))
5454
0
                {
5455
0
                    ReportError(CE_Failure, CPLE_AppDefined,
5456
0
                                "Duplicate field name: '%s'",
5457
0
                                fieldDefn.GetNameRef());
5458
0
                    return false;
5459
0
                }
5460
0
            }
5461
0
            pFieldDefns->push_back(fieldDefn);
5462
0
        }
5463
0
        return true;
5464
0
    };
5465
5466
0
    arg.AddValidationAction(std::move(validationFunction));
5467
5468
0
    return arg;
5469
0
}
5470
5471
/************************************************************************/
5472
/*               GDALAlgorithm::AddFieldTypeSubtypeArg()                */
5473
/************************************************************************/
5474
5475
GDALInConstructionAlgorithmArg &GDALAlgorithm::AddFieldTypeSubtypeArg(
5476
    OGRFieldType *pTypeValue, OGRFieldSubType *pSubtypeValue,
5477
    std::string *pStrValue, const std::string &argName, const char *helpMessage)
5478
0
{
5479
0
    auto &arg =
5480
0
        AddArg(argName.empty() ? std::string("field-type") : argName, 0,
5481
0
               MsgOrDefault(helpMessage, _("Field type or subtype")), pStrValue)
5482
0
            .SetAutoCompleteFunction(
5483
0
                [](const std::string &currentValue)
5484
0
                {
5485
0
                    std::vector<std::string> oRet;
5486
0
                    for (int i = 1; i <= OGRFieldSubType::OFSTMaxSubType; i++)
5487
0
                    {
5488
0
                        const char *pszSubType =
5489
0
                            OGRFieldDefn::GetFieldSubTypeName(
5490
0
                                static_cast<OGRFieldSubType>(i));
5491
0
                        if (pszSubType != nullptr)
5492
0
                        {
5493
0
                            if (currentValue.empty() ||
5494
0
                                STARTS_WITH(pszSubType, currentValue.c_str()))
5495
0
                            {
5496
0
                                oRet.push_back(pszSubType);
5497
0
                            }
5498
0
                        }
5499
0
                    }
5500
5501
0
                    for (int i = 0; i <= OGRFieldType::OFTMaxType; i++)
5502
0
                    {
5503
                        // Skip deprecated
5504
0
                        if (static_cast<OGRFieldType>(i) ==
5505
0
                                OGRFieldType::OFTWideString ||
5506
0
                            static_cast<OGRFieldType>(i) ==
5507
0
                                OGRFieldType::OFTWideStringList)
5508
0
                            continue;
5509
0
                        const char *pszType = OGRFieldDefn::GetFieldTypeName(
5510
0
                            static_cast<OGRFieldType>(i));
5511
0
                        if (pszType != nullptr)
5512
0
                        {
5513
0
                            if (currentValue.empty() ||
5514
0
                                STARTS_WITH(pszType, currentValue.c_str()))
5515
0
                            {
5516
0
                                oRet.push_back(pszType);
5517
0
                            }
5518
0
                        }
5519
0
                    }
5520
0
                    return oRet;
5521
0
                });
5522
5523
0
    auto validationFunction =
5524
0
        [this, &arg, pTypeValue, pSubtypeValue, pStrValue]()
5525
0
    {
5526
0
        bool isValid{true};
5527
0
        *pTypeValue = OGRFieldDefn::GetFieldTypeByName(pStrValue->c_str());
5528
5529
        // String is returned for unknown types
5530
0
        if (!EQUAL(pStrValue->c_str(), "String") && *pTypeValue == OFTString)
5531
0
        {
5532
0
            isValid = false;
5533
0
        }
5534
5535
0
        *pSubtypeValue =
5536
0
            OGRFieldDefn::GetFieldSubTypeByName(pStrValue->c_str());
5537
5538
0
        if (*pSubtypeValue != OFSTNone)
5539
0
        {
5540
0
            isValid = true;
5541
0
            switch (*pSubtypeValue)
5542
0
            {
5543
0
                case OFSTBoolean:
5544
0
                case OFSTInt16:
5545
0
                {
5546
0
                    *pTypeValue = OFTInteger;
5547
0
                    break;
5548
0
                }
5549
0
                case OFSTFloat32:
5550
0
                {
5551
0
                    *pTypeValue = OFTReal;
5552
0
                    break;
5553
0
                }
5554
0
                default:
5555
0
                {
5556
0
                    *pTypeValue = OFTString;
5557
0
                    break;
5558
0
                }
5559
0
            }
5560
0
        }
5561
5562
0
        if (!isValid)
5563
0
        {
5564
0
            ReportError(CE_Failure, CPLE_AppDefined,
5565
0
                        "Invalid value for argument '%s': '%s'",
5566
0
                        arg.GetName().c_str(), pStrValue->c_str());
5567
0
        }
5568
5569
0
        return isValid;
5570
0
    };
5571
5572
0
    if (!pStrValue->empty())
5573
0
    {
5574
0
        arg.SetDefault(*pStrValue);
5575
0
        validationFunction();
5576
0
    }
5577
5578
0
    arg.AddValidationAction(std::move(validationFunction));
5579
5580
0
    return arg;
5581
0
}
5582
5583
/************************************************************************/
5584
/*                   GDALAlgorithm::ValidateBandArg()                   */
5585
/************************************************************************/
5586
5587
bool GDALAlgorithm::ValidateBandArg() const
5588
0
{
5589
0
    bool ret = true;
5590
0
    const auto bandArg = GetArg(GDAL_ARG_NAME_BAND);
5591
0
    const auto inputDatasetArg = GetArg(GDAL_ARG_NAME_INPUT);
5592
0
    if (bandArg && bandArg->IsExplicitlySet() && inputDatasetArg &&
5593
0
        (inputDatasetArg->GetType() == GAAT_DATASET ||
5594
0
         inputDatasetArg->GetType() == GAAT_DATASET_LIST) &&
5595
0
        (inputDatasetArg->GetDatasetType() & GDAL_OF_RASTER) != 0)
5596
0
    {
5597
0
        const auto CheckBand = [this](const GDALDataset *poDS, int nBand)
5598
0
        {
5599
0
            if (nBand > poDS->GetRasterCount())
5600
0
            {
5601
0
                ReportError(CE_Failure, CPLE_AppDefined,
5602
0
                            "Value of 'band' should be greater or equal than "
5603
0
                            "1 and less or equal than %d.",
5604
0
                            poDS->GetRasterCount());
5605
0
                return false;
5606
0
            }
5607
0
            return true;
5608
0
        };
5609
5610
0
        const auto ValidateForOneDataset =
5611
0
            [&bandArg, &CheckBand](const GDALDataset *poDS)
5612
0
        {
5613
0
            bool l_ret = true;
5614
0
            if (bandArg->GetType() == GAAT_INTEGER)
5615
0
            {
5616
0
                l_ret = CheckBand(poDS, bandArg->Get<int>());
5617
0
            }
5618
0
            else if (bandArg->GetType() == GAAT_INTEGER_LIST)
5619
0
            {
5620
0
                for (int nBand : bandArg->Get<std::vector<int>>())
5621
0
                {
5622
0
                    l_ret = l_ret && CheckBand(poDS, nBand);
5623
0
                }
5624
0
            }
5625
0
            return l_ret;
5626
0
        };
5627
5628
0
        if (inputDatasetArg->GetType() == GAAT_DATASET)
5629
0
        {
5630
0
            auto poDS =
5631
0
                inputDatasetArg->Get<GDALArgDatasetValue>().GetDatasetRef();
5632
0
            if (poDS && !ValidateForOneDataset(poDS))
5633
0
                ret = false;
5634
0
        }
5635
0
        else
5636
0
        {
5637
0
            CPLAssert(inputDatasetArg->GetType() == GAAT_DATASET_LIST);
5638
0
            for (auto &datasetValue :
5639
0
                 inputDatasetArg->Get<std::vector<GDALArgDatasetValue>>())
5640
0
            {
5641
0
                auto poDS = datasetValue.GetDatasetRef();
5642
0
                if (poDS && !ValidateForOneDataset(poDS))
5643
0
                    ret = false;
5644
0
            }
5645
0
        }
5646
0
    }
5647
0
    return ret;
5648
0
}
5649
5650
/************************************************************************/
5651
/*            GDALAlgorithm::RunPreStepPipelineValidations()            */
5652
/************************************************************************/
5653
5654
bool GDALAlgorithm::RunPreStepPipelineValidations() const
5655
0
{
5656
0
    return ValidateBandArg();
5657
0
}
5658
5659
/************************************************************************/
5660
/*                     GDALAlgorithm::AddBandArg()                      */
5661
/************************************************************************/
5662
5663
GDALInConstructionAlgorithmArg &
5664
GDALAlgorithm::AddBandArg(int *pValue, const char *helpMessage)
5665
0
{
5666
0
    AddValidationAction([this]() { return ValidateBandArg(); });
5667
5668
0
    return AddArg(GDAL_ARG_NAME_BAND, 'b',
5669
0
                  MsgOrDefault(helpMessage, _("Input band (1-based index)")),
5670
0
                  pValue)
5671
0
        .AddValidationAction(
5672
0
            [pValue]()
5673
0
            {
5674
0
                if (*pValue <= 0)
5675
0
                {
5676
0
                    CPLError(CE_Failure, CPLE_AppDefined,
5677
0
                             "Value of 'band' should greater or equal to 1.");
5678
0
                    return false;
5679
0
                }
5680
0
                return true;
5681
0
            });
5682
0
}
5683
5684
/************************************************************************/
5685
/*                     GDALAlgorithm::AddBandArg()                      */
5686
/************************************************************************/
5687
5688
GDALInConstructionAlgorithmArg &
5689
GDALAlgorithm::AddBandArg(std::vector<int> *pValue, const char *helpMessage)
5690
0
{
5691
0
    AddValidationAction([this]() { return ValidateBandArg(); });
5692
5693
0
    return AddArg(GDAL_ARG_NAME_BAND, 'b',
5694
0
                  MsgOrDefault(helpMessage, _("Input band(s) (1-based index)")),
5695
0
                  pValue)
5696
0
        .AddValidationAction(
5697
0
            [pValue]()
5698
0
            {
5699
0
                for (int val : *pValue)
5700
0
                {
5701
0
                    if (val <= 0)
5702
0
                    {
5703
0
                        CPLError(CE_Failure, CPLE_AppDefined,
5704
0
                                 "Value of 'band' should greater or equal "
5705
0
                                 "to 1.");
5706
0
                        return false;
5707
0
                    }
5708
0
                }
5709
0
                return true;
5710
0
            });
5711
0
}
5712
5713
/************************************************************************/
5714
/*                      ParseAndValidateKeyValue()                      */
5715
/************************************************************************/
5716
5717
bool GDALAlgorithm::ParseAndValidateKeyValue(GDALAlgorithmArg &arg)
5718
0
{
5719
0
    const auto Validate = [this, &arg](const std::string &val)
5720
0
    {
5721
0
        if (val.find('=') == std::string::npos)
5722
0
        {
5723
0
            ReportError(
5724
0
                CE_Failure, CPLE_AppDefined,
5725
0
                "Invalid value for argument '%s'. <KEY>=<VALUE> expected",
5726
0
                arg.GetName().c_str());
5727
0
            return false;
5728
0
        }
5729
5730
0
        return true;
5731
0
    };
5732
5733
0
    if (arg.GetType() == GAAT_STRING)
5734
0
    {
5735
0
        return Validate(arg.Get<std::string>());
5736
0
    }
5737
0
    else if (arg.GetType() == GAAT_STRING_LIST)
5738
0
    {
5739
0
        std::vector<std::string> &vals = arg.Get<std::vector<std::string>>();
5740
0
        if (vals.size() == 1)
5741
0
        {
5742
            // Try to split A=B,C=D into A=B and C=D if there is no ambiguity
5743
0
            std::vector<std::string> newVals;
5744
0
            std::string curToken;
5745
0
            bool canSplitOnComma = true;
5746
0
            char lastSep = 0;
5747
0
            bool inString = false;
5748
0
            bool equalFoundInLastToken = false;
5749
0
            for (char c : vals[0])
5750
0
            {
5751
0
                if (!inString && c == ',')
5752
0
                {
5753
0
                    if (lastSep != '=' || !equalFoundInLastToken)
5754
0
                    {
5755
0
                        canSplitOnComma = false;
5756
0
                        break;
5757
0
                    }
5758
0
                    lastSep = c;
5759
0
                    newVals.push_back(curToken);
5760
0
                    curToken.clear();
5761
0
                    equalFoundInLastToken = false;
5762
0
                }
5763
0
                else if (!inString && c == '=')
5764
0
                {
5765
0
                    if (lastSep == '=')
5766
0
                    {
5767
0
                        canSplitOnComma = false;
5768
0
                        break;
5769
0
                    }
5770
0
                    equalFoundInLastToken = true;
5771
0
                    lastSep = c;
5772
0
                    curToken += c;
5773
0
                }
5774
0
                else if (c == '"')
5775
0
                {
5776
0
                    inString = !inString;
5777
0
                    curToken += c;
5778
0
                }
5779
0
                else
5780
0
                {
5781
0
                    curToken += c;
5782
0
                }
5783
0
            }
5784
0
            if (canSplitOnComma && !inString && equalFoundInLastToken)
5785
0
            {
5786
0
                if (!curToken.empty())
5787
0
                    newVals.emplace_back(std::move(curToken));
5788
0
                vals = std::move(newVals);
5789
0
            }
5790
0
        }
5791
5792
0
        for (const auto &val : vals)
5793
0
        {
5794
0
            if (!Validate(val))
5795
0
                return false;
5796
0
        }
5797
0
    }
5798
5799
0
    return true;
5800
0
}
5801
5802
/************************************************************************/
5803
/*                           IsGDALGOutput()                            */
5804
/************************************************************************/
5805
5806
bool GDALAlgorithm::IsGDALGOutput() const
5807
0
{
5808
0
    bool isGDALGOutput = false;
5809
0
    const auto outputFormatArg = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
5810
0
    const auto outputArg = GetArg(GDAL_ARG_NAME_OUTPUT);
5811
0
    if (outputArg && outputArg->GetType() == GAAT_DATASET &&
5812
0
        outputArg->IsExplicitlySet())
5813
0
    {
5814
0
        if (outputFormatArg && outputFormatArg->GetType() == GAAT_STRING &&
5815
0
            outputFormatArg->IsExplicitlySet())
5816
0
        {
5817
0
            const auto &val =
5818
0
                outputFormatArg->GDALAlgorithmArg::Get<std::string>();
5819
0
            isGDALGOutput = EQUAL(val.c_str(), "GDALG");
5820
0
        }
5821
0
        else
5822
0
        {
5823
0
            const auto &filename =
5824
0
                outputArg->GDALAlgorithmArg::Get<GDALArgDatasetValue>();
5825
0
            isGDALGOutput =
5826
0
                filename.GetName().size() > strlen(".gdalg.json") &&
5827
0
                EQUAL(filename.GetName().c_str() + filename.GetName().size() -
5828
0
                          strlen(".gdalg.json"),
5829
0
                      ".gdalg.json");
5830
0
        }
5831
0
    }
5832
0
    return isGDALGOutput;
5833
0
}
5834
5835
/************************************************************************/
5836
/*                         ProcessGDALGOutput()                         */
5837
/************************************************************************/
5838
5839
GDALAlgorithm::ProcessGDALGOutputRet GDALAlgorithm::ProcessGDALGOutput()
5840
0
{
5841
0
    if (!SupportsStreamedOutput())
5842
0
        return ProcessGDALGOutputRet::NOT_GDALG;
5843
5844
0
    if (IsGDALGOutput())
5845
0
    {
5846
0
        const auto outputArg = GetArg(GDAL_ARG_NAME_OUTPUT);
5847
0
        const auto &filename =
5848
0
            outputArg->GDALAlgorithmArg::Get<GDALArgDatasetValue>().GetName();
5849
0
        VSIStatBufL sStat;
5850
0
        if (VSIStatL(filename.c_str(), &sStat) == 0)
5851
0
        {
5852
0
            const auto overwriteArg = GetArg(GDAL_ARG_NAME_OVERWRITE);
5853
0
            if (overwriteArg && overwriteArg->GetType() == GAAT_BOOLEAN)
5854
0
            {
5855
0
                if (!overwriteArg->GDALAlgorithmArg::Get<bool>())
5856
0
                {
5857
0
                    CPLError(CE_Failure, CPLE_AppDefined,
5858
0
                             "File '%s' already exists. Specify the "
5859
0
                             "--overwrite option to overwrite it.",
5860
0
                             filename.c_str());
5861
0
                    return ProcessGDALGOutputRet::GDALG_ERROR;
5862
0
                }
5863
0
            }
5864
0
        }
5865
5866
0
        std::string osCommandLine;
5867
5868
0
        for (const auto &path : GDALAlgorithm::m_callPath)
5869
0
        {
5870
0
            if (!osCommandLine.empty())
5871
0
                osCommandLine += ' ';
5872
0
            osCommandLine += path;
5873
0
        }
5874
5875
0
        for (const auto &arg : GetArgs())
5876
0
        {
5877
0
            if (arg->IsExplicitlySet() &&
5878
0
                arg->GetName() != GDAL_ARG_NAME_OUTPUT &&
5879
0
                arg->GetName() != GDAL_ARG_NAME_OUTPUT_FORMAT &&
5880
0
                arg->GetName() != GDAL_ARG_NAME_UPDATE &&
5881
0
                arg->GetName() != GDAL_ARG_NAME_OVERWRITE)
5882
0
            {
5883
0
                osCommandLine += ' ';
5884
0
                std::string strArg;
5885
0
                if (!arg->Serialize(strArg))
5886
0
                {
5887
0
                    CPLError(CE_Failure, CPLE_AppDefined,
5888
0
                             "Cannot serialize argument %s",
5889
0
                             arg->GetName().c_str());
5890
0
                    return ProcessGDALGOutputRet::GDALG_ERROR;
5891
0
                }
5892
0
                osCommandLine += strArg;
5893
0
            }
5894
0
        }
5895
5896
0
        osCommandLine += " --output-format stream --output streamed_dataset";
5897
5898
0
        std::string outStringUnused;
5899
0
        return SaveGDALG(filename, outStringUnused, osCommandLine)
5900
0
                   ? ProcessGDALGOutputRet::GDALG_OK
5901
0
                   : ProcessGDALGOutputRet::GDALG_ERROR;
5902
0
    }
5903
5904
0
    return ProcessGDALGOutputRet::NOT_GDALG;
5905
0
}
5906
5907
/************************************************************************/
5908
/*                      GDALAlgorithm::SaveGDALG()                      */
5909
/************************************************************************/
5910
5911
/* static */ bool GDALAlgorithm::SaveGDALG(const std::string &filename,
5912
                                           std::string &outString,
5913
                                           const std::string &commandLine)
5914
0
{
5915
0
    CPLJSONDocument oDoc;
5916
0
    oDoc.GetRoot().Add("type", "gdal_streamed_alg");
5917
0
    oDoc.GetRoot().Add("command_line", commandLine);
5918
0
    oDoc.GetRoot().Add("gdal_version", GDALVersionInfo("VERSION_NUM"));
5919
5920
0
    if (!filename.empty())
5921
0
        return oDoc.Save(filename);
5922
5923
0
    outString = oDoc.GetRoot().Format(CPLJSONObject::PrettyFormat::Pretty);
5924
0
    return true;
5925
0
}
5926
5927
/************************************************************************/
5928
/*                GDALAlgorithm::AddCreationOptionsArg()                */
5929
/************************************************************************/
5930
5931
GDALInConstructionAlgorithmArg &
5932
GDALAlgorithm::AddCreationOptionsArg(std::vector<std::string> *pValue,
5933
                                     const char *helpMessage)
5934
0
{
5935
0
    auto &arg = AddArg(GDAL_ARG_NAME_CREATION_OPTION, 0,
5936
0
                       MsgOrDefault(helpMessage, _("Creation option")), pValue)
5937
0
                    .AddAlias("co")
5938
0
                    .SetMetaVar("<KEY>=<VALUE>")
5939
0
                    .SetPackedValuesAllowed(false);
5940
0
    arg.AddValidationAction([this, &arg]()
5941
0
                            { return ParseAndValidateKeyValue(arg); });
5942
5943
0
    arg.SetAutoCompleteFunction(
5944
0
        [this](const std::string &currentValue)
5945
0
        {
5946
0
            std::vector<std::string> oRet;
5947
5948
0
            int datasetType =
5949
0
                GDAL_OF_RASTER | GDAL_OF_VECTOR | GDAL_OF_MULTIDIM_RASTER;
5950
0
            auto outputArg = GetArg(GDAL_ARG_NAME_OUTPUT);
5951
0
            if (outputArg && (outputArg->GetType() == GAAT_DATASET ||
5952
0
                              outputArg->GetType() == GAAT_DATASET_LIST))
5953
0
            {
5954
0
                datasetType = outputArg->GetDatasetType();
5955
0
            }
5956
5957
0
            const char *pszMDCreationOptionList =
5958
0
                (datasetType == GDAL_OF_MULTIDIM_RASTER)
5959
0
                    ? GDAL_DMD_MULTIDIM_DATASET_CREATIONOPTIONLIST
5960
0
                    : GDAL_DMD_CREATIONOPTIONLIST;
5961
5962
0
            auto outputFormat = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
5963
0
            if (outputFormat && outputFormat->GetType() == GAAT_STRING &&
5964
0
                outputFormat->IsExplicitlySet())
5965
0
            {
5966
0
                auto poDriver = GetGDALDriverManager()->GetDriverByName(
5967
0
                    outputFormat->Get<std::string>().c_str());
5968
0
                if (poDriver)
5969
0
                {
5970
0
                    AddOptionsSuggestions(
5971
0
                        poDriver->GetMetadataItem(pszMDCreationOptionList),
5972
0
                        datasetType, currentValue, oRet);
5973
0
                }
5974
0
                return oRet;
5975
0
            }
5976
5977
0
            if (outputArg && outputArg->GetType() == GAAT_DATASET)
5978
0
            {
5979
0
                auto poDM = GetGDALDriverManager();
5980
0
                auto &datasetValue = outputArg->Get<GDALArgDatasetValue>();
5981
0
                const auto &osDSName = datasetValue.GetName();
5982
0
                const std::string osExt = CPLGetExtensionSafe(osDSName.c_str());
5983
0
                if (!osExt.empty())
5984
0
                {
5985
0
                    std::set<std::string> oVisitedExtensions;
5986
0
                    for (int i = 0; i < poDM->GetDriverCount(); ++i)
5987
0
                    {
5988
0
                        auto poDriver = poDM->GetDriver(i);
5989
0
                        if (((datasetType & GDAL_OF_RASTER) != 0 &&
5990
0
                             poDriver->GetMetadataItem(GDAL_DCAP_RASTER)) ||
5991
0
                            ((datasetType & GDAL_OF_VECTOR) != 0 &&
5992
0
                             poDriver->GetMetadataItem(GDAL_DCAP_VECTOR)) ||
5993
0
                            ((datasetType & GDAL_OF_MULTIDIM_RASTER) != 0 &&
5994
0
                             poDriver->GetMetadataItem(
5995
0
                                 GDAL_DCAP_MULTIDIM_RASTER)))
5996
0
                        {
5997
0
                            const char *pszExtensions =
5998
0
                                poDriver->GetMetadataItem(GDAL_DMD_EXTENSIONS);
5999
0
                            if (pszExtensions)
6000
0
                            {
6001
0
                                const CPLStringList aosExts(
6002
0
                                    CSLTokenizeString2(pszExtensions, " ", 0));
6003
0
                                for (const char *pszExt : cpl::Iterate(aosExts))
6004
0
                                {
6005
0
                                    if (EQUAL(pszExt, osExt.c_str()) &&
6006
0
                                        !cpl::contains(oVisitedExtensions,
6007
0
                                                       pszExt))
6008
0
                                    {
6009
0
                                        oVisitedExtensions.insert(pszExt);
6010
0
                                        if (AddOptionsSuggestions(
6011
0
                                                poDriver->GetMetadataItem(
6012
0
                                                    pszMDCreationOptionList),
6013
0
                                                datasetType, currentValue,
6014
0
                                                oRet))
6015
0
                                        {
6016
0
                                            return oRet;
6017
0
                                        }
6018
0
                                        break;
6019
0
                                    }
6020
0
                                }
6021
0
                            }
6022
0
                        }
6023
0
                    }
6024
0
                }
6025
0
            }
6026
6027
0
            return oRet;
6028
0
        });
6029
6030
0
    return arg;
6031
0
}
6032
6033
/************************************************************************/
6034
/*             GDALAlgorithm::AddLayerCreationOptionsArg()              */
6035
/************************************************************************/
6036
6037
GDALInConstructionAlgorithmArg &
6038
GDALAlgorithm::AddLayerCreationOptionsArg(std::vector<std::string> *pValue,
6039
                                          const char *helpMessage)
6040
0
{
6041
0
    auto &arg =
6042
0
        AddArg(GDAL_ARG_NAME_LAYER_CREATION_OPTION, 0,
6043
0
               MsgOrDefault(helpMessage, _("Layer creation option")), pValue)
6044
0
            .AddAlias("lco")
6045
0
            .SetMetaVar("<KEY>=<VALUE>")
6046
0
            .SetPackedValuesAllowed(false);
6047
0
    arg.AddValidationAction([this, &arg]()
6048
0
                            { return ParseAndValidateKeyValue(arg); });
6049
6050
0
    arg.SetAutoCompleteFunction(
6051
0
        [this](const std::string &currentValue)
6052
0
        {
6053
0
            std::vector<std::string> oRet;
6054
6055
0
            auto outputFormat = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
6056
0
            if (outputFormat && outputFormat->GetType() == GAAT_STRING &&
6057
0
                outputFormat->IsExplicitlySet())
6058
0
            {
6059
0
                auto poDriver = GetGDALDriverManager()->GetDriverByName(
6060
0
                    outputFormat->Get<std::string>().c_str());
6061
0
                if (poDriver)
6062
0
                {
6063
0
                    AddOptionsSuggestions(poDriver->GetMetadataItem(
6064
0
                                              GDAL_DS_LAYER_CREATIONOPTIONLIST),
6065
0
                                          GDAL_OF_VECTOR, currentValue, oRet);
6066
0
                }
6067
0
                return oRet;
6068
0
            }
6069
6070
0
            auto outputArg = GetArg(GDAL_ARG_NAME_OUTPUT);
6071
0
            if (outputArg && outputArg->GetType() == GAAT_DATASET)
6072
0
            {
6073
0
                auto poDM = GetGDALDriverManager();
6074
0
                auto &datasetValue = outputArg->Get<GDALArgDatasetValue>();
6075
0
                const auto &osDSName = datasetValue.GetName();
6076
0
                const std::string osExt = CPLGetExtensionSafe(osDSName.c_str());
6077
0
                if (!osExt.empty())
6078
0
                {
6079
0
                    std::set<std::string> oVisitedExtensions;
6080
0
                    for (int i = 0; i < poDM->GetDriverCount(); ++i)
6081
0
                    {
6082
0
                        auto poDriver = poDM->GetDriver(i);
6083
0
                        if (poDriver->GetMetadataItem(GDAL_DCAP_VECTOR))
6084
0
                        {
6085
0
                            const char *pszExtensions =
6086
0
                                poDriver->GetMetadataItem(GDAL_DMD_EXTENSIONS);
6087
0
                            if (pszExtensions)
6088
0
                            {
6089
0
                                const CPLStringList aosExts(
6090
0
                                    CSLTokenizeString2(pszExtensions, " ", 0));
6091
0
                                for (const char *pszExt : cpl::Iterate(aosExts))
6092
0
                                {
6093
0
                                    if (EQUAL(pszExt, osExt.c_str()) &&
6094
0
                                        !cpl::contains(oVisitedExtensions,
6095
0
                                                       pszExt))
6096
0
                                    {
6097
0
                                        oVisitedExtensions.insert(pszExt);
6098
0
                                        if (AddOptionsSuggestions(
6099
0
                                                poDriver->GetMetadataItem(
6100
0
                                                    GDAL_DS_LAYER_CREATIONOPTIONLIST),
6101
0
                                                GDAL_OF_VECTOR, currentValue,
6102
0
                                                oRet))
6103
0
                                        {
6104
0
                                            return oRet;
6105
0
                                        }
6106
0
                                        break;
6107
0
                                    }
6108
0
                                }
6109
0
                            }
6110
0
                        }
6111
0
                    }
6112
0
                }
6113
0
            }
6114
6115
0
            return oRet;
6116
0
        });
6117
6118
0
    return arg;
6119
0
}
6120
6121
/************************************************************************/
6122
/*                     GDALAlgorithm::AddBBOXArg()                      */
6123
/************************************************************************/
6124
6125
/** Add bbox=xmin,ymin,xmax,ymax argument. */
6126
GDALInConstructionAlgorithmArg &
6127
GDALAlgorithm::AddBBOXArg(std::vector<double> *pValue, const char *helpMessage)
6128
0
{
6129
0
    auto &arg = AddArg("bbox", 0,
6130
0
                       MsgOrDefault(helpMessage,
6131
0
                                    _("Bounding box as xmin,ymin,xmax,ymax")),
6132
0
                       pValue)
6133
0
                    .SetRepeatedArgAllowed(false)
6134
0
                    .SetMinCount(4)
6135
0
                    .SetMaxCount(4)
6136
0
                    .SetDisplayHintAboutRepetition(false);
6137
0
    arg.AddValidationAction(
6138
0
        [&arg]()
6139
0
        {
6140
0
            const auto &val = arg.Get<std::vector<double>>();
6141
0
            CPLAssert(val.size() == 4);
6142
0
            if (!(val[0] <= val[2]) || !(val[1] <= val[3]))
6143
0
            {
6144
0
                CPLError(CE_Failure, CPLE_AppDefined,
6145
0
                         "Value of 'bbox' should be xmin,ymin,xmax,ymax with "
6146
0
                         "xmin <= xmax and ymin <= ymax");
6147
0
                return false;
6148
0
            }
6149
0
            return true;
6150
0
        });
6151
0
    return arg;
6152
0
}
6153
6154
/************************************************************************/
6155
/*                  GDALAlgorithm::AddActiveLayerArg()                  */
6156
/************************************************************************/
6157
6158
GDALInConstructionAlgorithmArg &
6159
GDALAlgorithm::AddActiveLayerArg(std::string *pValue, const char *helpMessage)
6160
0
{
6161
0
    return AddArg("active-layer", 0,
6162
0
                  MsgOrDefault(helpMessage,
6163
0
                               _("Set active layer (if not specified, all)")),
6164
0
                  pValue);
6165
0
}
6166
6167
/************************************************************************/
6168
/*                  GDALAlgorithm::AddNumThreadsArg()                   */
6169
/************************************************************************/
6170
6171
GDALInConstructionAlgorithmArg &
6172
GDALAlgorithm::AddNumThreadsArg(int *pValue, std::string *pStrValue,
6173
                                const char *helpMessage)
6174
0
{
6175
0
    auto &arg =
6176
0
        AddArg(GDAL_ARG_NAME_NUM_THREADS, 'j',
6177
0
               MsgOrDefault(helpMessage, _("Number of jobs (or ALL_CPUS)")),
6178
0
               pStrValue);
6179
6180
0
    AddArg(GDAL_ARG_NAME_NUM_THREADS_INT_HIDDEN, 0,
6181
0
           _("Number of jobs (read-only, hidden argument)"), pValue)
6182
0
        .SetHidden();
6183
6184
0
    auto lambda = [this, &arg, pValue, pStrValue]
6185
0
    {
6186
0
        bool bOK = false;
6187
0
        const char *pszVal = CPLGetConfigOption("GDAL_NUM_THREADS", nullptr);
6188
0
        const int nLimit = std::clamp(
6189
0
            pszVal && !EQUAL(pszVal, "ALL_CPUS") ? atoi(pszVal) : INT_MAX, 1,
6190
0
            CPLGetNumCPUs());
6191
0
        const int nNumThreads =
6192
0
            GDALGetNumThreads(pStrValue->c_str(), nLimit,
6193
0
                              /* bDefaultToAllCPUs = */ false, nullptr, &bOK);
6194
0
        if (bOK)
6195
0
        {
6196
0
            *pValue = nNumThreads;
6197
0
        }
6198
0
        else
6199
0
        {
6200
0
            ReportError(CE_Failure, CPLE_IllegalArg,
6201
0
                        "Invalid value for '%s' argument",
6202
0
                        arg.GetName().c_str());
6203
0
        }
6204
0
        return bOK;
6205
0
    };
6206
0
    if (!pStrValue->empty())
6207
0
    {
6208
0
        arg.SetDefault(*pStrValue);
6209
0
        lambda();
6210
0
    }
6211
0
    arg.AddValidationAction(std::move(lambda));
6212
0
    return arg;
6213
0
}
6214
6215
/************************************************************************/
6216
/*                 GDALAlgorithm::AddAbsolutePathArg()                  */
6217
/************************************************************************/
6218
6219
GDALInConstructionAlgorithmArg &
6220
GDALAlgorithm::AddAbsolutePathArg(bool *pValue, const char *helpMessage)
6221
0
{
6222
0
    return AddArg(
6223
0
        "absolute-path", 0,
6224
0
        MsgOrDefault(helpMessage, _("Whether the path to the input dataset "
6225
0
                                    "should be stored as an absolute path")),
6226
0
        pValue);
6227
0
}
6228
6229
/************************************************************************/
6230
/*               GDALAlgorithm::AddPixelFunctionNameArg()               */
6231
/************************************************************************/
6232
6233
GDALInConstructionAlgorithmArg &
6234
GDALAlgorithm::AddPixelFunctionNameArg(std::string *pValue,
6235
                                       const char *helpMessage)
6236
0
{
6237
6238
0
    const auto pixelFunctionNames =
6239
0
        VRTDerivedRasterBand::GetPixelFunctionNames();
6240
0
    return AddArg(
6241
0
               "pixel-function", 0,
6242
0
               MsgOrDefault(
6243
0
                   helpMessage,
6244
0
                   _("Specify a pixel function to calculate output value from "
6245
0
                     "overlapping inputs")),
6246
0
               pValue)
6247
0
        .SetChoices(pixelFunctionNames);
6248
0
}
6249
6250
/************************************************************************/
6251
/*               GDALAlgorithm::AddPixelFunctionArgsArg()               */
6252
/************************************************************************/
6253
6254
GDALInConstructionAlgorithmArg &
6255
GDALAlgorithm::AddPixelFunctionArgsArg(std::vector<std::string> *pValue,
6256
                                       const char *helpMessage)
6257
0
{
6258
0
    auto &pixelFunctionArgArg =
6259
0
        AddArg("pixel-function-arg", 0,
6260
0
               MsgOrDefault(
6261
0
                   helpMessage,
6262
0
                   _("Specify argument(s) to pass to the pixel function")),
6263
0
               pValue)
6264
0
            .SetMetaVar("<NAME>=<VALUE>")
6265
0
            .SetRepeatedArgAllowed(true);
6266
0
    pixelFunctionArgArg.AddValidationAction(
6267
0
        [this, &pixelFunctionArgArg]()
6268
0
        { return ParseAndValidateKeyValue(pixelFunctionArgArg); });
6269
6270
0
    pixelFunctionArgArg.SetAutoCompleteFunction(
6271
0
        [this](const std::string &currentValue)
6272
0
        {
6273
0
            std::string pixelFunction;
6274
0
            const auto pixelFunctionArg = GetArg("pixel-function");
6275
0
            if (pixelFunctionArg && pixelFunctionArg->GetType() == GAAT_STRING)
6276
0
            {
6277
0
                pixelFunction = pixelFunctionArg->Get<std::string>();
6278
0
            }
6279
6280
0
            std::vector<std::string> ret;
6281
6282
0
            if (!pixelFunction.empty())
6283
0
            {
6284
0
                const auto *pair = VRTDerivedRasterBand::GetPixelFunction(
6285
0
                    pixelFunction.c_str());
6286
0
                if (!pair)
6287
0
                {
6288
0
                    ret.push_back("**");
6289
                    // Non printable UTF-8 space, to avoid autocompletion to pickup on 'd'
6290
0
                    ret.push_back(std::string("\xC2\xA0"
6291
0
                                              "Invalid pixel function name"));
6292
0
                }
6293
0
                else if (pair->second.find("Argument name=") ==
6294
0
                         std::string::npos)
6295
0
                {
6296
0
                    ret.push_back("**");
6297
                    // Non printable UTF-8 space, to avoid autocompletion to pickup on 'd'
6298
0
                    ret.push_back(
6299
0
                        std::string(
6300
0
                            "\xC2\xA0"
6301
0
                            "No pixel function arguments for pixel function '")
6302
0
                            .append(pixelFunction)
6303
0
                            .append("'"));
6304
0
                }
6305
0
                else
6306
0
                {
6307
0
                    AddOptionsSuggestions(pair->second.c_str(), 0, currentValue,
6308
0
                                          ret);
6309
0
                }
6310
0
            }
6311
6312
0
            return ret;
6313
0
        });
6314
6315
0
    return pixelFunctionArgArg;
6316
0
}
6317
6318
/************************************************************************/
6319
/*                   GDALAlgorithm::AddProgressArg()                    */
6320
/************************************************************************/
6321
6322
void GDALAlgorithm::AddProgressArg(bool hidden)
6323
0
{
6324
0
    auto &arg =
6325
0
        AddArg(GDAL_ARG_NAME_QUIET, 'q',
6326
0
               _("Quiet mode (no progress bar or warning message)"), &m_quiet)
6327
0
            .SetAvailableInPipelineStep(false)
6328
0
            .SetCategory(GAAC_COMMON)
6329
0
            .AddAction([this]() { m_progressBarRequested = false; });
6330
0
    if (hidden)
6331
0
        arg.SetHidden();
6332
6333
0
    AddArg("progress", 0, _("Display progress bar"), &m_progressBarRequested)
6334
0
        .SetAvailableInPipelineStep(false)
6335
0
        .SetHidden();
6336
0
}
6337
6338
/************************************************************************/
6339
/*                         GDALAlgorithm::Run()                         */
6340
/************************************************************************/
6341
6342
bool GDALAlgorithm::Run(GDALProgressFunc pfnProgress, void *pProgressData)
6343
0
{
6344
0
    WarnIfDeprecated();
6345
6346
0
    if (m_selectedSubAlg)
6347
0
    {
6348
0
        if (m_calledFromCommandLine)
6349
0
            m_selectedSubAlg->m_calledFromCommandLine = true;
6350
0
        return m_selectedSubAlg->Run(pfnProgress, pProgressData);
6351
0
    }
6352
6353
0
    if (m_helpRequested || m_helpDocRequested)
6354
0
    {
6355
0
        if (m_calledFromCommandLine)
6356
0
            printf("%s", GetUsageForCLI(false).c_str()); /*ok*/
6357
0
        return true;
6358
0
    }
6359
6360
0
    if (m_JSONUsageRequested)
6361
0
    {
6362
0
        if (m_calledFromCommandLine)
6363
0
            printf("%s", GetUsageAsJSON().c_str()); /*ok*/
6364
0
        return true;
6365
0
    }
6366
6367
0
    if (!ValidateArguments())
6368
0
        return false;
6369
6370
0
    if (m_alreadyRun)
6371
0
    {
6372
0
        ReportError(CE_Failure, CPLE_AppDefined,
6373
0
                    "Run() can be called only once per algorithm instance");
6374
0
        return false;
6375
0
    }
6376
0
    m_alreadyRun = true;
6377
6378
0
    switch (ProcessGDALGOutput())
6379
0
    {
6380
0
        case ProcessGDALGOutputRet::GDALG_ERROR:
6381
0
            return false;
6382
6383
0
        case ProcessGDALGOutputRet::GDALG_OK:
6384
0
            return true;
6385
6386
0
        case ProcessGDALGOutputRet::NOT_GDALG:
6387
0
            break;
6388
0
    }
6389
6390
0
    if (m_executionForStreamOutput)
6391
0
    {
6392
0
        if (!CheckSafeForStreamOutput())
6393
0
        {
6394
0
            return false;
6395
0
        }
6396
0
    }
6397
6398
0
    return RunImpl(pfnProgress, pProgressData);
6399
0
}
6400
6401
/************************************************************************/
6402
/*              GDALAlgorithm::CheckSafeForStreamOutput()               */
6403
/************************************************************************/
6404
6405
bool GDALAlgorithm::CheckSafeForStreamOutput()
6406
0
{
6407
0
    const auto outputFormatArg = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
6408
0
    if (outputFormatArg && outputFormatArg->GetType() == GAAT_STRING)
6409
0
    {
6410
0
        const auto &val = outputFormatArg->GDALAlgorithmArg::Get<std::string>();
6411
0
        if (!EQUAL(val.c_str(), "stream"))
6412
0
        {
6413
            // For security reasons, to avoid that reading a .gdalg.json file
6414
            // writes a file on the file system.
6415
0
            ReportError(
6416
0
                CE_Failure, CPLE_NotSupported,
6417
0
                "in streamed execution, --format stream should be used");
6418
0
            return false;
6419
0
        }
6420
0
    }
6421
0
    return true;
6422
0
}
6423
6424
/************************************************************************/
6425
/*                      GDALAlgorithm::Finalize()                       */
6426
/************************************************************************/
6427
6428
bool GDALAlgorithm::Finalize()
6429
0
{
6430
0
    bool ret = true;
6431
0
    if (m_selectedSubAlg)
6432
0
        ret = m_selectedSubAlg->Finalize();
6433
6434
0
    for (auto &arg : m_args)
6435
0
    {
6436
0
        if (arg->GetType() == GAAT_DATASET)
6437
0
        {
6438
0
            ret = arg->Get<GDALArgDatasetValue>().Close() && ret;
6439
0
        }
6440
0
        else if (arg->GetType() == GAAT_DATASET_LIST)
6441
0
        {
6442
0
            for (auto &ds : arg->Get<std::vector<GDALArgDatasetValue>>())
6443
0
            {
6444
0
                ret = ds.Close() && ret;
6445
0
            }
6446
0
        }
6447
0
    }
6448
0
    return ret;
6449
0
}
6450
6451
/************************************************************************/
6452
/*                  GDALAlgorithm::GetArgNamesForCLI()                  */
6453
/************************************************************************/
6454
6455
std::pair<std::vector<std::pair<GDALAlgorithmArg *, std::string>>, size_t>
6456
GDALAlgorithm::GetArgNamesForCLI() const
6457
0
{
6458
0
    std::vector<std::pair<GDALAlgorithmArg *, std::string>> options;
6459
6460
0
    size_t maxOptLen = 0;
6461
0
    for (const auto &arg : m_args)
6462
0
    {
6463
0
        if (arg->IsHidden() || arg->IsHiddenForCLI())
6464
0
            continue;
6465
0
        std::string opt;
6466
0
        bool addComma = false;
6467
0
        if (!arg->GetShortName().empty())
6468
0
        {
6469
0
            opt += '-';
6470
0
            opt += arg->GetShortName();
6471
0
            addComma = true;
6472
0
        }
6473
0
        for (char alias : arg->GetShortNameAliases())
6474
0
        {
6475
0
            if (addComma)
6476
0
                opt += ", ";
6477
0
            opt += "-";
6478
0
            opt += alias;
6479
0
            addComma = true;
6480
0
        }
6481
0
        for (const std::string &alias : arg->GetAliases())
6482
0
        {
6483
0
            if (addComma)
6484
0
                opt += ", ";
6485
0
            opt += "--";
6486
0
            opt += alias;
6487
0
            addComma = true;
6488
0
        }
6489
0
        if (!arg->GetName().empty())
6490
0
        {
6491
0
            if (addComma)
6492
0
                opt += ", ";
6493
0
            opt += "--";
6494
0
            opt += arg->GetName();
6495
0
        }
6496
0
        const auto &metaVar = arg->GetMetaVar();
6497
0
        if (!metaVar.empty())
6498
0
        {
6499
0
            opt += ' ';
6500
0
            if (metaVar.front() != '<')
6501
0
                opt += '<';
6502
0
            opt += metaVar;
6503
0
            if (metaVar.back() != '>')
6504
0
                opt += '>';
6505
0
        }
6506
0
        maxOptLen = std::max(maxOptLen, opt.size());
6507
0
        options.emplace_back(arg.get(), opt);
6508
0
    }
6509
6510
0
    return std::make_pair(std::move(options), maxOptLen);
6511
0
}
6512
6513
/************************************************************************/
6514
/*                   GDALAlgorithm::GetUsageForCLI()                    */
6515
/************************************************************************/
6516
6517
std::string
6518
GDALAlgorithm::GetUsageForCLI(bool shortUsage,
6519
                              const UsageOptions &usageOptions) const
6520
0
{
6521
0
    if (m_selectedSubAlg)
6522
0
        return m_selectedSubAlg->GetUsageForCLI(shortUsage, usageOptions);
6523
6524
0
    std::string osRet(usageOptions.isPipelineStep ? "*" : "Usage:");
6525
0
    std::string osPath;
6526
0
    for (const std::string &s : m_callPath)
6527
0
    {
6528
0
        if (!osPath.empty())
6529
0
            osPath += ' ';
6530
0
        osPath += s;
6531
0
    }
6532
0
    osRet += ' ';
6533
0
    osRet += osPath;
6534
6535
0
    bool hasNonPositionals = false;
6536
0
    for (const auto &arg : m_args)
6537
0
    {
6538
0
        if (!arg->IsHidden() && !arg->IsHiddenForCLI() && !arg->IsPositional())
6539
0
            hasNonPositionals = true;
6540
0
    }
6541
6542
0
    if (HasSubAlgorithms())
6543
0
    {
6544
0
        if (m_callPath.size() == 1)
6545
0
        {
6546
0
            osRet += " <COMMAND>";
6547
0
            if (hasNonPositionals)
6548
0
                osRet += " [OPTIONS]";
6549
0
            if (usageOptions.isPipelineStep)
6550
0
            {
6551
0
                const size_t nLenFirstLine = osRet.size();
6552
0
                osRet += '\n';
6553
0
                osRet.append(nLenFirstLine, '-');
6554
0
                osRet += '\n';
6555
0
            }
6556
0
            osRet += "\nwhere <COMMAND> is one of:\n";
6557
0
        }
6558
0
        else
6559
0
        {
6560
0
            osRet += " <SUBCOMMAND>";
6561
0
            if (hasNonPositionals)
6562
0
                osRet += " [OPTIONS]";
6563
0
            if (usageOptions.isPipelineStep)
6564
0
            {
6565
0
                const size_t nLenFirstLine = osRet.size();
6566
0
                osRet += '\n';
6567
0
                osRet.append(nLenFirstLine, '-');
6568
0
                osRet += '\n';
6569
0
            }
6570
0
            osRet += "\nwhere <SUBCOMMAND> is one of:\n";
6571
0
        }
6572
0
        size_t maxNameLen = 0;
6573
0
        for (const auto &subAlgName : GetSubAlgorithmNames())
6574
0
        {
6575
0
            maxNameLen = std::max(maxNameLen, subAlgName.size());
6576
0
        }
6577
0
        for (const auto &subAlgName : GetSubAlgorithmNames())
6578
0
        {
6579
0
            auto subAlg = InstantiateSubAlgorithm(subAlgName);
6580
0
            if (subAlg && !subAlg->IsHidden())
6581
0
            {
6582
0
                const std::string &name(subAlg->GetName());
6583
0
                osRet += "  - ";
6584
0
                osRet += name;
6585
0
                osRet += ": ";
6586
0
                osRet.append(maxNameLen - name.size(), ' ');
6587
0
                osRet += subAlg->GetDescription();
6588
0
                if (!subAlg->m_aliases.empty())
6589
0
                {
6590
0
                    bool first = true;
6591
0
                    for (const auto &alias : subAlg->GetAliases())
6592
0
                    {
6593
0
                        if (alias ==
6594
0
                            GDALAlgorithmRegistry::HIDDEN_ALIAS_SEPARATOR)
6595
0
                            break;
6596
0
                        if (first)
6597
0
                            osRet += " (alias: ";
6598
0
                        else
6599
0
                            osRet += ", ";
6600
0
                        osRet += alias;
6601
0
                        first = false;
6602
0
                    }
6603
0
                    if (!first)
6604
0
                    {
6605
0
                        osRet += ')';
6606
0
                    }
6607
0
                }
6608
0
                osRet += '\n';
6609
0
            }
6610
0
        }
6611
6612
0
        if (shortUsage && hasNonPositionals)
6613
0
        {
6614
0
            osRet += "\nTry '";
6615
0
            osRet += osPath;
6616
0
            osRet += " --help' for help.\n";
6617
0
        }
6618
0
    }
6619
0
    else
6620
0
    {
6621
0
        if (!m_args.empty())
6622
0
        {
6623
0
            if (hasNonPositionals)
6624
0
                osRet += " [OPTIONS]";
6625
0
            for (const auto *arg : m_positionalArgs)
6626
0
            {
6627
0
                if ((!arg->IsHidden() && !arg->IsHiddenForCLI()) ||
6628
0
                    (GetName() == "pipeline" && arg->GetName() == "pipeline"))
6629
0
                {
6630
0
                    const bool optional =
6631
0
                        (!arg->IsRequired() && !(GetName() == "pipeline" &&
6632
0
                                                 arg->GetName() == "pipeline"));
6633
0
                    osRet += ' ';
6634
0
                    if (optional)
6635
0
                        osRet += '[';
6636
0
                    const std::string &metavar = arg->GetMetaVar();
6637
0
                    if (!metavar.empty() && metavar[0] == '<')
6638
0
                    {
6639
0
                        osRet += metavar;
6640
0
                    }
6641
0
                    else
6642
0
                    {
6643
0
                        osRet += '<';
6644
0
                        osRet += metavar;
6645
0
                        osRet += '>';
6646
0
                    }
6647
0
                    if (arg->GetType() == GAAT_DATASET_LIST &&
6648
0
                        arg->GetMaxCount() > 1)
6649
0
                    {
6650
0
                        osRet += "...";
6651
0
                    }
6652
0
                    if (optional)
6653
0
                        osRet += ']';
6654
0
                }
6655
0
            }
6656
0
        }
6657
6658
0
        const size_t nLenFirstLine = osRet.size();
6659
0
        osRet += '\n';
6660
0
        if (usageOptions.isPipelineStep)
6661
0
        {
6662
0
            osRet.append(nLenFirstLine, '-');
6663
0
            osRet += '\n';
6664
0
        }
6665
6666
0
        if (shortUsage)
6667
0
        {
6668
0
            osRet += "Try '";
6669
0
            osRet += osPath;
6670
0
            osRet += " --help' for help.\n";
6671
0
            return osRet;
6672
0
        }
6673
6674
0
        osRet += '\n';
6675
0
        osRet += m_description;
6676
0
        osRet += '\n';
6677
0
    }
6678
6679
0
    if (!m_args.empty() && !shortUsage)
6680
0
    {
6681
0
        std::vector<std::pair<GDALAlgorithmArg *, std::string>> options;
6682
0
        size_t maxOptLen;
6683
0
        std::tie(options, maxOptLen) = GetArgNamesForCLI();
6684
0
        if (usageOptions.maxOptLen)
6685
0
            maxOptLen = usageOptions.maxOptLen;
6686
6687
0
        const std::string userProvidedOpt = "--<user-provided-option>=<value>";
6688
0
        if (m_arbitraryLongNameArgsAllowed)
6689
0
            maxOptLen = std::max(maxOptLen, userProvidedOpt.size());
6690
6691
0
        const auto OutputArg =
6692
0
            [this, maxOptLen, &osRet,
6693
0
             &usageOptions](const GDALAlgorithmArg *arg, const std::string &opt)
6694
0
        {
6695
0
            osRet += "  ";
6696
0
            osRet += opt;
6697
0
            osRet += "  ";
6698
0
            osRet.append(maxOptLen - opt.size(), ' ');
6699
0
            osRet += arg->GetDescription();
6700
6701
0
            const auto &choices = arg->GetChoices();
6702
0
            if (!choices.empty())
6703
0
            {
6704
0
                osRet += ". ";
6705
0
                osRet += arg->GetMetaVar();
6706
0
                osRet += '=';
6707
0
                bool firstChoice = true;
6708
0
                for (const auto &choice : choices)
6709
0
                {
6710
0
                    if (!firstChoice)
6711
0
                        osRet += '|';
6712
0
                    osRet += choice;
6713
0
                    firstChoice = false;
6714
0
                }
6715
0
            }
6716
6717
0
            if (arg->GetType() == GAAT_DATASET ||
6718
0
                arg->GetType() == GAAT_DATASET_LIST)
6719
0
            {
6720
0
                if (arg->IsOutput() &&
6721
0
                    arg->GetDatasetInputFlags() == GADV_NAME &&
6722
0
                    arg->GetDatasetOutputFlags() == GADV_OBJECT)
6723
0
                {
6724
0
                    osRet += " (created by algorithm)";
6725
0
                }
6726
0
            }
6727
6728
0
            if (arg->GetType() == GAAT_STRING && arg->HasDefaultValue())
6729
0
            {
6730
0
                osRet += " (default: ";
6731
0
                osRet += arg->GetDefault<std::string>();
6732
0
                osRet += ')';
6733
0
            }
6734
0
            else if (arg->GetType() == GAAT_BOOLEAN && arg->HasDefaultValue())
6735
0
            {
6736
0
                if (arg->GetDefault<bool>())
6737
0
                    osRet += " (default: true)";
6738
0
            }
6739
0
            else if (arg->GetType() == GAAT_INTEGER && arg->HasDefaultValue())
6740
0
            {
6741
0
                osRet += " (default: ";
6742
0
                osRet += CPLSPrintf("%d", arg->GetDefault<int>());
6743
0
                osRet += ')';
6744
0
            }
6745
0
            else if (arg->GetType() == GAAT_REAL && arg->HasDefaultValue())
6746
0
            {
6747
0
                osRet += " (default: ";
6748
0
                osRet += CPLSPrintf("%g", arg->GetDefault<double>());
6749
0
                osRet += ')';
6750
0
            }
6751
0
            else if (arg->GetType() == GAAT_STRING_LIST &&
6752
0
                     arg->HasDefaultValue())
6753
0
            {
6754
0
                const auto &defaultVal =
6755
0
                    arg->GetDefault<std::vector<std::string>>();
6756
0
                if (defaultVal.size() == 1)
6757
0
                {
6758
0
                    osRet += " (default: ";
6759
0
                    osRet += defaultVal[0];
6760
0
                    osRet += ')';
6761
0
                }
6762
0
            }
6763
0
            else if (arg->GetType() == GAAT_INTEGER_LIST &&
6764
0
                     arg->HasDefaultValue())
6765
0
            {
6766
0
                const auto &defaultVal = arg->GetDefault<std::vector<int>>();
6767
0
                if (defaultVal.size() == 1)
6768
0
                {
6769
0
                    osRet += " (default: ";
6770
0
                    osRet += CPLSPrintf("%d", defaultVal[0]);
6771
0
                    osRet += ')';
6772
0
                }
6773
0
            }
6774
0
            else if (arg->GetType() == GAAT_REAL_LIST && arg->HasDefaultValue())
6775
0
            {
6776
0
                const auto &defaultVal = arg->GetDefault<std::vector<double>>();
6777
0
                if (defaultVal.size() == 1)
6778
0
                {
6779
0
                    osRet += " (default: ";
6780
0
                    osRet += CPLSPrintf("%g", defaultVal[0]);
6781
0
                    osRet += ')';
6782
0
                }
6783
0
            }
6784
6785
0
            if (arg->GetDisplayHintAboutRepetition())
6786
0
            {
6787
0
                if (arg->GetMinCount() > 0 &&
6788
0
                    arg->GetMinCount() == arg->GetMaxCount())
6789
0
                {
6790
0
                    if (arg->GetMinCount() != 1)
6791
0
                        osRet += CPLSPrintf(" [%d values]", arg->GetMaxCount());
6792
0
                }
6793
0
                else if (arg->GetMinCount() > 0 &&
6794
0
                         arg->GetMaxCount() < GDALAlgorithmArgDecl::UNBOUNDED)
6795
0
                {
6796
0
                    osRet += CPLSPrintf(" [%d..%d values]", arg->GetMinCount(),
6797
0
                                        arg->GetMaxCount());
6798
0
                }
6799
0
                else if (arg->GetMinCount() > 0)
6800
0
                {
6801
0
                    osRet += CPLSPrintf(" [%d.. values]", arg->GetMinCount());
6802
0
                }
6803
0
                else if (arg->GetMaxCount() > 1)
6804
0
                {
6805
0
                    osRet += " [may be repeated]";
6806
0
                }
6807
0
            }
6808
6809
0
            if (arg->IsRequired())
6810
0
            {
6811
0
                osRet += " [required]";
6812
0
            }
6813
6814
0
            if (!arg->IsAvailableInPipelineStep() &&
6815
0
                !usageOptions.isPipelineStep)
6816
0
            {
6817
0
                osRet += " [not available in pipelines]";
6818
0
            }
6819
6820
0
            osRet += '\n';
6821
6822
0
            const auto &mutualExclusionGroup = arg->GetMutualExclusionGroup();
6823
0
            if (!mutualExclusionGroup.empty())
6824
0
            {
6825
0
                std::string otherArgs;
6826
0
                for (const auto &otherArg : m_args)
6827
0
                {
6828
0
                    if (otherArg->IsHidden() || otherArg->IsHiddenForCLI() ||
6829
0
                        otherArg.get() == arg)
6830
0
                        continue;
6831
0
                    if (otherArg->GetMutualExclusionGroup() ==
6832
0
                        mutualExclusionGroup)
6833
0
                    {
6834
0
                        if (!otherArgs.empty())
6835
0
                            otherArgs += ", ";
6836
0
                        otherArgs += "--";
6837
0
                        otherArgs += otherArg->GetName();
6838
0
                    }
6839
0
                }
6840
0
                if (!otherArgs.empty())
6841
0
                {
6842
0
                    osRet += "  ";
6843
0
                    osRet += "  ";
6844
0
                    osRet.append(maxOptLen, ' ');
6845
0
                    osRet += "Mutually exclusive with ";
6846
0
                    osRet += otherArgs;
6847
0
                    osRet += '\n';
6848
0
                }
6849
0
            }
6850
6851
            // Check dependency
6852
0
            std::string dependencyArgs;
6853
6854
0
            for (const auto &dependencyArgumentName :
6855
0
                 GetArgDependencies(arg->GetName()))
6856
0
            {
6857
0
                const auto otherArg{GetArg(dependencyArgumentName)};
6858
0
                if (otherArg != nullptr)
6859
0
                {
6860
0
                    if (otherArg->IsHidden() || otherArg->IsHiddenForCLI() ||
6861
0
                        otherArg == arg)
6862
0
                    {
6863
0
                        continue;
6864
0
                    }
6865
6866
0
                    if (!dependencyArgs.empty())
6867
0
                    {
6868
0
                        dependencyArgs += ", ";
6869
0
                    }
6870
6871
0
                    dependencyArgs += "--";
6872
0
                    dependencyArgs += otherArg->GetName();
6873
0
                }
6874
0
                else
6875
0
                {
6876
0
                    CPLError(CE_Warning, CPLE_AppDefined,
6877
0
                             "Argument '%s' depends on unknown argument '%s'",
6878
0
                             arg->GetName().c_str(),
6879
0
                             dependencyArgumentName.c_str());
6880
0
                }
6881
0
            }
6882
6883
0
            if (!dependencyArgs.empty())
6884
0
            {
6885
0
                osRet += "  ";
6886
0
                osRet += "  ";
6887
0
                osRet.append(maxOptLen, ' ');
6888
0
                osRet += "Depends on ";
6889
0
                osRet += dependencyArgs;
6890
0
                osRet += '\n';
6891
0
            }
6892
0
        };
6893
6894
0
        if (!m_positionalArgs.empty())
6895
0
        {
6896
0
            osRet += "\nPositional arguments:\n";
6897
0
            for (const auto &[arg, opt] : options)
6898
0
            {
6899
0
                if (arg->IsPositional())
6900
0
                    OutputArg(arg, opt);
6901
0
            }
6902
0
        }
6903
6904
0
        if (hasNonPositionals)
6905
0
        {
6906
0
            bool hasCommon = false;
6907
0
            bool hasBase = false;
6908
0
            bool hasAdvanced = false;
6909
0
            bool hasEsoteric = false;
6910
0
            std::vector<std::string> categories;
6911
0
            for (const auto &iter : options)
6912
0
            {
6913
0
                const auto &arg = iter.first;
6914
0
                if (!arg->IsPositional())
6915
0
                {
6916
0
                    const auto &category = arg->GetCategory();
6917
0
                    if (category == GAAC_COMMON)
6918
0
                    {
6919
0
                        hasCommon = true;
6920
0
                    }
6921
0
                    else if (category == GAAC_BASE)
6922
0
                    {
6923
0
                        hasBase = true;
6924
0
                    }
6925
0
                    else if (category == GAAC_ADVANCED)
6926
0
                    {
6927
0
                        hasAdvanced = true;
6928
0
                    }
6929
0
                    else if (category == GAAC_ESOTERIC)
6930
0
                    {
6931
0
                        hasEsoteric = true;
6932
0
                    }
6933
0
                    else if (std::find(categories.begin(), categories.end(),
6934
0
                                       category) == categories.end())
6935
0
                    {
6936
0
                        categories.push_back(category);
6937
0
                    }
6938
0
                }
6939
0
            }
6940
0
            if (hasAdvanced || m_arbitraryLongNameArgsAllowed)
6941
0
                categories.insert(categories.begin(), GAAC_ADVANCED);
6942
0
            if (hasBase)
6943
0
                categories.insert(categories.begin(), GAAC_BASE);
6944
0
            if (hasCommon && !usageOptions.isPipelineStep)
6945
0
                categories.insert(categories.begin(), GAAC_COMMON);
6946
0
            if (hasEsoteric)
6947
0
                categories.push_back(GAAC_ESOTERIC);
6948
6949
0
            for (const auto &category : categories)
6950
0
            {
6951
0
                osRet += "\n";
6952
0
                if (category != GAAC_BASE)
6953
0
                {
6954
0
                    osRet += category;
6955
0
                    osRet += ' ';
6956
0
                }
6957
0
                osRet += "Options:\n";
6958
0
                for (const auto &[arg, opt] : options)
6959
0
                {
6960
0
                    if (!arg->IsPositional() && arg->GetCategory() == category)
6961
0
                        OutputArg(arg, opt);
6962
0
                }
6963
0
                if (m_arbitraryLongNameArgsAllowed && category == GAAC_ADVANCED)
6964
0
                {
6965
0
                    osRet += "  ";
6966
0
                    osRet += userProvidedOpt;
6967
0
                    osRet += "  ";
6968
0
                    if (userProvidedOpt.size() < maxOptLen)
6969
0
                        osRet.append(maxOptLen - userProvidedOpt.size(), ' ');
6970
0
                    osRet += "Argument provided by user";
6971
0
                    osRet += '\n';
6972
0
                }
6973
0
            }
6974
0
        }
6975
0
    }
6976
6977
0
    if (!m_longDescription.empty())
6978
0
    {
6979
0
        osRet += '\n';
6980
0
        osRet += m_longDescription;
6981
0
        osRet += '\n';
6982
0
    }
6983
6984
0
    if (!m_helpDocRequested && !usageOptions.isPipelineMain)
6985
0
    {
6986
0
        if (!m_helpURL.empty())
6987
0
        {
6988
0
            osRet += "\nFor more details, consult ";
6989
0
            osRet += GetHelpFullURL();
6990
0
            osRet += '\n';
6991
0
        }
6992
0
        osRet += GetUsageForCLIEnd();
6993
0
    }
6994
6995
0
    return osRet;
6996
0
}
6997
6998
/************************************************************************/
6999
/*                  GDALAlgorithm::GetUsageForCLIEnd()                  */
7000
/************************************************************************/
7001
7002
//! @cond Doxygen_Suppress
7003
std::string GDALAlgorithm::GetUsageForCLIEnd() const
7004
0
{
7005
0
    std::string osRet;
7006
7007
0
    if (!m_callPath.empty() && m_callPath[0] == "gdal")
7008
0
    {
7009
0
        osRet += "\nWARNING: the gdal command is provisionally provided as an "
7010
0
                 "alternative interface to GDAL and OGR command line "
7011
0
                 "utilities.\nThe project reserves the right to modify, "
7012
0
                 "rename, reorganize, and change the behavior of the utility\n"
7013
0
                 "until it is officially frozen in a future feature release of "
7014
0
                 "GDAL.\n";
7015
0
    }
7016
0
    return osRet;
7017
0
}
7018
7019
//! @endcond
7020
7021
/************************************************************************/
7022
/*                   GDALAlgorithm::GetUsageAsJSON()                    */
7023
/************************************************************************/
7024
7025
std::string GDALAlgorithm::GetUsageAsJSON() const
7026
0
{
7027
0
    CPLJSONDocument oDoc;
7028
0
    auto oRoot = oDoc.GetRoot();
7029
7030
0
    if (m_displayInJSONUsage)
7031
0
    {
7032
0
        oRoot.Add("name", m_name);
7033
0
        CPLJSONArray jFullPath;
7034
0
        for (const std::string &s : m_callPath)
7035
0
        {
7036
0
            jFullPath.Add(s);
7037
0
        }
7038
0
        oRoot.Add("full_path", jFullPath);
7039
0
    }
7040
7041
0
    oRoot.Add("description", m_description);
7042
0
    if (!m_helpURL.empty())
7043
0
    {
7044
0
        oRoot.Add("short_url", m_helpURL);
7045
0
        oRoot.Add("url", GetHelpFullURL());
7046
0
    }
7047
7048
0
    CPLJSONArray jSubAlgorithms;
7049
0
    for (const auto &subAlgName : GetSubAlgorithmNames())
7050
0
    {
7051
0
        auto subAlg = InstantiateSubAlgorithm(subAlgName);
7052
0
        if (subAlg && subAlg->m_displayInJSONUsage && !subAlg->IsHidden())
7053
0
        {
7054
0
            CPLJSONDocument oSubDoc;
7055
0
            CPL_IGNORE_RET_VAL(oSubDoc.LoadMemory(subAlg->GetUsageAsJSON()));
7056
0
            jSubAlgorithms.Add(oSubDoc.GetRoot());
7057
0
        }
7058
0
    }
7059
0
    oRoot.Add("sub_algorithms", jSubAlgorithms);
7060
7061
0
    if (m_arbitraryLongNameArgsAllowed)
7062
0
    {
7063
0
        oRoot.Add("user_provided_arguments_allowed", true);
7064
0
    }
7065
7066
0
    const auto ProcessArg = [this](const GDALAlgorithmArg *arg)
7067
0
    {
7068
0
        CPLJSONObject jArg;
7069
0
        jArg.Add("name", arg->GetName());
7070
0
        jArg.Add("type", GDALAlgorithmArgTypeName(arg->GetType()));
7071
0
        jArg.Add("description", arg->GetDescription());
7072
7073
0
        const auto &metaVar = arg->GetMetaVar();
7074
0
        if (!metaVar.empty() && metaVar != CPLString(arg->GetName()).toupper())
7075
0
        {
7076
0
            if (metaVar.front() == '<' && metaVar.back() == '>' &&
7077
0
                metaVar.substr(1, metaVar.size() - 2).find('>') ==
7078
0
                    std::string::npos)
7079
0
                jArg.Add("metavar", metaVar.substr(1, metaVar.size() - 2));
7080
0
            else
7081
0
                jArg.Add("metavar", metaVar);
7082
0
        }
7083
7084
0
        if (!arg->IsAvailableInPipelineStep())
7085
0
        {
7086
0
            jArg.Add("available_in_pipeline_step", false);
7087
0
        }
7088
7089
0
        const auto &choices = arg->GetChoices();
7090
0
        if (!choices.empty())
7091
0
        {
7092
0
            CPLJSONArray jChoices;
7093
0
            for (const auto &choice : choices)
7094
0
                jChoices.Add(choice);
7095
0
            jArg.Add("choices", jChoices);
7096
0
        }
7097
0
        if (arg->HasDefaultValue())
7098
0
        {
7099
0
            switch (arg->GetType())
7100
0
            {
7101
0
                case GAAT_BOOLEAN:
7102
0
                    jArg.Add("default", arg->GetDefault<bool>());
7103
0
                    break;
7104
0
                case GAAT_STRING:
7105
0
                    jArg.Add("default", arg->GetDefault<std::string>());
7106
0
                    break;
7107
0
                case GAAT_INTEGER:
7108
0
                    jArg.Add("default", arg->GetDefault<int>());
7109
0
                    break;
7110
0
                case GAAT_REAL:
7111
0
                    jArg.Add("default", arg->GetDefault<double>());
7112
0
                    break;
7113
0
                case GAAT_STRING_LIST:
7114
0
                {
7115
0
                    const auto &val =
7116
0
                        arg->GetDefault<std::vector<std::string>>();
7117
0
                    if (val.size() == 1)
7118
0
                    {
7119
0
                        jArg.Add("default", val[0]);
7120
0
                    }
7121
0
                    else
7122
0
                    {
7123
0
                        CPLJSONArray jArr;
7124
0
                        for (const auto &s : val)
7125
0
                        {
7126
0
                            jArr.Add(s);
7127
0
                        }
7128
0
                        jArg.Add("default", jArr);
7129
0
                    }
7130
0
                    break;
7131
0
                }
7132
0
                case GAAT_INTEGER_LIST:
7133
0
                {
7134
0
                    const auto &val = arg->GetDefault<std::vector<int>>();
7135
0
                    if (val.size() == 1)
7136
0
                    {
7137
0
                        jArg.Add("default", val[0]);
7138
0
                    }
7139
0
                    else
7140
0
                    {
7141
0
                        CPLJSONArray jArr;
7142
0
                        for (int i : val)
7143
0
                        {
7144
0
                            jArr.Add(i);
7145
0
                        }
7146
0
                        jArg.Add("default", jArr);
7147
0
                    }
7148
0
                    break;
7149
0
                }
7150
0
                case GAAT_REAL_LIST:
7151
0
                {
7152
0
                    const auto &val = arg->GetDefault<std::vector<double>>();
7153
0
                    if (val.size() == 1)
7154
0
                    {
7155
0
                        jArg.Add("default", val[0]);
7156
0
                    }
7157
0
                    else
7158
0
                    {
7159
0
                        CPLJSONArray jArr;
7160
0
                        for (double d : val)
7161
0
                        {
7162
0
                            jArr.Add(d);
7163
0
                        }
7164
0
                        jArg.Add("default", jArr);
7165
0
                    }
7166
0
                    break;
7167
0
                }
7168
0
                case GAAT_DATASET:
7169
0
                case GAAT_DATASET_LIST:
7170
0
                    CPLError(CE_Warning, CPLE_AppDefined,
7171
0
                             "Unhandled default value for arg %s",
7172
0
                             arg->GetName().c_str());
7173
0
                    break;
7174
0
            }
7175
0
        }
7176
7177
0
        const auto [minVal, minValIsIncluded] = arg->GetMinValue();
7178
0
        if (!std::isnan(minVal))
7179
0
        {
7180
0
            if (arg->GetType() == GAAT_INTEGER ||
7181
0
                arg->GetType() == GAAT_INTEGER_LIST)
7182
0
                jArg.Add("min_value", static_cast<int>(minVal));
7183
0
            else
7184
0
                jArg.Add("min_value", minVal);
7185
0
            jArg.Add("min_value_is_included", minValIsIncluded);
7186
0
        }
7187
7188
0
        const auto [maxVal, maxValIsIncluded] = arg->GetMaxValue();
7189
0
        if (!std::isnan(maxVal))
7190
0
        {
7191
0
            if (arg->GetType() == GAAT_INTEGER ||
7192
0
                arg->GetType() == GAAT_INTEGER_LIST)
7193
0
                jArg.Add("max_value", static_cast<int>(maxVal));
7194
0
            else
7195
0
                jArg.Add("max_value", maxVal);
7196
0
            jArg.Add("max_value_is_included", maxValIsIncluded);
7197
0
        }
7198
7199
0
        jArg.Add("required", arg->IsRequired());
7200
0
        if (GDALAlgorithmArgTypeIsList(arg->GetType()))
7201
0
        {
7202
0
            jArg.Add("packed_values_allowed", arg->GetPackedValuesAllowed());
7203
0
            jArg.Add("repeated_arg_allowed", arg->GetRepeatedArgAllowed());
7204
0
            jArg.Add("min_count", arg->GetMinCount());
7205
0
            jArg.Add("max_count", arg->GetMaxCount());
7206
0
        }
7207
7208
        // Process dependencies
7209
0
        const auto &mutualDependencyGroup = arg->GetMutualDependencyGroup();
7210
0
        if (!mutualDependencyGroup.empty())
7211
0
        {
7212
0
            jArg.Add("mutual_dependency_group", mutualDependencyGroup);
7213
0
        }
7214
7215
0
        CPLJSONArray jDependencies;
7216
0
        for (const auto &dependencyArgumentName :
7217
0
             GetArgDependencies(arg->GetName()))
7218
0
        {
7219
0
            jDependencies.Add(dependencyArgumentName);
7220
0
        }
7221
7222
0
        if (jDependencies.Size() > 0)
7223
0
        {
7224
0
            jArg.Add("depends_on", jDependencies);
7225
0
        }
7226
7227
0
        jArg.Add("category", arg->GetCategory());
7228
7229
0
        if (arg->GetType() == GAAT_DATASET ||
7230
0
            arg->GetType() == GAAT_DATASET_LIST)
7231
0
        {
7232
0
            {
7233
0
                CPLJSONArray jAr;
7234
0
                if (arg->GetDatasetType() & GDAL_OF_RASTER)
7235
0
                    jAr.Add("raster");
7236
0
                if (arg->GetDatasetType() & GDAL_OF_VECTOR)
7237
0
                    jAr.Add("vector");
7238
0
                if (arg->GetDatasetType() & GDAL_OF_MULTIDIM_RASTER)
7239
0
                    jAr.Add("multidim_raster");
7240
0
                jArg.Add("dataset_type", jAr);
7241
0
            }
7242
7243
0
            const auto GetFlags = [](int flags)
7244
0
            {
7245
0
                CPLJSONArray jAr;
7246
0
                if (flags & GADV_NAME)
7247
0
                    jAr.Add("name");
7248
0
                if (flags & GADV_OBJECT)
7249
0
                    jAr.Add("dataset");
7250
0
                return jAr;
7251
0
            };
7252
7253
0
            if (arg->IsInput())
7254
0
            {
7255
0
                jArg.Add("input_flags", GetFlags(arg->GetDatasetInputFlags()));
7256
0
            }
7257
0
            if (arg->IsOutput())
7258
0
            {
7259
0
                jArg.Add("output_flags",
7260
0
                         GetFlags(arg->GetDatasetOutputFlags()));
7261
0
            }
7262
0
        }
7263
7264
0
        const auto &mutualExclusionGroup = arg->GetMutualExclusionGroup();
7265
0
        if (!mutualExclusionGroup.empty())
7266
0
        {
7267
0
            jArg.Add("mutual_exclusion_group", mutualExclusionGroup);
7268
0
        }
7269
7270
0
        const auto &metadata = arg->GetMetadata();
7271
0
        if (!metadata.empty())
7272
0
        {
7273
0
            CPLJSONObject jMetadata;
7274
0
            for (const auto &[key, values] : metadata)
7275
0
            {
7276
0
                CPLJSONArray jValue;
7277
0
                for (const auto &value : values)
7278
0
                    jValue.Add(value);
7279
0
                jMetadata.Add(key, jValue);
7280
0
            }
7281
0
            jArg.Add("metadata", jMetadata);
7282
0
        }
7283
7284
0
        return jArg;
7285
0
    };
7286
7287
0
    {
7288
0
        CPLJSONArray jArgs;
7289
0
        for (const auto &arg : m_args)
7290
0
        {
7291
0
            if (!arg->IsHiddenForAPI() && arg->IsInput() && !arg->IsOutput())
7292
0
                jArgs.Add(ProcessArg(arg.get()));
7293
0
        }
7294
0
        oRoot.Add("input_arguments", jArgs);
7295
0
    }
7296
7297
0
    {
7298
0
        CPLJSONArray jArgs;
7299
0
        for (const auto &arg : m_args)
7300
0
        {
7301
0
            if (!arg->IsHiddenForAPI() && !arg->IsInput() && arg->IsOutput())
7302
0
                jArgs.Add(ProcessArg(arg.get()));
7303
0
        }
7304
0
        oRoot.Add("output_arguments", jArgs);
7305
0
    }
7306
7307
0
    {
7308
0
        CPLJSONArray jArgs;
7309
0
        for (const auto &arg : m_args)
7310
0
        {
7311
0
            if (!arg->IsHiddenForAPI() && arg->IsInput() && arg->IsOutput())
7312
0
                jArgs.Add(ProcessArg(arg.get()));
7313
0
        }
7314
0
        oRoot.Add("input_output_arguments", jArgs);
7315
0
    }
7316
7317
0
    if (m_supportsStreamedOutput)
7318
0
    {
7319
0
        oRoot.Add("supports_streamed_output", true);
7320
0
    }
7321
7322
0
    return oDoc.SaveAsString();
7323
0
}
7324
7325
/************************************************************************/
7326
/*                   GDALAlgorithm::GetAutoComplete()                   */
7327
/************************************************************************/
7328
7329
std::vector<std::string>
7330
GDALAlgorithm::GetAutoComplete(std::vector<std::string> &args,
7331
                               bool lastWordIsComplete, bool showAllOptions)
7332
0
{
7333
0
    std::vector<std::string> ret;
7334
7335
    // Get inner-most algorithm
7336
0
    std::unique_ptr<GDALAlgorithm> curAlgHolder;
7337
0
    GDALAlgorithm *curAlg = this;
7338
0
    while (!args.empty() && !args.front().empty() && args.front()[0] != '-')
7339
0
    {
7340
0
        auto subAlg = curAlg->InstantiateSubAlgorithm(
7341
0
            args.front(), /* suggestionAllowed = */ false);
7342
0
        if (!subAlg)
7343
0
            break;
7344
0
        if (args.size() == 1 && !lastWordIsComplete)
7345
0
        {
7346
0
            int nCount = 0;
7347
0
            for (const auto &subAlgName : curAlg->GetSubAlgorithmNames())
7348
0
            {
7349
0
                if (STARTS_WITH(subAlgName.c_str(), args.front().c_str()))
7350
0
                    nCount++;
7351
0
            }
7352
0
            if (nCount >= 2)
7353
0
            {
7354
0
                for (const std::string &subAlgName :
7355
0
                     curAlg->GetSubAlgorithmNames())
7356
0
                {
7357
0
                    subAlg = curAlg->InstantiateSubAlgorithm(subAlgName);
7358
0
                    if (subAlg && !subAlg->IsHidden())
7359
0
                        ret.push_back(subAlg->GetName());
7360
0
                }
7361
0
                return ret;
7362
0
            }
7363
0
        }
7364
0
        showAllOptions = false;
7365
0
        args.erase(args.begin());
7366
0
        curAlgHolder = std::move(subAlg);
7367
0
        curAlg = curAlgHolder.get();
7368
0
    }
7369
0
    if (curAlg != this)
7370
0
    {
7371
0
        curAlg->m_calledFromCommandLine = m_calledFromCommandLine;
7372
0
        return curAlg->GetAutoComplete(args, lastWordIsComplete,
7373
0
                                       /* showAllOptions = */ false);
7374
0
    }
7375
7376
0
    std::string option;
7377
0
    std::string value;
7378
0
    ExtractLastOptionAndValue(args, option, value);
7379
7380
0
    if (option.empty() && !args.empty() && !args.back().empty() &&
7381
0
        args.back()[0] == '-')
7382
0
    {
7383
0
        const auto &lastArg = args.back();
7384
        // List available options
7385
0
        for (const auto &arg : GetArgs())
7386
0
        {
7387
0
            if (arg->IsHidden() || arg->IsHiddenForCLI() ||
7388
0
                (!showAllOptions &&
7389
0
                 (arg->GetName() == "help" || arg->GetName() == "config" ||
7390
0
                  arg->GetName() == "version" ||
7391
0
                  arg->GetName() == "json-usage")))
7392
0
            {
7393
0
                continue;
7394
0
            }
7395
0
            if (!arg->GetShortName().empty())
7396
0
            {
7397
0
                std::string str = std::string("-").append(arg->GetShortName());
7398
0
                if (lastArg == str)
7399
0
                    ret.push_back(std::move(str));
7400
0
            }
7401
0
            if (lastArg != "-" && lastArg != "--")
7402
0
            {
7403
0
                for (const std::string &alias : arg->GetAliases())
7404
0
                {
7405
0
                    std::string str = std::string("--").append(alias);
7406
0
                    if (cpl::starts_with(str, lastArg))
7407
0
                        ret.push_back(std::move(str));
7408
0
                }
7409
0
            }
7410
0
            if (!arg->GetName().empty())
7411
0
            {
7412
0
                std::string str = std::string("--").append(arg->GetName());
7413
0
                if (cpl::starts_with(str, lastArg))
7414
0
                    ret.push_back(std::move(str));
7415
0
            }
7416
0
        }
7417
0
        std::sort(ret.begin(), ret.end());
7418
0
    }
7419
0
    else if (!option.empty())
7420
0
    {
7421
        // List possible choices for current option
7422
0
        auto arg = GetArg(option);
7423
0
        if (arg && arg->GetType() != GAAT_BOOLEAN)
7424
0
        {
7425
0
            ret = arg->GetChoices();
7426
0
            if (ret.empty())
7427
0
            {
7428
0
                {
7429
0
                    CPLErrorStateBackuper oErrorQuieter(CPLQuietErrorHandler);
7430
0
                    SetParseForAutoCompletion();
7431
0
                    CPL_IGNORE_RET_VAL(ParseCommandLineArguments(args));
7432
0
                }
7433
0
                ret = arg->GetAutoCompleteChoices(value);
7434
0
            }
7435
0
            else
7436
0
            {
7437
0
                std::sort(ret.begin(), ret.end());
7438
0
            }
7439
0
            if (!ret.empty() && ret.back() == value)
7440
0
            {
7441
0
                ret.clear();
7442
0
            }
7443
0
            else if (ret.empty())
7444
0
            {
7445
0
                ret.push_back("**");
7446
                // Non printable UTF-8 space, to avoid autocompletion to pickup on 'd'
7447
0
                ret.push_back(std::string("\xC2\xA0"
7448
0
                                          "description: ")
7449
0
                                  .append(arg->GetDescription()));
7450
0
            }
7451
0
        }
7452
0
    }
7453
0
    else
7454
0
    {
7455
        // List possible sub-algorithms
7456
0
        for (const std::string &subAlgName : GetSubAlgorithmNames())
7457
0
        {
7458
0
            auto subAlg = InstantiateSubAlgorithm(subAlgName);
7459
0
            if (subAlg && !subAlg->IsHidden())
7460
0
                ret.push_back(subAlg->GetName());
7461
0
        }
7462
0
        if (!ret.empty())
7463
0
        {
7464
0
            std::sort(ret.begin(), ret.end());
7465
0
        }
7466
7467
        // Try filenames
7468
0
        if (ret.empty() && !args.empty())
7469
0
        {
7470
0
            {
7471
0
                CPLErrorStateBackuper oErrorQuieter(CPLQuietErrorHandler);
7472
0
                SetParseForAutoCompletion();
7473
0
                CPL_IGNORE_RET_VAL(ParseCommandLineArguments(args));
7474
0
            }
7475
7476
0
            const std::string &lastArg = args.back();
7477
0
            GDALAlgorithmArg *arg = nullptr;
7478
0
            for (const char *name : {GDAL_ARG_NAME_INPUT, "dataset", "filename",
7479
0
                                     "like", "source", "destination"})
7480
0
            {
7481
0
                if (!arg)
7482
0
                {
7483
0
                    auto newArg = GetArg(name);
7484
0
                    if (newArg)
7485
0
                    {
7486
0
                        if (!newArg->IsExplicitlySet())
7487
0
                        {
7488
0
                            arg = newArg;
7489
0
                        }
7490
0
                        else if (newArg->GetType() == GAAT_STRING ||
7491
0
                                 newArg->GetType() == GAAT_STRING_LIST ||
7492
0
                                 newArg->GetType() == GAAT_DATASET ||
7493
0
                                 newArg->GetType() == GAAT_DATASET_LIST)
7494
0
                        {
7495
0
                            VSIStatBufL sStat;
7496
0
                            if ((!lastArg.empty() && lastArg.back() == '/') ||
7497
0
                                VSIStatL(lastArg.c_str(), &sStat) != 0)
7498
0
                            {
7499
0
                                arg = newArg;
7500
0
                            }
7501
0
                        }
7502
0
                    }
7503
0
                }
7504
0
            }
7505
0
            if (arg)
7506
0
            {
7507
0
                ret = arg->GetAutoCompleteChoices(lastArg);
7508
0
            }
7509
0
        }
7510
0
    }
7511
7512
0
    return ret;
7513
0
}
7514
7515
/************************************************************************/
7516
/*                   GDALAlgorithm::GetFieldIndices()                   */
7517
/************************************************************************/
7518
7519
bool GDALAlgorithm::GetFieldIndices(const std::vector<std::string> &names,
7520
                                    OGRLayerH hLayer, std::vector<int> &indices)
7521
0
{
7522
0
    VALIDATE_POINTER1(hLayer, __func__, false);
7523
7524
0
    const OGRLayer &layer = *OGRLayer::FromHandle(hLayer);
7525
7526
0
    if (names.size() == 1 && names[0] == "ALL")
7527
0
    {
7528
0
        const int nSrcFieldCount = layer.GetLayerDefn()->GetFieldCount();
7529
0
        for (int i = 0; i < nSrcFieldCount; ++i)
7530
0
        {
7531
0
            indices.push_back(i);
7532
0
        }
7533
0
    }
7534
0
    else if (!names.empty() && !(names.size() == 1 && names[0] == "NONE"))
7535
0
    {
7536
0
        std::set<int> fieldsAdded;
7537
0
        for (const std::string &osFieldName : names)
7538
0
        {
7539
7540
0
            const int nIdx =
7541
0
                layer.GetLayerDefn()->GetFieldIndex(osFieldName.c_str());
7542
7543
0
            if (nIdx < 0)
7544
0
            {
7545
0
                CPLError(CE_Failure, CPLE_AppDefined,
7546
0
                         "Field '%s' does not exist in layer '%s'",
7547
0
                         osFieldName.c_str(), layer.GetName());
7548
0
                return false;
7549
0
            }
7550
7551
0
            if (fieldsAdded.insert(nIdx).second)
7552
0
            {
7553
0
                indices.push_back(nIdx);
7554
0
            }
7555
0
        }
7556
0
    }
7557
7558
0
    return true;
7559
0
}
7560
7561
/************************************************************************/
7562
/*              GDALAlgorithm::ExtractLastOptionAndValue()              */
7563
/************************************************************************/
7564
7565
void GDALAlgorithm::ExtractLastOptionAndValue(std::vector<std::string> &args,
7566
                                              std::string &option,
7567
                                              std::string &value) const
7568
0
{
7569
0
    if (!args.empty() && !args.back().empty() && args.back()[0] == '-')
7570
0
    {
7571
0
        const auto nPosEqual = args.back().find('=');
7572
0
        if (nPosEqual == std::string::npos)
7573
0
        {
7574
            // Deal with "gdal ... --option"
7575
0
            if (GetArg(args.back()))
7576
0
            {
7577
0
                option = args.back();
7578
0
                args.pop_back();
7579
0
            }
7580
0
        }
7581
0
        else
7582
0
        {
7583
            // Deal with "gdal ... --option=<value>"
7584
0
            if (GetArg(args.back().substr(0, nPosEqual)))
7585
0
            {
7586
0
                option = args.back().substr(0, nPosEqual);
7587
0
                value = args.back().substr(nPosEqual + 1);
7588
0
                args.pop_back();
7589
0
            }
7590
0
        }
7591
0
    }
7592
0
    else if (args.size() >= 2 && !args[args.size() - 2].empty() &&
7593
0
             args[args.size() - 2][0] == '-')
7594
0
    {
7595
        // Deal with "gdal ... --option <value>"
7596
0
        auto arg = GetArg(args[args.size() - 2]);
7597
0
        if (arg && arg->GetType() != GAAT_BOOLEAN)
7598
0
        {
7599
0
            option = args[args.size() - 2];
7600
0
            value = args.back();
7601
0
            args.pop_back();
7602
0
        }
7603
0
    }
7604
7605
0
    const auto IsKeyValueOption = [](const std::string &osStr)
7606
0
    {
7607
0
        return osStr == "--co" || osStr == "--creation-option" ||
7608
0
               osStr == "--lco" || osStr == "--layer-creation-option" ||
7609
0
               osStr == "--oo" || osStr == "--open-option";
7610
0
    };
7611
7612
0
    if (IsKeyValueOption(option))
7613
0
    {
7614
0
        const auto nPosEqual = value.find('=');
7615
0
        if (nPosEqual != std::string::npos)
7616
0
        {
7617
0
            value.resize(nPosEqual);
7618
0
        }
7619
0
    }
7620
0
}
7621
7622
/************************************************************************/
7623
/*                 GDALAlgorithm::GetArgDependencies()                  */
7624
/************************************************************************/
7625
7626
std::vector<std::string>
7627
GDALAlgorithm::GetArgDependencies(const std::string &osName) const
7628
0
{
7629
0
    const auto arg = GetArg(osName, false);
7630
0
    if (!arg)
7631
0
    {
7632
0
        ReportError(CE_Failure, CPLE_AppDefined, "Argument '%s' does not exist",
7633
0
                    osName.c_str());
7634
0
        return {};
7635
0
    }
7636
0
    std::vector<std::string> dependencies = arg->GetDirectDependencies();
7637
0
    if (const auto &mutualDependencyGroup = arg->GetMutualDependencyGroup();
7638
0
        !mutualDependencyGroup.empty())
7639
0
    {
7640
0
        for (const auto &otherArg : m_args)
7641
0
        {
7642
0
            if (otherArg.get() == arg ||
7643
0
                mutualDependencyGroup.compare(
7644
0
                    otherArg->GetMutualDependencyGroup()) != 0)
7645
0
                continue;
7646
0
            dependencies.push_back(otherArg->GetName());
7647
0
        }
7648
0
    }
7649
0
    return dependencies;
7650
0
}
7651
7652
//! @cond Doxygen_Suppress
7653
7654
/************************************************************************/
7655
/*                  GDALContainerAlgorithm::RunImpl()                   */
7656
/************************************************************************/
7657
7658
bool GDALContainerAlgorithm::RunImpl(GDALProgressFunc, void *)
7659
0
{
7660
0
    return false;
7661
0
}
7662
7663
//! @endcond
7664
7665
/************************************************************************/
7666
/*                        GDALAlgorithmRelease()                        */
7667
/************************************************************************/
7668
7669
/** Release a handle to an algorithm.
7670
 *
7671
 * @since 3.11
7672
 */
7673
void GDALAlgorithmRelease(GDALAlgorithmH hAlg)
7674
0
{
7675
0
    delete hAlg;
7676
0
}
7677
7678
/************************************************************************/
7679
/*                        GDALAlgorithmGetName()                        */
7680
/************************************************************************/
7681
7682
/** Return the algorithm name.
7683
 *
7684
 * @param hAlg Handle to an algorithm. Must NOT be null.
7685
 * @return algorithm name whose lifetime is bound to hAlg and which must not
7686
 * be freed.
7687
 * @since 3.11
7688
 */
7689
const char *GDALAlgorithmGetName(GDALAlgorithmH hAlg)
7690
0
{
7691
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7692
0
    return hAlg->ptr->GetName().c_str();
7693
0
}
7694
7695
/************************************************************************/
7696
/*                    GDALAlgorithmGetDescription()                     */
7697
/************************************************************************/
7698
7699
/** Return the algorithm (short) description.
7700
 *
7701
 * @param hAlg Handle to an algorithm. Must NOT be null.
7702
 * @return algorithm description whose lifetime is bound to hAlg and which must
7703
 * not be freed.
7704
 * @since 3.11
7705
 */
7706
const char *GDALAlgorithmGetDescription(GDALAlgorithmH hAlg)
7707
0
{
7708
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7709
0
    return hAlg->ptr->GetDescription().c_str();
7710
0
}
7711
7712
/************************************************************************/
7713
/*                  GDALAlgorithmGetLongDescription()                   */
7714
/************************************************************************/
7715
7716
/** Return the algorithm (longer) description.
7717
 *
7718
 * @param hAlg Handle to an algorithm. Must NOT be null.
7719
 * @return algorithm description whose lifetime is bound to hAlg and which must
7720
 * not be freed.
7721
 * @since 3.11
7722
 */
7723
const char *GDALAlgorithmGetLongDescription(GDALAlgorithmH hAlg)
7724
0
{
7725
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7726
0
    return hAlg->ptr->GetLongDescription().c_str();
7727
0
}
7728
7729
/************************************************************************/
7730
/*                    GDALAlgorithmGetHelpFullURL()                     */
7731
/************************************************************************/
7732
7733
/** Return the algorithm full URL.
7734
 *
7735
 * @param hAlg Handle to an algorithm. Must NOT be null.
7736
 * @return algorithm URL whose lifetime is bound to hAlg and which must
7737
 * not be freed.
7738
 * @since 3.11
7739
 */
7740
const char *GDALAlgorithmGetHelpFullURL(GDALAlgorithmH hAlg)
7741
0
{
7742
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7743
0
    return hAlg->ptr->GetHelpFullURL().c_str();
7744
0
}
7745
7746
/************************************************************************/
7747
/*                   GDALAlgorithmHasSubAlgorithms()                    */
7748
/************************************************************************/
7749
7750
/** Return whether the algorithm has sub-algorithms.
7751
 *
7752
 * @param hAlg Handle to an algorithm. Must NOT be null.
7753
 * @since 3.11
7754
 */
7755
bool GDALAlgorithmHasSubAlgorithms(GDALAlgorithmH hAlg)
7756
0
{
7757
0
    VALIDATE_POINTER1(hAlg, __func__, false);
7758
0
    return hAlg->ptr->HasSubAlgorithms();
7759
0
}
7760
7761
/************************************************************************/
7762
/*                 GDALAlgorithmGetSubAlgorithmNames()                  */
7763
/************************************************************************/
7764
7765
/** Get the names of registered algorithms.
7766
 *
7767
 * @param hAlg Handle to an algorithm. Must NOT be null.
7768
 * @return a NULL terminated list of names, which must be destroyed with
7769
 * CSLDestroy()
7770
 * @since 3.11
7771
 */
7772
char **GDALAlgorithmGetSubAlgorithmNames(GDALAlgorithmH hAlg)
7773
0
{
7774
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7775
0
    return CPLStringList(hAlg->ptr->GetSubAlgorithmNames()).StealList();
7776
0
}
7777
7778
/************************************************************************/
7779
/*                GDALAlgorithmInstantiateSubAlgorithm()                */
7780
/************************************************************************/
7781
7782
/** Instantiate an algorithm by its name (or its alias).
7783
 *
7784
 * @param hAlg Handle to an algorithm. Must NOT be null.
7785
 * @param pszSubAlgName Algorithm name. Must NOT be null.
7786
 * @return an handle to the algorithm (to be freed with GDALAlgorithmRelease),
7787
 * or NULL if the algorithm does not exist or another error occurred.
7788
 * @since 3.11
7789
 */
7790
GDALAlgorithmH GDALAlgorithmInstantiateSubAlgorithm(GDALAlgorithmH hAlg,
7791
                                                    const char *pszSubAlgName)
7792
0
{
7793
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7794
0
    VALIDATE_POINTER1(pszSubAlgName, __func__, nullptr);
7795
0
    auto subAlg = hAlg->ptr->InstantiateSubAlgorithm(pszSubAlgName);
7796
0
    return subAlg
7797
0
               ? std::make_unique<GDALAlgorithmHS>(std::move(subAlg)).release()
7798
0
               : nullptr;
7799
0
}
7800
7801
/************************************************************************/
7802
/*               GDALAlgorithmParseCommandLineArguments()               */
7803
/************************************************************************/
7804
7805
/** Parse a command line argument, which does not include the algorithm
7806
 * name, to set the value of corresponding arguments.
7807
 *
7808
 * @param hAlg Handle to an algorithm. Must NOT be null.
7809
 * @param papszArgs NULL-terminated list of arguments, not including the algorithm name.
7810
 * @return true if successful, false otherwise
7811
 * @since 3.11
7812
 */
7813
7814
bool GDALAlgorithmParseCommandLineArguments(GDALAlgorithmH hAlg,
7815
                                            CSLConstList papszArgs)
7816
0
{
7817
0
    VALIDATE_POINTER1(hAlg, __func__, false);
7818
0
    return hAlg->ptr->ParseCommandLineArguments(CPLStringList(papszArgs));
7819
0
}
7820
7821
/************************************************************************/
7822
/*                  GDALAlgorithmGetActualAlgorithm()                   */
7823
/************************************************************************/
7824
7825
/** Return the actual algorithm that is going to be invoked, when the
7826
 * current algorithm has sub-algorithms.
7827
 *
7828
 * Only valid after GDALAlgorithmParseCommandLineArguments() has been called.
7829
 *
7830
 * Note that the lifetime of the returned algorithm does not exceed the one of
7831
 * the hAlg instance that owns it.
7832
 *
7833
 * @param hAlg Handle to an algorithm. Must NOT be null.
7834
 * @return an handle to the algorithm (to be freed with GDALAlgorithmRelease).
7835
 * @since 3.11
7836
 */
7837
GDALAlgorithmH GDALAlgorithmGetActualAlgorithm(GDALAlgorithmH hAlg)
7838
0
{
7839
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7840
0
    return GDALAlgorithmHS::FromRef(hAlg->ptr->GetActualAlgorithm()).release();
7841
0
}
7842
7843
/************************************************************************/
7844
/*                          GDALAlgorithmRun()                          */
7845
/************************************************************************/
7846
7847
/** Execute the algorithm, starting with ValidateArguments() and then
7848
 * calling RunImpl().
7849
 *
7850
 * This function must be called at most once per instance.
7851
 *
7852
 * @param hAlg Handle to an algorithm. Must NOT be null.
7853
 * @param pfnProgress Progress callback. May be null.
7854
 * @param pProgressData Progress callback user data. May be null.
7855
 * @return true if successful, false otherwise
7856
 * @since 3.11
7857
 */
7858
7859
bool GDALAlgorithmRun(GDALAlgorithmH hAlg, GDALProgressFunc pfnProgress,
7860
                      void *pProgressData)
7861
0
{
7862
0
    VALIDATE_POINTER1(hAlg, __func__, false);
7863
0
    return hAlg->ptr->Run(pfnProgress, pProgressData);
7864
0
}
7865
7866
/************************************************************************/
7867
/*                       GDALAlgorithmFinalize()                        */
7868
/************************************************************************/
7869
7870
/** Complete any pending actions, and return the final status.
7871
 * This is typically useful for algorithm that generate an output dataset.
7872
 *
7873
 * Note that this function does *NOT* release memory associated with the
7874
 * algorithm. GDALAlgorithmRelease() must still be called afterwards.
7875
 *
7876
 * @param hAlg Handle to an algorithm. Must NOT be null.
7877
 * @return true if successful, false otherwise
7878
 * @since 3.11
7879
 */
7880
7881
bool GDALAlgorithmFinalize(GDALAlgorithmH hAlg)
7882
0
{
7883
0
    VALIDATE_POINTER1(hAlg, __func__, false);
7884
0
    return hAlg->ptr->Finalize();
7885
0
}
7886
7887
/************************************************************************/
7888
/*                    GDALAlgorithmGetUsageAsJSON()                     */
7889
/************************************************************************/
7890
7891
/** Return the usage of the algorithm as a JSON-serialized string.
7892
 *
7893
 * This can be used to dynamically generate interfaces to algorithms.
7894
 *
7895
 * @param hAlg Handle to an algorithm. Must NOT be null.
7896
 * @return a string that must be freed with CPLFree()
7897
 * @since 3.11
7898
 */
7899
char *GDALAlgorithmGetUsageAsJSON(GDALAlgorithmH hAlg)
7900
0
{
7901
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7902
0
    return CPLStrdup(hAlg->ptr->GetUsageAsJSON().c_str());
7903
0
}
7904
7905
/************************************************************************/
7906
/*                      GDALAlgorithmGetArgNames()                      */
7907
/************************************************************************/
7908
7909
/** Return the list of available argument names.
7910
 *
7911
 * @param hAlg Handle to an algorithm. Must NOT be null.
7912
 * @return a NULL terminated list of names, which must be destroyed with
7913
 * CSLDestroy()
7914
 * @since 3.11
7915
 */
7916
char **GDALAlgorithmGetArgNames(GDALAlgorithmH hAlg)
7917
0
{
7918
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7919
0
    CPLStringList list;
7920
0
    for (const auto &arg : hAlg->ptr->GetArgs())
7921
0
        list.AddString(arg->GetName().c_str());
7922
0
    return list.StealList();
7923
0
}
7924
7925
/************************************************************************/
7926
/*                        GDALAlgorithmGetArg()                         */
7927
/************************************************************************/
7928
7929
/** Return an argument from its name.
7930
 *
7931
 * The lifetime of the returned object does not exceed the one of hAlg.
7932
 *
7933
 * @param hAlg Handle to an algorithm. Must NOT be null.
7934
 * @param pszArgName Argument name. Must NOT be null.
7935
 * @return an argument that must be released with GDALAlgorithmArgRelease(),
7936
 * or nullptr in case of error
7937
 * @since 3.11
7938
 */
7939
GDALAlgorithmArgH GDALAlgorithmGetArg(GDALAlgorithmH hAlg,
7940
                                      const char *pszArgName)
7941
0
{
7942
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7943
0
    VALIDATE_POINTER1(pszArgName, __func__, nullptr);
7944
0
    auto arg = hAlg->ptr->GetArg(pszArgName, /* suggestionAllowed = */ true,
7945
0
                                 /* isConst = */ true);
7946
0
    if (!arg)
7947
0
        return nullptr;
7948
0
    return std::make_unique<GDALAlgorithmArgHS>(arg).release();
7949
0
}
7950
7951
/************************************************************************/
7952
/*                    GDALAlgorithmGetArgNonConst()                     */
7953
/************************************************************************/
7954
7955
/** Return an argument from its name, possibly allowing creation of user-provided
7956
 * argument if the algorithm allow it.
7957
 *
7958
 * The lifetime of the returned object does not exceed the one of hAlg.
7959
 *
7960
 * @param hAlg Handle to an algorithm. Must NOT be null.
7961
 * @param pszArgName Argument name. Must NOT be null.
7962
 * @return an argument that must be released with GDALAlgorithmArgRelease(),
7963
 * or nullptr in case of error
7964
 * @since 3.12
7965
 */
7966
GDALAlgorithmArgH GDALAlgorithmGetArgNonConst(GDALAlgorithmH hAlg,
7967
                                              const char *pszArgName)
7968
0
{
7969
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7970
0
    VALIDATE_POINTER1(pszArgName, __func__, nullptr);
7971
0
    auto arg = hAlg->ptr->GetArg(pszArgName, /* suggestionAllowed = */ true,
7972
0
                                 /* isConst = */ false);
7973
0
    if (!arg)
7974
0
        return nullptr;
7975
0
    return std::make_unique<GDALAlgorithmArgHS>(arg).release();
7976
0
}
7977
7978
/************************************************************************/
7979
/*                  GDALAlgorithmGetArgDependencies()                   */
7980
/************************************************************************/
7981
7982
/** Return the list of argument names the specified argument depends on.
7983
 *
7984
 *  This includes both regular dependencies and mutual dependencies.
7985
 *
7986
 * @param hAlg Handle to an algorithm. Must NOT be null.
7987
 * @param pszArgName Argument name. Must NOT be null.
7988
 * @return a NULL terminated list of names, which must be destroyed with
7989
 * CSLDestroy()
7990
 * @since 3.11
7991
 */
7992
char **GDALAlgorithmGetArgDependencies(GDALAlgorithmH hAlg,
7993
                                       const char *pszArgName)
7994
0
{
7995
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7996
0
    VALIDATE_POINTER1(pszArgName, __func__, nullptr);
7997
0
    return CPLStringList(hAlg->ptr->GetArgDependencies(pszArgName)).StealList();
7998
0
}
7999
8000
/************************************************************************/
8001
/*                      GDALAlgorithmArgRelease()                       */
8002
/************************************************************************/
8003
8004
/** Release a handle to an argument.
8005
 *
8006
 * @since 3.11
8007
 */
8008
void GDALAlgorithmArgRelease(GDALAlgorithmArgH hArg)
8009
0
{
8010
0
    delete hArg;
8011
0
}
8012
8013
/************************************************************************/
8014
/*                      GDALAlgorithmArgGetName()                       */
8015
/************************************************************************/
8016
8017
/** Return the name of an argument.
8018
 *
8019
 * @param hArg Handle to an argument. Must NOT be null.
8020
 * @return argument name whose lifetime is bound to hArg and which must not
8021
 * be freed.
8022
 * @since 3.11
8023
 */
8024
const char *GDALAlgorithmArgGetName(GDALAlgorithmArgH hArg)
8025
0
{
8026
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8027
0
    return hArg->ptr->GetName().c_str();
8028
0
}
8029
8030
/************************************************************************/
8031
/*                      GDALAlgorithmArgGetType()                       */
8032
/************************************************************************/
8033
8034
/** Get the type of an argument
8035
 *
8036
 * @param hArg Handle to an argument. Must NOT be null.
8037
 * @since 3.11
8038
 */
8039
GDALAlgorithmArgType GDALAlgorithmArgGetType(GDALAlgorithmArgH hArg)
8040
0
{
8041
0
    VALIDATE_POINTER1(hArg, __func__, GAAT_STRING);
8042
0
    return hArg->ptr->GetType();
8043
0
}
8044
8045
/************************************************************************/
8046
/*                   GDALAlgorithmArgGetDescription()                   */
8047
/************************************************************************/
8048
8049
/** Return the description of an argument.
8050
 *
8051
 * @param hArg Handle to an argument. Must NOT be null.
8052
 * @return argument description whose lifetime is bound to hArg and which must not
8053
 * be freed.
8054
 * @since 3.11
8055
 */
8056
const char *GDALAlgorithmArgGetDescription(GDALAlgorithmArgH hArg)
8057
0
{
8058
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8059
0
    return hArg->ptr->GetDescription().c_str();
8060
0
}
8061
8062
/************************************************************************/
8063
/*                    GDALAlgorithmArgGetShortName()                    */
8064
/************************************************************************/
8065
8066
/** Return the short name, or empty string if there is none
8067
 *
8068
 * @param hArg Handle to an argument. Must NOT be null.
8069
 * @return short name whose lifetime is bound to hArg and which must not
8070
 * be freed.
8071
 * @since 3.11
8072
 */
8073
const char *GDALAlgorithmArgGetShortName(GDALAlgorithmArgH hArg)
8074
0
{
8075
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8076
0
    return hArg->ptr->GetShortName().c_str();
8077
0
}
8078
8079
/************************************************************************/
8080
/*                     GDALAlgorithmArgGetAliases()                     */
8081
/************************************************************************/
8082
8083
/** Return the aliases (potentially none)
8084
 *
8085
 * @param hArg Handle to an argument. Must NOT be null.
8086
 * @return a NULL terminated list of names, which must be destroyed with
8087
 * CSLDestroy()
8088
8089
 * @since 3.11
8090
 */
8091
char **GDALAlgorithmArgGetAliases(GDALAlgorithmArgH hArg)
8092
0
{
8093
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8094
0
    return CPLStringList(hArg->ptr->GetAliases()).StealList();
8095
0
}
8096
8097
/************************************************************************/
8098
/*                     GDALAlgorithmArgGetMetaVar()                     */
8099
/************************************************************************/
8100
8101
/** Return the "meta-var" hint.
8102
 *
8103
 * By default, the meta-var value is the long name of the argument in
8104
 * upper case.
8105
 *
8106
 * @param hArg Handle to an argument. Must NOT be null.
8107
 * @return meta-var hint whose lifetime is bound to hArg and which must not
8108
 * be freed.
8109
 * @since 3.11
8110
 */
8111
const char *GDALAlgorithmArgGetMetaVar(GDALAlgorithmArgH hArg)
8112
0
{
8113
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8114
0
    return hArg->ptr->GetMetaVar().c_str();
8115
0
}
8116
8117
/************************************************************************/
8118
/*                    GDALAlgorithmArgGetCategory()                     */
8119
/************************************************************************/
8120
8121
/** Return the argument category
8122
 *
8123
 * GAAC_COMMON, GAAC_BASE, GAAC_ADVANCED, GAAC_ESOTERIC or a custom category.
8124
 *
8125
 * @param hArg Handle to an argument. Must NOT be null.
8126
 * @return category whose lifetime is bound to hArg and which must not
8127
 * be freed.
8128
 * @since 3.11
8129
 */
8130
const char *GDALAlgorithmArgGetCategory(GDALAlgorithmArgH hArg)
8131
0
{
8132
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8133
0
    return hArg->ptr->GetCategory().c_str();
8134
0
}
8135
8136
/************************************************************************/
8137
/*                    GDALAlgorithmArgIsPositional()                    */
8138
/************************************************************************/
8139
8140
/** Return if the argument is a positional one.
8141
 *
8142
 * @param hArg Handle to an argument. Must NOT be null.
8143
 * @since 3.11
8144
 */
8145
bool GDALAlgorithmArgIsPositional(GDALAlgorithmArgH hArg)
8146
0
{
8147
0
    VALIDATE_POINTER1(hArg, __func__, false);
8148
0
    return hArg->ptr->IsPositional();
8149
0
}
8150
8151
/************************************************************************/
8152
/*                     GDALAlgorithmArgIsRequired()                     */
8153
/************************************************************************/
8154
8155
/** Return whether the argument is required. Defaults to false.
8156
 *
8157
 * @param hArg Handle to an argument. Must NOT be null.
8158
 * @since 3.11
8159
 */
8160
bool GDALAlgorithmArgIsRequired(GDALAlgorithmArgH hArg)
8161
0
{
8162
0
    VALIDATE_POINTER1(hArg, __func__, false);
8163
0
    return hArg->ptr->IsRequired();
8164
0
}
8165
8166
/************************************************************************/
8167
/*                    GDALAlgorithmArgGetMinCount()                     */
8168
/************************************************************************/
8169
8170
/** Return the minimum number of values for the argument.
8171
 *
8172
 * Defaults to 0.
8173
 * Only applies to list type of arguments.
8174
 *
8175
 * @param hArg Handle to an argument. Must NOT be null.
8176
 * @since 3.11
8177
 */
8178
int GDALAlgorithmArgGetMinCount(GDALAlgorithmArgH hArg)
8179
0
{
8180
0
    VALIDATE_POINTER1(hArg, __func__, 0);
8181
0
    return hArg->ptr->GetMinCount();
8182
0
}
8183
8184
/************************************************************************/
8185
/*                    GDALAlgorithmArgGetMaxCount()                     */
8186
/************************************************************************/
8187
8188
/** Return the maximum number of values for the argument.
8189
 *
8190
 * Defaults to 1 for scalar types, and INT_MAX for list types.
8191
 * Only applies to list type of arguments.
8192
 *
8193
 * @param hArg Handle to an argument. Must NOT be null.
8194
 * @since 3.11
8195
 */
8196
int GDALAlgorithmArgGetMaxCount(GDALAlgorithmArgH hArg)
8197
0
{
8198
0
    VALIDATE_POINTER1(hArg, __func__, 0);
8199
0
    return hArg->ptr->GetMaxCount();
8200
0
}
8201
8202
/************************************************************************/
8203
/*               GDALAlgorithmArgGetPackedValuesAllowed()               */
8204
/************************************************************************/
8205
8206
/** Return whether, for list type of arguments, several values, space
8207
 * separated, may be specified. That is "--foo=bar,baz".
8208
 * The default is true.
8209
 *
8210
 * @param hArg Handle to an argument. Must NOT be null.
8211
 * @since 3.11
8212
 */
8213
bool GDALAlgorithmArgGetPackedValuesAllowed(GDALAlgorithmArgH hArg)
8214
0
{
8215
0
    VALIDATE_POINTER1(hArg, __func__, false);
8216
0
    return hArg->ptr->GetPackedValuesAllowed();
8217
0
}
8218
8219
/************************************************************************/
8220
/*               GDALAlgorithmArgGetRepeatedArgAllowed()                */
8221
/************************************************************************/
8222
8223
/** Return whether, for list type of arguments, the argument may be
8224
 * repeated. That is "--foo=bar --foo=baz".
8225
 * The default is true.
8226
 *
8227
 * @param hArg Handle to an argument. Must NOT be null.
8228
 * @since 3.11
8229
 */
8230
bool GDALAlgorithmArgGetRepeatedArgAllowed(GDALAlgorithmArgH hArg)
8231
0
{
8232
0
    VALIDATE_POINTER1(hArg, __func__, false);
8233
0
    return hArg->ptr->GetRepeatedArgAllowed();
8234
0
}
8235
8236
/************************************************************************/
8237
/*                     GDALAlgorithmArgGetChoices()                     */
8238
/************************************************************************/
8239
8240
/** Return the allowed values (as strings) for the argument.
8241
 *
8242
 * Only honored for GAAT_STRING and GAAT_STRING_LIST types.
8243
 *
8244
 * @param hArg Handle to an argument. Must NOT be null.
8245
 * @return a NULL terminated list of names, which must be destroyed with
8246
 * CSLDestroy()
8247
8248
 * @since 3.11
8249
 */
8250
char **GDALAlgorithmArgGetChoices(GDALAlgorithmArgH hArg)
8251
0
{
8252
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8253
0
    return CPLStringList(hArg->ptr->GetChoices()).StealList();
8254
0
}
8255
8256
/************************************************************************/
8257
/*                  GDALAlgorithmArgGetMetadataItem()                   */
8258
/************************************************************************/
8259
8260
/** Return the values of the metadata item of an argument.
8261
 *
8262
 * @param hArg Handle to an argument. Must NOT be null.
8263
 * @param pszItem Name of the item. Must NOT be null.
8264
 * @return a NULL terminated list of values, which must be destroyed with
8265
 * CSLDestroy()
8266
8267
 * @since 3.11
8268
 */
8269
char **GDALAlgorithmArgGetMetadataItem(GDALAlgorithmArgH hArg,
8270
                                       const char *pszItem)
8271
0
{
8272
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8273
0
    VALIDATE_POINTER1(pszItem, __func__, nullptr);
8274
0
    const auto pVecOfStrings = hArg->ptr->GetMetadataItem(pszItem);
8275
0
    return pVecOfStrings ? CPLStringList(*pVecOfStrings).StealList() : nullptr;
8276
0
}
8277
8278
/************************************************************************/
8279
/*                  GDALAlgorithmArgIsExplicitlySet()                   */
8280
/************************************************************************/
8281
8282
/** Return whether the argument value has been explicitly set with Set()
8283
 *
8284
 * @param hArg Handle to an argument. Must NOT be null.
8285
 * @since 3.11
8286
 */
8287
bool GDALAlgorithmArgIsExplicitlySet(GDALAlgorithmArgH hArg)
8288
0
{
8289
0
    VALIDATE_POINTER1(hArg, __func__, false);
8290
0
    return hArg->ptr->IsExplicitlySet();
8291
0
}
8292
8293
/************************************************************************/
8294
/*                  GDALAlgorithmArgHasDefaultValue()                   */
8295
/************************************************************************/
8296
8297
/** Return if the argument has a declared default value.
8298
 *
8299
 * @param hArg Handle to an argument. Must NOT be null.
8300
 * @since 3.11
8301
 */
8302
bool GDALAlgorithmArgHasDefaultValue(GDALAlgorithmArgH hArg)
8303
0
{
8304
0
    VALIDATE_POINTER1(hArg, __func__, false);
8305
0
    return hArg->ptr->HasDefaultValue();
8306
0
}
8307
8308
/************************************************************************/
8309
/*                GDALAlgorithmArgGetDefaultAsBoolean()                 */
8310
/************************************************************************/
8311
8312
/** Return the argument default value as a integer.
8313
 *
8314
 * Must only be called on arguments whose type is GAAT_BOOLEAN
8315
 *
8316
 * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
8317
 * argument has a default value.
8318
 *
8319
 * @param hArg Handle to an argument. Must NOT be null.
8320
 * @since 3.12
8321
 */
8322
bool GDALAlgorithmArgGetDefaultAsBoolean(GDALAlgorithmArgH hArg)
8323
0
{
8324
0
    VALIDATE_POINTER1(hArg, __func__, false);
8325
0
    if (hArg->ptr->GetType() != GAAT_BOOLEAN)
8326
0
    {
8327
0
        CPLError(CE_Failure, CPLE_AppDefined,
8328
0
                 "%s must only be called on arguments of type GAAT_BOOLEAN",
8329
0
                 __func__);
8330
0
        return false;
8331
0
    }
8332
0
    return hArg->ptr->GetDefault<bool>();
8333
0
}
8334
8335
/************************************************************************/
8336
/*                 GDALAlgorithmArgGetDefaultAsString()                 */
8337
/************************************************************************/
8338
8339
/** Return the argument default value as a string.
8340
 *
8341
 * Must only be called on arguments whose type is GAAT_STRING.
8342
 *
8343
 * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
8344
 * argument has a default value.
8345
 *
8346
 * @param hArg Handle to an argument. Must NOT be null.
8347
 * @return string whose lifetime is bound to hArg and which must not
8348
 * be freed.
8349
 * @since 3.11
8350
 */
8351
const char *GDALAlgorithmArgGetDefaultAsString(GDALAlgorithmArgH hArg)
8352
0
{
8353
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8354
0
    if (hArg->ptr->GetType() != GAAT_STRING)
8355
0
    {
8356
0
        CPLError(CE_Failure, CPLE_AppDefined,
8357
0
                 "%s must only be called on arguments of type GAAT_STRING",
8358
0
                 __func__);
8359
0
        return nullptr;
8360
0
    }
8361
0
    return hArg->ptr->GetDefault<std::string>().c_str();
8362
0
}
8363
8364
/************************************************************************/
8365
/*                GDALAlgorithmArgGetDefaultAsInteger()                 */
8366
/************************************************************************/
8367
8368
/** Return the argument default value as a integer.
8369
 *
8370
 * Must only be called on arguments whose type is GAAT_INTEGER
8371
 *
8372
 * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
8373
 * argument has a default value.
8374
 *
8375
 * @param hArg Handle to an argument. Must NOT be null.
8376
 * @since 3.12
8377
 */
8378
int GDALAlgorithmArgGetDefaultAsInteger(GDALAlgorithmArgH hArg)
8379
0
{
8380
0
    VALIDATE_POINTER1(hArg, __func__, 0);
8381
0
    if (hArg->ptr->GetType() != GAAT_INTEGER)
8382
0
    {
8383
0
        CPLError(CE_Failure, CPLE_AppDefined,
8384
0
                 "%s must only be called on arguments of type GAAT_INTEGER",
8385
0
                 __func__);
8386
0
        return 0;
8387
0
    }
8388
0
    return hArg->ptr->GetDefault<int>();
8389
0
}
8390
8391
/************************************************************************/
8392
/*                 GDALAlgorithmArgGetDefaultAsDouble()                 */
8393
/************************************************************************/
8394
8395
/** Return the argument default value as a double.
8396
 *
8397
 * Must only be called on arguments whose type is GAAT_REAL
8398
 *
8399
 * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
8400
 * argument has a default value.
8401
 *
8402
 * @param hArg Handle to an argument. Must NOT be null.
8403
 * @since 3.12
8404
 */
8405
double GDALAlgorithmArgGetDefaultAsDouble(GDALAlgorithmArgH hArg)
8406
0
{
8407
0
    VALIDATE_POINTER1(hArg, __func__, 0);
8408
0
    if (hArg->ptr->GetType() != GAAT_REAL)
8409
0
    {
8410
0
        CPLError(CE_Failure, CPLE_AppDefined,
8411
0
                 "%s must only be called on arguments of type GAAT_REAL",
8412
0
                 __func__);
8413
0
        return 0;
8414
0
    }
8415
0
    return hArg->ptr->GetDefault<double>();
8416
0
}
8417
8418
/************************************************************************/
8419
/*               GDALAlgorithmArgGetDefaultAsStringList()               */
8420
/************************************************************************/
8421
8422
/** Return the argument default value as a string list.
8423
 *
8424
 * Must only be called on arguments whose type is GAAT_STRING_LIST.
8425
 *
8426
 * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
8427
 * argument has a default value.
8428
 *
8429
 * @param hArg Handle to an argument. Must NOT be null.
8430
 * @return a NULL terminated list of names, which must be destroyed with
8431
 * CSLDestroy()
8432
8433
 * @since 3.12
8434
 */
8435
char **GDALAlgorithmArgGetDefaultAsStringList(GDALAlgorithmArgH hArg)
8436
0
{
8437
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8438
0
    if (hArg->ptr->GetType() != GAAT_STRING_LIST)
8439
0
    {
8440
0
        CPLError(CE_Failure, CPLE_AppDefined,
8441
0
                 "%s must only be called on arguments of type GAAT_STRING_LIST",
8442
0
                 __func__);
8443
0
        return nullptr;
8444
0
    }
8445
0
    return CPLStringList(hArg->ptr->GetDefault<std::vector<std::string>>())
8446
0
        .StealList();
8447
0
}
8448
8449
/************************************************************************/
8450
/*              GDALAlgorithmArgGetDefaultAsIntegerList()               */
8451
/************************************************************************/
8452
8453
/** Return the argument default value as a integer list.
8454
 *
8455
 * Must only be called on arguments whose type is GAAT_INTEGER_LIST.
8456
 *
8457
 * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
8458
 * argument has a default value.
8459
 *
8460
 * @param hArg Handle to an argument. Must NOT be null.
8461
 * @param[out] pnCount Pointer to the number of values in the list. Must NOT be null.
8462
 * @since 3.12
8463
 */
8464
const int *GDALAlgorithmArgGetDefaultAsIntegerList(GDALAlgorithmArgH hArg,
8465
                                                   size_t *pnCount)
8466
0
{
8467
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8468
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
8469
0
    if (hArg->ptr->GetType() != GAAT_INTEGER_LIST)
8470
0
    {
8471
0
        CPLError(
8472
0
            CE_Failure, CPLE_AppDefined,
8473
0
            "%s must only be called on arguments of type GAAT_INTEGER_LIST",
8474
0
            __func__);
8475
0
        *pnCount = 0;
8476
0
        return nullptr;
8477
0
    }
8478
0
    const auto &val = hArg->ptr->GetDefault<std::vector<int>>();
8479
0
    *pnCount = val.size();
8480
0
    return val.data();
8481
0
}
8482
8483
/************************************************************************/
8484
/*               GDALAlgorithmArgGetDefaultAsDoubleList()               */
8485
/************************************************************************/
8486
8487
/** Return the argument default value as a real list.
8488
 *
8489
 * Must only be called on arguments whose type is GAAT_REAL_LIST.
8490
 *
8491
 * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
8492
 * argument has a default value.
8493
 *
8494
 * @param hArg Handle to an argument. Must NOT be null.
8495
 * @param[out] pnCount Pointer to the number of values in the list. Must NOT be null.
8496
 * @since 3.12
8497
 */
8498
const double *GDALAlgorithmArgGetDefaultAsDoubleList(GDALAlgorithmArgH hArg,
8499
                                                     size_t *pnCount)
8500
0
{
8501
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8502
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
8503
0
    if (hArg->ptr->GetType() != GAAT_REAL_LIST)
8504
0
    {
8505
0
        CPLError(CE_Failure, CPLE_AppDefined,
8506
0
                 "%s must only be called on arguments of type GAAT_REAL_LIST",
8507
0
                 __func__);
8508
0
        *pnCount = 0;
8509
0
        return nullptr;
8510
0
    }
8511
0
    const auto &val = hArg->ptr->GetDefault<std::vector<double>>();
8512
0
    *pnCount = val.size();
8513
0
    return val.data();
8514
0
}
8515
8516
/************************************************************************/
8517
/*                      GDALAlgorithmArgIsHidden()                      */
8518
/************************************************************************/
8519
8520
/** Return whether the argument is hidden (for GDAL internal use)
8521
 *
8522
 * This is an alias for GDALAlgorithmArgIsHiddenForCLI() &&
8523
 * GDALAlgorithmArgIsHiddenForAPI().
8524
 *
8525
 * @param hArg Handle to an argument. Must NOT be null.
8526
 * @since 3.12
8527
 */
8528
bool GDALAlgorithmArgIsHidden(GDALAlgorithmArgH hArg)
8529
0
{
8530
0
    VALIDATE_POINTER1(hArg, __func__, false);
8531
0
    return hArg->ptr->IsHidden();
8532
0
}
8533
8534
/************************************************************************/
8535
/*                   GDALAlgorithmArgIsHiddenForCLI()                   */
8536
/************************************************************************/
8537
8538
/** Return whether the argument must not be mentioned in CLI usage.
8539
 *
8540
 * For example, "output-value" for "gdal raster info", which is only
8541
 * meant when the algorithm is used from a non-CLI context.
8542
 *
8543
 * @param hArg Handle to an argument. Must NOT be null.
8544
 * @since 3.11
8545
 */
8546
bool GDALAlgorithmArgIsHiddenForCLI(GDALAlgorithmArgH hArg)
8547
0
{
8548
0
    VALIDATE_POINTER1(hArg, __func__, false);
8549
0
    return hArg->ptr->IsHiddenForCLI();
8550
0
}
8551
8552
/************************************************************************/
8553
/*                   GDALAlgorithmArgIsHiddenForAPI()                   */
8554
/************************************************************************/
8555
8556
/** Return whether the argument must not be mentioned in the context of an
8557
 * API use.
8558
 * Said otherwise, if it is only for CLI usage.
8559
 *
8560
 * For example "--help"
8561
 *
8562
 * @param hArg Handle to an argument. Must NOT be null.
8563
 * @since 3.12
8564
 */
8565
bool GDALAlgorithmArgIsHiddenForAPI(GDALAlgorithmArgH hArg)
8566
0
{
8567
0
    VALIDATE_POINTER1(hArg, __func__, false);
8568
0
    return hArg->ptr->IsHiddenForAPI();
8569
0
}
8570
8571
/************************************************************************/
8572
/*                    GDALAlgorithmArgIsOnlyForCLI()                    */
8573
/************************************************************************/
8574
8575
/** Return whether the argument must not be mentioned in the context of an
8576
 * API use.
8577
 * Said otherwise, if it is only for CLI usage.
8578
 *
8579
 * For example "--help"
8580
 *
8581
 * @param hArg Handle to an argument. Must NOT be null.
8582
 * @since 3.11
8583
 * @deprecated Use GDALAlgorithmArgIsHiddenForAPI() instead.
8584
 */
8585
bool GDALAlgorithmArgIsOnlyForCLI(GDALAlgorithmArgH hArg)
8586
0
{
8587
0
    VALIDATE_POINTER1(hArg, __func__, false);
8588
0
    return hArg->ptr->IsHiddenForAPI();
8589
0
}
8590
8591
/************************************************************************/
8592
/*             GDALAlgorithmArgIsAvailableInPipelineStep()              */
8593
/************************************************************************/
8594
8595
/** Return whether the argument is available in a pipeline step.
8596
 *
8597
 * If false, it is only available in standalone mode.
8598
 *
8599
 * @param hArg Handle to an argument. Must NOT be null.
8600
 * @since 3.13
8601
 */
8602
bool GDALAlgorithmArgIsAvailableInPipelineStep(GDALAlgorithmArgH hArg)
8603
0
{
8604
0
    VALIDATE_POINTER1(hArg, __func__, false);
8605
0
    return hArg->ptr->IsAvailableInPipelineStep();
8606
0
}
8607
8608
/************************************************************************/
8609
/*                      GDALAlgorithmArgIsInput()                       */
8610
/************************************************************************/
8611
8612
/** Indicate whether the value of the argument is read-only during the
8613
 * execution of the algorithm.
8614
 *
8615
 * Default is true.
8616
 *
8617
 * @param hArg Handle to an argument. Must NOT be null.
8618
 * @since 3.11
8619
 */
8620
bool GDALAlgorithmArgIsInput(GDALAlgorithmArgH hArg)
8621
0
{
8622
0
    VALIDATE_POINTER1(hArg, __func__, false);
8623
0
    return hArg->ptr->IsInput();
8624
0
}
8625
8626
/************************************************************************/
8627
/*                      GDALAlgorithmArgIsOutput()                      */
8628
/************************************************************************/
8629
8630
/** Return whether (at least part of) the value of the argument is set
8631
 * during the execution of the algorithm.
8632
 *
8633
 * For example, "output-value" for "gdal raster info"
8634
 * Default is false.
8635
 * An argument may return both IsInput() and IsOutput() as true.
8636
 * For example the "gdal raster convert" algorithm consumes the dataset
8637
 * name of its "output" argument, and sets the dataset object during its
8638
 * execution.
8639
 *
8640
 * @param hArg Handle to an argument. Must NOT be null.
8641
 * @since 3.11
8642
 */
8643
bool GDALAlgorithmArgIsOutput(GDALAlgorithmArgH hArg)
8644
0
{
8645
0
    VALIDATE_POINTER1(hArg, __func__, false);
8646
0
    return hArg->ptr->IsOutput();
8647
0
}
8648
8649
/************************************************************************/
8650
/*                   GDALAlgorithmArgGetDatasetType()                   */
8651
/************************************************************************/
8652
8653
/** Get which type of dataset is allowed / generated.
8654
 *
8655
 * Binary-or combination of GDAL_OF_RASTER, GDAL_OF_VECTOR and
8656
 * GDAL_OF_MULTIDIM_RASTER.
8657
 * Only applies to arguments of type GAAT_DATASET or GAAT_DATASET_LIST.
8658
 *
8659
 * @param hArg Handle to an argument. Must NOT be null.
8660
 * @since 3.11
8661
 */
8662
GDALArgDatasetType GDALAlgorithmArgGetDatasetType(GDALAlgorithmArgH hArg)
8663
0
{
8664
0
    VALIDATE_POINTER1(hArg, __func__, 0);
8665
0
    return hArg->ptr->GetDatasetType();
8666
0
}
8667
8668
/************************************************************************/
8669
/*                GDALAlgorithmArgGetDatasetInputFlags()                */
8670
/************************************************************************/
8671
8672
/** Indicates which components among name and dataset are accepted as
8673
 * input, when this argument serves as an input.
8674
 *
8675
 * If the GADV_NAME bit is set, it indicates a dataset name is accepted as
8676
 * input.
8677
 * If the GADV_OBJECT bit is set, it indicates a dataset object is
8678
 * accepted as input.
8679
 * If both bits are set, the algorithm can accept either a name or a dataset
8680
 * object.
8681
 * Only applies to arguments of type GAAT_DATASET or GAAT_DATASET_LIST.
8682
 *
8683
 * @param hArg Handle to an argument. Must NOT be null.
8684
 * @return string whose lifetime is bound to hAlg and which must not
8685
 * be freed.
8686
 * @since 3.11
8687
 */
8688
int GDALAlgorithmArgGetDatasetInputFlags(GDALAlgorithmArgH hArg)
8689
0
{
8690
0
    VALIDATE_POINTER1(hArg, __func__, 0);
8691
0
    return hArg->ptr->GetDatasetInputFlags();
8692
0
}
8693
8694
/************************************************************************/
8695
/*               GDALAlgorithmArgGetDatasetOutputFlags()                */
8696
/************************************************************************/
8697
8698
/** Indicates which components among name and dataset are modified,
8699
 * when this argument serves as an output.
8700
 *
8701
 * If the GADV_NAME bit is set, it indicates a dataset name is generated as
8702
 * output (that is the algorithm will generate the name. Rarely used).
8703
 * If the GADV_OBJECT bit is set, it indicates a dataset object is
8704
 * generated as output, and available for use after the algorithm has
8705
 * completed.
8706
 * Only applies to arguments of type GAAT_DATASET or GAAT_DATASET_LIST.
8707
 *
8708
 * @param hArg Handle to an argument. Must NOT be null.
8709
 * @return string whose lifetime is bound to hAlg and which must not
8710
 * be freed.
8711
 * @since 3.11
8712
 */
8713
int GDALAlgorithmArgGetDatasetOutputFlags(GDALAlgorithmArgH hArg)
8714
0
{
8715
0
    VALIDATE_POINTER1(hArg, __func__, 0);
8716
0
    return hArg->ptr->GetDatasetOutputFlags();
8717
0
}
8718
8719
/************************************************************************/
8720
/*              GDALAlgorithmArgGetMutualExclusionGroup()               */
8721
/************************************************************************/
8722
8723
/** Return the name of the mutual exclusion group to which this argument
8724
 * belongs to.
8725
 *
8726
 * Or empty string if it does not belong to any exclusion group.
8727
 *
8728
 * @param hArg Handle to an argument. Must NOT be null.
8729
 * @return string whose lifetime is bound to hArg and which must not
8730
 * be freed.
8731
 * @since 3.11
8732
 */
8733
const char *GDALAlgorithmArgGetMutualExclusionGroup(GDALAlgorithmArgH hArg)
8734
0
{
8735
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8736
0
    return hArg->ptr->GetMutualExclusionGroup().c_str();
8737
0
}
8738
8739
/************************************************************************/
8740
/*              GDALAlgorithmArgGetMutualDependencyGroup()              */
8741
/************************************************************************/
8742
8743
/** Return the name of the mutual dependency group to which this argument
8744
 * belongs to.
8745
 *
8746
 * Or empty string if it does not belong to any dependency group.
8747
 *
8748
 * @param hArg Handle to an argument. Must NOT be null.
8749
 * @return string whose lifetime is bound to hArg and which must not
8750
 * be freed.
8751
 * @since 3.13
8752
 */
8753
const char *GDALAlgorithmArgGetMutualDependencyGroup(GDALAlgorithmArgH hArg)
8754
0
{
8755
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8756
0
    return hArg->ptr->GetMutualDependencyGroup().c_str();
8757
0
}
8758
8759
/************************************************************************/
8760
/*               GDALAlgorithmArgGetDirectDependencies()                */
8761
/************************************************************************/
8762
8763
/** Return the list of names of arguments that this argument depends on.
8764
 *
8765
 *  This is not necessarily a symmetric relationship.
8766
 *  If argument A depends on argument B, it doesn't mean that B depends on A.
8767
 *  Mutual dependency groups are a special case of dependencies,
8768
 *  where all arguments of the group depend on each other and are not
8769
 *  returned by this method.
8770
 *
8771
 * @param hArg Handle to an argument. Must NOT be null.
8772
 * @return a NULL terminated list of names, which must be destroyed with
8773
 * CSLDestroy()
8774
 * @since 3.13
8775
 */
8776
char **GDALAlgorithmArgGetDirectDependencies(GDALAlgorithmArgH hArg)
8777
0
{
8778
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8779
0
    return CPLStringList(hArg->ptr->GetDirectDependencies()).StealList();
8780
0
}
8781
8782
/************************************************************************/
8783
/*                    GDALAlgorithmArgGetAsBoolean()                    */
8784
/************************************************************************/
8785
8786
/** Return the argument value as a boolean.
8787
 *
8788
 * Must only be called on arguments whose type is GAAT_BOOLEAN.
8789
 *
8790
 * @param hArg Handle to an argument. Must NOT be null.
8791
 * @since 3.11
8792
 */
8793
bool GDALAlgorithmArgGetAsBoolean(GDALAlgorithmArgH hArg)
8794
0
{
8795
0
    VALIDATE_POINTER1(hArg, __func__, false);
8796
0
    if (hArg->ptr->GetType() != GAAT_BOOLEAN)
8797
0
    {
8798
0
        CPLError(CE_Failure, CPLE_AppDefined,
8799
0
                 "%s must only be called on arguments of type GAAT_BOOLEAN",
8800
0
                 __func__);
8801
0
        return false;
8802
0
    }
8803
0
    return hArg->ptr->Get<bool>();
8804
0
}
8805
8806
/************************************************************************/
8807
/*                    GDALAlgorithmArgGetAsString()                     */
8808
/************************************************************************/
8809
8810
/** Return the argument value as a string.
8811
 *
8812
 * Must only be called on arguments whose type is GAAT_STRING.
8813
 *
8814
 * @param hArg Handle to an argument. Must NOT be null.
8815
 * @return string whose lifetime is bound to hArg and which must not
8816
 * be freed.
8817
 * @since 3.11
8818
 */
8819
const char *GDALAlgorithmArgGetAsString(GDALAlgorithmArgH hArg)
8820
0
{
8821
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8822
0
    if (hArg->ptr->GetType() != GAAT_STRING)
8823
0
    {
8824
0
        CPLError(CE_Failure, CPLE_AppDefined,
8825
0
                 "%s must only be called on arguments of type GAAT_STRING",
8826
0
                 __func__);
8827
0
        return nullptr;
8828
0
    }
8829
0
    return hArg->ptr->Get<std::string>().c_str();
8830
0
}
8831
8832
/************************************************************************/
8833
/*                 GDALAlgorithmArgGetAsDatasetValue()                  */
8834
/************************************************************************/
8835
8836
/** Return the argument value as a GDALArgDatasetValueH.
8837
 *
8838
 * Must only be called on arguments whose type is GAAT_DATASET
8839
 *
8840
 * @param hArg Handle to an argument. Must NOT be null.
8841
 * @return handle to a GDALArgDatasetValue that must be released with
8842
 * GDALArgDatasetValueRelease(). The lifetime of that handle does not exceed
8843
 * the one of hArg.
8844
 * @since 3.11
8845
 */
8846
GDALArgDatasetValueH GDALAlgorithmArgGetAsDatasetValue(GDALAlgorithmArgH hArg)
8847
0
{
8848
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8849
0
    if (hArg->ptr->GetType() != GAAT_DATASET)
8850
0
    {
8851
0
        CPLError(CE_Failure, CPLE_AppDefined,
8852
0
                 "%s must only be called on arguments of type GAAT_DATASET",
8853
0
                 __func__);
8854
0
        return nullptr;
8855
0
    }
8856
0
    return std::make_unique<GDALArgDatasetValueHS>(
8857
0
               &(hArg->ptr->Get<GDALArgDatasetValue>()))
8858
0
        .release();
8859
0
}
8860
8861
/************************************************************************/
8862
/*                    GDALAlgorithmArgGetAsInteger()                    */
8863
/************************************************************************/
8864
8865
/** Return the argument value as a integer.
8866
 *
8867
 * Must only be called on arguments whose type is GAAT_INTEGER
8868
 *
8869
 * @param hArg Handle to an argument. Must NOT be null.
8870
 * @since 3.11
8871
 */
8872
int GDALAlgorithmArgGetAsInteger(GDALAlgorithmArgH hArg)
8873
0
{
8874
0
    VALIDATE_POINTER1(hArg, __func__, 0);
8875
0
    if (hArg->ptr->GetType() != GAAT_INTEGER)
8876
0
    {
8877
0
        CPLError(CE_Failure, CPLE_AppDefined,
8878
0
                 "%s must only be called on arguments of type GAAT_INTEGER",
8879
0
                 __func__);
8880
0
        return 0;
8881
0
    }
8882
0
    return hArg->ptr->Get<int>();
8883
0
}
8884
8885
/************************************************************************/
8886
/*                    GDALAlgorithmArgGetAsDouble()                     */
8887
/************************************************************************/
8888
8889
/** Return the argument value as a double.
8890
 *
8891
 * Must only be called on arguments whose type is GAAT_REAL
8892
 *
8893
 * @param hArg Handle to an argument. Must NOT be null.
8894
 * @since 3.11
8895
 */
8896
double GDALAlgorithmArgGetAsDouble(GDALAlgorithmArgH hArg)
8897
0
{
8898
0
    VALIDATE_POINTER1(hArg, __func__, 0);
8899
0
    if (hArg->ptr->GetType() != GAAT_REAL)
8900
0
    {
8901
0
        CPLError(CE_Failure, CPLE_AppDefined,
8902
0
                 "%s must only be called on arguments of type GAAT_REAL",
8903
0
                 __func__);
8904
0
        return 0;
8905
0
    }
8906
0
    return hArg->ptr->Get<double>();
8907
0
}
8908
8909
/************************************************************************/
8910
/*                  GDALAlgorithmArgGetAsStringList()                   */
8911
/************************************************************************/
8912
8913
/** Return the argument value as a string list.
8914
 *
8915
 * Must only be called on arguments whose type is GAAT_STRING_LIST.
8916
 *
8917
 * @param hArg Handle to an argument. Must NOT be null.
8918
 * @return a NULL terminated list of names, which must be destroyed with
8919
 * CSLDestroy()
8920
8921
 * @since 3.11
8922
 */
8923
char **GDALAlgorithmArgGetAsStringList(GDALAlgorithmArgH hArg)
8924
0
{
8925
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8926
0
    if (hArg->ptr->GetType() != GAAT_STRING_LIST)
8927
0
    {
8928
0
        CPLError(CE_Failure, CPLE_AppDefined,
8929
0
                 "%s must only be called on arguments of type GAAT_STRING_LIST",
8930
0
                 __func__);
8931
0
        return nullptr;
8932
0
    }
8933
0
    return CPLStringList(hArg->ptr->Get<std::vector<std::string>>())
8934
0
        .StealList();
8935
0
}
8936
8937
/************************************************************************/
8938
/*                  GDALAlgorithmArgGetAsIntegerList()                  */
8939
/************************************************************************/
8940
8941
/** Return the argument value as a integer list.
8942
 *
8943
 * Must only be called on arguments whose type is GAAT_INTEGER_LIST.
8944
 *
8945
 * @param hArg Handle to an argument. Must NOT be null.
8946
 * @param[out] pnCount Pointer to the number of values in the list. Must NOT be null.
8947
 * @since 3.11
8948
 */
8949
const int *GDALAlgorithmArgGetAsIntegerList(GDALAlgorithmArgH hArg,
8950
                                            size_t *pnCount)
8951
0
{
8952
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8953
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
8954
0
    if (hArg->ptr->GetType() != GAAT_INTEGER_LIST)
8955
0
    {
8956
0
        CPLError(
8957
0
            CE_Failure, CPLE_AppDefined,
8958
0
            "%s must only be called on arguments of type GAAT_INTEGER_LIST",
8959
0
            __func__);
8960
0
        *pnCount = 0;
8961
0
        return nullptr;
8962
0
    }
8963
0
    const auto &val = hArg->ptr->Get<std::vector<int>>();
8964
0
    *pnCount = val.size();
8965
0
    return val.data();
8966
0
}
8967
8968
/************************************************************************/
8969
/*                  GDALAlgorithmArgGetAsDoubleList()                   */
8970
/************************************************************************/
8971
8972
/** Return the argument value as a real list.
8973
 *
8974
 * Must only be called on arguments whose type is GAAT_REAL_LIST.
8975
 *
8976
 * @param hArg Handle to an argument. Must NOT be null.
8977
 * @param[out] pnCount Pointer to the number of values in the list. Must NOT be null.
8978
 * @since 3.11
8979
 */
8980
const double *GDALAlgorithmArgGetAsDoubleList(GDALAlgorithmArgH hArg,
8981
                                              size_t *pnCount)
8982
0
{
8983
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8984
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
8985
0
    if (hArg->ptr->GetType() != GAAT_REAL_LIST)
8986
0
    {
8987
0
        CPLError(CE_Failure, CPLE_AppDefined,
8988
0
                 "%s must only be called on arguments of type GAAT_REAL_LIST",
8989
0
                 __func__);
8990
0
        *pnCount = 0;
8991
0
        return nullptr;
8992
0
    }
8993
0
    const auto &val = hArg->ptr->Get<std::vector<double>>();
8994
0
    *pnCount = val.size();
8995
0
    return val.data();
8996
0
}
8997
8998
/************************************************************************/
8999
/*                    GDALAlgorithmArgSetAsBoolean()                    */
9000
/************************************************************************/
9001
9002
/** Set the value for a GAAT_BOOLEAN argument.
9003
 *
9004
 * It cannot be called several times for a given argument.
9005
 * Validation checks and other actions are run.
9006
 *
9007
 * @param hArg Handle to an argument. Must NOT be null.
9008
 * @param value value.
9009
 * @return true if success.
9010
 * @since 3.11
9011
 */
9012
9013
bool GDALAlgorithmArgSetAsBoolean(GDALAlgorithmArgH hArg, bool value)
9014
0
{
9015
0
    VALIDATE_POINTER1(hArg, __func__, false);
9016
0
    return hArg->ptr->Set(value);
9017
0
}
9018
9019
/************************************************************************/
9020
/*                    GDALAlgorithmArgSetAsString()                     */
9021
/************************************************************************/
9022
9023
/** Set the value for a GAAT_STRING argument.
9024
 *
9025
 * It cannot be called several times for a given argument.
9026
 * Validation checks and other actions are run.
9027
 *
9028
 * @param hArg Handle to an argument. Must NOT be null.
9029
 * @param value value (may be null)
9030
 * @return true if success.
9031
 * @since 3.11
9032
 */
9033
9034
bool GDALAlgorithmArgSetAsString(GDALAlgorithmArgH hArg, const char *value)
9035
0
{
9036
0
    VALIDATE_POINTER1(hArg, __func__, false);
9037
0
    return hArg->ptr->Set(value ? value : "");
9038
0
}
9039
9040
/************************************************************************/
9041
/*                    GDALAlgorithmArgSetAsInteger()                    */
9042
/************************************************************************/
9043
9044
/** Set the value for a GAAT_INTEGER (or GAAT_REAL) argument.
9045
 *
9046
 * It cannot be called several times for a given argument.
9047
 * Validation checks and other actions are run.
9048
 *
9049
 * @param hArg Handle to an argument. Must NOT be null.
9050
 * @param value value.
9051
 * @return true if success.
9052
 * @since 3.11
9053
 */
9054
9055
bool GDALAlgorithmArgSetAsInteger(GDALAlgorithmArgH hArg, int value)
9056
0
{
9057
0
    VALIDATE_POINTER1(hArg, __func__, false);
9058
0
    return hArg->ptr->Set(value);
9059
0
}
9060
9061
/************************************************************************/
9062
/*                    GDALAlgorithmArgSetAsDouble()                     */
9063
/************************************************************************/
9064
9065
/** Set the value for a GAAT_REAL argument.
9066
 *
9067
 * It cannot be called several times for a given argument.
9068
 * Validation checks and other actions are run.
9069
 *
9070
 * @param hArg Handle to an argument. Must NOT be null.
9071
 * @param value value.
9072
 * @return true if success.
9073
 * @since 3.11
9074
 */
9075
9076
bool GDALAlgorithmArgSetAsDouble(GDALAlgorithmArgH hArg, double value)
9077
0
{
9078
0
    VALIDATE_POINTER1(hArg, __func__, false);
9079
0
    return hArg->ptr->Set(value);
9080
0
}
9081
9082
/************************************************************************/
9083
/*                 GDALAlgorithmArgSetAsDatasetValue()                  */
9084
/************************************************************************/
9085
9086
/** Set the value for a GAAT_DATASET argument.
9087
 *
9088
 * It cannot be called several times for a given argument.
9089
 * Validation checks and other actions are run.
9090
 *
9091
 * @param hArg Handle to an argument. Must NOT be null.
9092
 * @param value Handle to a GDALArgDatasetValue. Must NOT be null.
9093
 * @return true if success.
9094
 * @since 3.11
9095
 */
9096
bool GDALAlgorithmArgSetAsDatasetValue(GDALAlgorithmArgH hArg,
9097
                                       GDALArgDatasetValueH value)
9098
0
{
9099
0
    VALIDATE_POINTER1(hArg, __func__, false);
9100
0
    VALIDATE_POINTER1(value, __func__, false);
9101
0
    return hArg->ptr->SetFrom(*(value->ptr));
9102
0
}
9103
9104
/************************************************************************/
9105
/*                     GDALAlgorithmArgSetDataset()                     */
9106
/************************************************************************/
9107
9108
/** Set dataset object, increasing its reference counter.
9109
 *
9110
 * @param hArg Handle to an argument. Must NOT be null.
9111
 * @param hDS Dataset object. May be null.
9112
 * @return true if success.
9113
 * @since 3.11
9114
 */
9115
9116
bool GDALAlgorithmArgSetDataset(GDALAlgorithmArgH hArg, GDALDatasetH hDS)
9117
0
{
9118
0
    VALIDATE_POINTER1(hArg, __func__, false);
9119
0
    return hArg->ptr->Set(GDALDataset::FromHandle(hDS));
9120
0
}
9121
9122
/************************************************************************/
9123
/*                  GDALAlgorithmArgSetAsStringList()                   */
9124
/************************************************************************/
9125
9126
/** Set the value for a GAAT_STRING_LIST argument.
9127
 *
9128
 * It cannot be called several times for a given argument.
9129
 * Validation checks and other actions are run.
9130
 *
9131
 * @param hArg Handle to an argument. Must NOT be null.
9132
 * @param value value as a NULL terminated list (may be null)
9133
 * @return true if success.
9134
 * @since 3.11
9135
 */
9136
9137
bool GDALAlgorithmArgSetAsStringList(GDALAlgorithmArgH hArg, CSLConstList value)
9138
0
{
9139
0
    VALIDATE_POINTER1(hArg, __func__, false);
9140
0
    return hArg->ptr->Set(
9141
0
        static_cast<std::vector<std::string>>(CPLStringList(value)));
9142
0
}
9143
9144
/************************************************************************/
9145
/*                  GDALAlgorithmArgSetAsIntegerList()                  */
9146
/************************************************************************/
9147
9148
/** Set the value for a GAAT_INTEGER_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 nCount Number of values in pnValues.
9155
 * @param pnValues Pointer to an array of integer values of size nCount.
9156
 * @return true if success.
9157
 * @since 3.11
9158
 */
9159
bool GDALAlgorithmArgSetAsIntegerList(GDALAlgorithmArgH hArg, size_t nCount,
9160
                                      const int *pnValues)
9161
0
{
9162
0
    VALIDATE_POINTER1(hArg, __func__, false);
9163
0
    return hArg->ptr->Set(std::vector<int>(pnValues, pnValues + nCount));
9164
0
}
9165
9166
/************************************************************************/
9167
/*                  GDALAlgorithmArgSetAsDoubleList()                   */
9168
/************************************************************************/
9169
9170
/** Set the value for a GAAT_REAL_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 double values of size nCount.
9178
 * @return true if success.
9179
 * @since 3.11
9180
 */
9181
bool GDALAlgorithmArgSetAsDoubleList(GDALAlgorithmArgH hArg, size_t nCount,
9182
                                     const double *pnValues)
9183
0
{
9184
0
    VALIDATE_POINTER1(hArg, __func__, false);
9185
0
    return hArg->ptr->Set(std::vector<double>(pnValues, pnValues + nCount));
9186
0
}
9187
9188
/************************************************************************/
9189
/*                    GDALAlgorithmArgSetDatasets()                     */
9190
/************************************************************************/
9191
9192
/** Set dataset objects to a GAAT_DATASET_LIST argument, increasing their reference counter.
9193
 *
9194
 * @param hArg Handle to an argument. Must NOT be null.
9195
 * @param nCount Number of values in pnValues.
9196
 * @param pahDS Pointer to an array of dataset of size nCount.
9197
 * @return true if success.
9198
 * @since 3.11
9199
 */
9200
9201
bool GDALAlgorithmArgSetDatasets(GDALAlgorithmArgH hArg, size_t nCount,
9202
                                 GDALDatasetH *pahDS)
9203
0
{
9204
0
    VALIDATE_POINTER1(hArg, __func__, false);
9205
0
    std::vector<GDALArgDatasetValue> values;
9206
0
    for (size_t i = 0; i < nCount; ++i)
9207
0
    {
9208
0
        values.emplace_back(GDALDataset::FromHandle(pahDS[i]));
9209
0
    }
9210
0
    return hArg->ptr->Set(std::move(values));
9211
0
}
9212
9213
/************************************************************************/
9214
/*                  GDALAlgorithmArgSetDatasetNames()                   */
9215
/************************************************************************/
9216
9217
/** Set dataset names to a GAAT_DATASET_LIST argument.
9218
 *
9219
 * @param hArg Handle to an argument. Must NOT be null.
9220
 * @param names Dataset names as a NULL terminated list (may be null)
9221
 * @return true if success.
9222
 * @since 3.11
9223
 */
9224
9225
bool GDALAlgorithmArgSetDatasetNames(GDALAlgorithmArgH hArg, CSLConstList names)
9226
0
{
9227
0
    VALIDATE_POINTER1(hArg, __func__, false);
9228
0
    std::vector<GDALArgDatasetValue> values;
9229
0
    for (size_t i = 0; names[i]; ++i)
9230
0
    {
9231
0
        values.emplace_back(names[i]);
9232
0
    }
9233
0
    return hArg->ptr->Set(std::move(values));
9234
0
}
9235
9236
/************************************************************************/
9237
/*                     GDALArgDatasetValueCreate()                      */
9238
/************************************************************************/
9239
9240
/** Instantiate an empty GDALArgDatasetValue
9241
 *
9242
 * @return new handle to free with GDALArgDatasetValueRelease()
9243
 * @since 3.11
9244
 */
9245
GDALArgDatasetValueH GDALArgDatasetValueCreate()
9246
0
{
9247
0
    return std::make_unique<GDALArgDatasetValueHS>().release();
9248
0
}
9249
9250
/************************************************************************/
9251
/*                     GDALArgDatasetValueRelease()                     */
9252
/************************************************************************/
9253
9254
/** Release a handle to a GDALArgDatasetValue
9255
 *
9256
 * @since 3.11
9257
 */
9258
void GDALArgDatasetValueRelease(GDALArgDatasetValueH hValue)
9259
0
{
9260
0
    delete hValue;
9261
0
}
9262
9263
/************************************************************************/
9264
/*                     GDALArgDatasetValueGetName()                     */
9265
/************************************************************************/
9266
9267
/** Return the name component of the GDALArgDatasetValue
9268
 *
9269
 * @param hValue Handle to a GDALArgDatasetValue. Must NOT be null.
9270
 * @return string whose lifetime is bound to hAlg and which must not
9271
 * be freed.
9272
 * @since 3.11
9273
 */
9274
const char *GDALArgDatasetValueGetName(GDALArgDatasetValueH hValue)
9275
0
{
9276
0
    VALIDATE_POINTER1(hValue, __func__, nullptr);
9277
0
    return hValue->ptr->GetName().c_str();
9278
0
}
9279
9280
/************************************************************************/
9281
/*                  GDALArgDatasetValueGetDatasetRef()                  */
9282
/************************************************************************/
9283
9284
/** Return the dataset component of the GDALArgDatasetValue.
9285
 *
9286
 * This does not modify the reference counter, hence the lifetime of the
9287
 * returned object is not guaranteed to exceed the one of hValue.
9288
 *
9289
 * @param hValue Handle to a GDALArgDatasetValue. Must NOT be null.
9290
 * @since 3.11
9291
 */
9292
GDALDatasetH GDALArgDatasetValueGetDatasetRef(GDALArgDatasetValueH hValue)
9293
0
{
9294
0
    VALIDATE_POINTER1(hValue, __func__, nullptr);
9295
0
    return GDALDataset::ToHandle(hValue->ptr->GetDatasetRef());
9296
0
}
9297
9298
/************************************************************************/
9299
/*           GDALArgDatasetValueGetDatasetIncreaseRefCount()            */
9300
/************************************************************************/
9301
9302
/** Return the dataset component of the GDALArgDatasetValue, and increase its
9303
 * reference count if not null. Once done with the dataset, the caller should
9304
 * call GDALReleaseDataset().
9305
 *
9306
 * @param hValue Handle to a GDALArgDatasetValue. Must NOT be null.
9307
 * @since 3.11
9308
 */
9309
GDALDatasetH
9310
GDALArgDatasetValueGetDatasetIncreaseRefCount(GDALArgDatasetValueH hValue)
9311
0
{
9312
0
    VALIDATE_POINTER1(hValue, __func__, nullptr);
9313
0
    return GDALDataset::ToHandle(hValue->ptr->GetDatasetIncreaseRefCount());
9314
0
}
9315
9316
/************************************************************************/
9317
/*                     GDALArgDatasetValueSetName()                     */
9318
/************************************************************************/
9319
9320
/** Set dataset name
9321
 *
9322
 * @param hValue Handle to a GDALArgDatasetValue. Must NOT be null.
9323
 * @param pszName Dataset name. May be null.
9324
 * @since 3.11
9325
 */
9326
9327
void GDALArgDatasetValueSetName(GDALArgDatasetValueH hValue,
9328
                                const char *pszName)
9329
0
{
9330
0
    VALIDATE_POINTER0(hValue, __func__);
9331
0
    hValue->ptr->Set(pszName ? pszName : "");
9332
0
}
9333
9334
/************************************************************************/
9335
/*                   GDALArgDatasetValueSetDataset()                    */
9336
/************************************************************************/
9337
9338
/** Set dataset object, increasing its reference counter.
9339
 *
9340
 * @param hValue Handle to a GDALArgDatasetValue. Must NOT be null.
9341
 * @param hDS Dataset object. May be null.
9342
 * @since 3.11
9343
 */
9344
9345
void GDALArgDatasetValueSetDataset(GDALArgDatasetValueH hValue,
9346
                                   GDALDatasetH hDS)
9347
0
{
9348
0
    VALIDATE_POINTER0(hValue, __func__);
9349
0
    hValue->ptr->Set(GDALDataset::FromHandle(hDS));
9350
0
}