Coverage Report

Created: 2026-02-14 06:52

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_error.h"
16
#include "cpl_json.h"
17
#include "cpl_levenshtein.h"
18
#include "cpl_minixml.h"
19
#include "cpl_multiproc.h"
20
21
#include "gdalalgorithm.h"
22
#include "gdalalg_abstract_pipeline.h"
23
#include "gdal_priv.h"
24
#include "gdal_thread_pool.h"
25
#include "ogrsf_frmts.h"
26
#include "ogr_spatialref.h"
27
#include "vrtdataset.h"
28
29
#include <algorithm>
30
#include <cassert>
31
#include <cerrno>
32
#include <cmath>
33
#include <cstdlib>
34
#include <limits>
35
#include <map>
36
#include <string_view>
37
38
#ifndef _
39
0
#define _(x) (x)
40
#endif
41
42
constexpr const char *GDAL_ARG_NAME_OUTPUT_DATA_TYPE = "output-data-type";
43
44
constexpr const char *GDAL_ARG_NAME_OUTPUT_OPEN_OPTION = "output-open-option";
45
46
constexpr const char *GDAL_ARG_NAME_BAND = "band";
47
48
//! @cond Doxygen_Suppress
49
struct GDALAlgorithmArgHS
50
{
51
    GDALAlgorithmArg *ptr = nullptr;
52
53
0
    explicit GDALAlgorithmArgHS(GDALAlgorithmArg *arg) : ptr(arg)
54
0
    {
55
0
    }
56
};
57
58
//! @endcond
59
60
//! @cond Doxygen_Suppress
61
struct GDALArgDatasetValueHS
62
{
63
    GDALArgDatasetValue val{};
64
    GDALArgDatasetValue *ptr = nullptr;
65
66
0
    GDALArgDatasetValueHS() : ptr(&val)
67
0
    {
68
0
    }
69
70
0
    explicit GDALArgDatasetValueHS(GDALArgDatasetValue *arg) : ptr(arg)
71
0
    {
72
0
    }
73
74
    GDALArgDatasetValueHS(const GDALArgDatasetValueHS &) = delete;
75
    GDALArgDatasetValueHS &operator=(const GDALArgDatasetValueHS &) = delete;
76
};
77
78
//! @endcond
79
80
/************************************************************************/
81
/*                     GDALAlgorithmArgTypeIsList()                     */
82
/************************************************************************/
83
84
bool GDALAlgorithmArgTypeIsList(GDALAlgorithmArgType type)
85
0
{
86
0
    switch (type)
87
0
    {
88
0
        case GAAT_BOOLEAN:
89
0
        case GAAT_STRING:
90
0
        case GAAT_INTEGER:
91
0
        case GAAT_REAL:
92
0
        case GAAT_DATASET:
93
0
            break;
94
95
0
        case GAAT_STRING_LIST:
96
0
        case GAAT_INTEGER_LIST:
97
0
        case GAAT_REAL_LIST:
98
0
        case GAAT_DATASET_LIST:
99
0
            return true;
100
0
    }
101
102
0
    return false;
103
0
}
104
105
/************************************************************************/
106
/*                      GDALAlgorithmArgTypeName()                      */
107
/************************************************************************/
108
109
const char *GDALAlgorithmArgTypeName(GDALAlgorithmArgType type)
110
0
{
111
0
    switch (type)
112
0
    {
113
0
        case GAAT_BOOLEAN:
114
0
            break;
115
0
        case GAAT_STRING:
116
0
            return "string";
117
0
        case GAAT_INTEGER:
118
0
            return "integer";
119
0
        case GAAT_REAL:
120
0
            return "real";
121
0
        case GAAT_DATASET:
122
0
            return "dataset";
123
0
        case GAAT_STRING_LIST:
124
0
            return "string_list";
125
0
        case GAAT_INTEGER_LIST:
126
0
            return "integer_list";
127
0
        case GAAT_REAL_LIST:
128
0
            return "real_list";
129
0
        case GAAT_DATASET_LIST:
130
0
            return "dataset_list";
131
0
    }
132
133
0
    return "boolean";
134
0
}
135
136
/************************************************************************/
137
/*                  GDALAlgorithmArgDatasetTypeName()                   */
138
/************************************************************************/
139
140
std::string GDALAlgorithmArgDatasetTypeName(GDALArgDatasetType type)
141
0
{
142
0
    std::string ret;
143
0
    if ((type & GDAL_OF_RASTER) != 0)
144
0
        ret = "raster";
145
0
    if ((type & GDAL_OF_VECTOR) != 0)
146
0
    {
147
0
        if (!ret.empty())
148
0
        {
149
0
            if ((type & GDAL_OF_MULTIDIM_RASTER) != 0)
150
0
                ret += ", ";
151
0
            else
152
0
                ret += " or ";
153
0
        }
154
0
        ret += "vector";
155
0
    }
156
0
    if ((type & GDAL_OF_MULTIDIM_RASTER) != 0)
157
0
    {
158
0
        if (!ret.empty())
159
0
        {
160
0
            ret += " or ";
161
0
        }
162
0
        ret += "multidimensional raster";
163
0
    }
164
0
    return ret;
165
0
}
166
167
/************************************************************************/
168
/*                        GDALAlgorithmArgDecl()                        */
169
/************************************************************************/
170
171
// cppcheck-suppress uninitMemberVar
172
GDALAlgorithmArgDecl::GDALAlgorithmArgDecl(const std::string &longName,
173
                                           char chShortName,
174
                                           const std::string &description,
175
                                           GDALAlgorithmArgType type)
176
0
    : m_longName(longName),
177
0
      m_shortName(chShortName ? std::string(&chShortName, 1) : std::string()),
178
0
      m_description(description), m_type(type),
179
0
      m_metaVar(CPLString(m_type == GAAT_BOOLEAN ? std::string() : longName)
180
0
                    .toupper()),
181
0
      m_maxCount(GDALAlgorithmArgTypeIsList(type) ? UNBOUNDED : 1)
182
0
{
183
0
    if (m_type == GAAT_BOOLEAN)
184
0
    {
185
0
        m_defaultValue = false;
186
0
    }
187
0
}
188
189
/************************************************************************/
190
/*                 GDALAlgorithmArgDecl::SetMinCount()                  */
191
/************************************************************************/
192
193
GDALAlgorithmArgDecl &GDALAlgorithmArgDecl::SetMinCount(int count)
194
0
{
195
0
    if (!GDALAlgorithmArgTypeIsList(m_type))
196
0
    {
197
0
        CPLError(CE_Failure, CPLE_NotSupported,
198
0
                 "SetMinCount() illegal on scalar argument '%s'",
199
0
                 GetName().c_str());
200
0
    }
201
0
    else
202
0
    {
203
0
        m_minCount = count;
204
0
    }
205
0
    return *this;
206
0
}
207
208
/************************************************************************/
209
/*                 GDALAlgorithmArgDecl::SetMaxCount()                  */
210
/************************************************************************/
211
212
GDALAlgorithmArgDecl &GDALAlgorithmArgDecl::SetMaxCount(int count)
213
0
{
214
0
    if (!GDALAlgorithmArgTypeIsList(m_type))
215
0
    {
216
0
        CPLError(CE_Failure, CPLE_NotSupported,
217
0
                 "SetMaxCount() illegal on scalar argument '%s'",
218
0
                 GetName().c_str());
219
0
    }
220
0
    else
221
0
    {
222
0
        m_maxCount = count;
223
0
    }
224
0
    return *this;
225
0
}
226
227
/************************************************************************/
228
/*                GDALAlgorithmArg::~GDALAlgorithmArg()                 */
229
/************************************************************************/
230
231
0
GDALAlgorithmArg::~GDALAlgorithmArg() = default;
232
233
/************************************************************************/
234
/*                       GDALAlgorithmArg::Set()                        */
235
/************************************************************************/
236
237
bool GDALAlgorithmArg::Set(bool value)
238
0
{
239
0
    if (m_decl.GetType() != GAAT_BOOLEAN)
240
0
    {
241
0
        CPLError(
242
0
            CE_Failure, CPLE_AppDefined,
243
0
            "Calling Set(bool) on argument '%s' of type %s is not supported",
244
0
            GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
245
0
        return false;
246
0
    }
247
0
    return SetInternal(value);
248
0
}
249
250
bool GDALAlgorithmArg::ProcessString(std::string &value) const
251
0
{
252
0
    if (m_decl.IsReadFromFileAtSyntaxAllowed() && !value.empty() &&
253
0
        value.front() == '@')
254
0
    {
255
0
        GByte *pabyData = nullptr;
256
0
        if (VSIIngestFile(nullptr, value.c_str() + 1, &pabyData, nullptr,
257
0
                          10 * 1024 * 1024))
258
0
        {
259
            // Remove UTF-8 BOM
260
0
            size_t offset = 0;
261
0
            if (pabyData[0] == 0xEF && pabyData[1] == 0xBB &&
262
0
                pabyData[2] == 0xBF)
263
0
            {
264
0
                offset = 3;
265
0
            }
266
0
            value = reinterpret_cast<const char *>(pabyData + offset);
267
0
            VSIFree(pabyData);
268
0
        }
269
0
        else
270
0
        {
271
0
            return false;
272
0
        }
273
0
    }
274
275
0
    if (m_decl.IsRemoveSQLCommentsEnabled())
276
0
        value = CPLRemoveSQLComments(value);
277
278
0
    return true;
279
0
}
280
281
bool GDALAlgorithmArg::Set(const std::string &value)
282
0
{
283
0
    switch (m_decl.GetType())
284
0
    {
285
0
        case GAAT_BOOLEAN:
286
0
            if (EQUAL(value.c_str(), "1") || EQUAL(value.c_str(), "TRUE") ||
287
0
                EQUAL(value.c_str(), "YES") || EQUAL(value.c_str(), "ON"))
288
0
            {
289
0
                return Set(true);
290
0
            }
291
0
            else if (EQUAL(value.c_str(), "0") ||
292
0
                     EQUAL(value.c_str(), "FALSE") ||
293
0
                     EQUAL(value.c_str(), "NO") || EQUAL(value.c_str(), "OFF"))
294
0
            {
295
0
                return Set(false);
296
0
            }
297
0
            break;
298
299
0
        case GAAT_INTEGER:
300
0
        case GAAT_INTEGER_LIST:
301
0
        {
302
0
            errno = 0;
303
0
            char *endptr = nullptr;
304
0
            const auto v = std::strtoll(value.c_str(), &endptr, 10);
305
0
            if (errno == 0 && v >= INT_MIN && v <= INT_MAX &&
306
0
                endptr == value.c_str() + value.size())
307
0
            {
308
0
                if (m_decl.GetType() == GAAT_INTEGER)
309
0
                    return Set(static_cast<int>(v));
310
0
                else
311
0
                    return Set(std::vector<int>{static_cast<int>(v)});
312
0
            }
313
0
            break;
314
0
        }
315
316
0
        case GAAT_REAL:
317
0
        case GAAT_REAL_LIST:
318
0
        {
319
0
            char *endptr = nullptr;
320
0
            const double v = CPLStrtod(value.c_str(), &endptr);
321
0
            if (endptr == value.c_str() + value.size())
322
0
            {
323
0
                if (m_decl.GetType() == GAAT_REAL)
324
0
                    return Set(v);
325
0
                else
326
0
                    return Set(std::vector<double>{v});
327
0
            }
328
0
            break;
329
0
        }
330
331
0
        case GAAT_STRING:
332
0
            break;
333
334
0
        case GAAT_STRING_LIST:
335
0
            return Set(std::vector<std::string>{value});
336
337
0
        case GAAT_DATASET:
338
0
            return SetDatasetName(value);
339
340
0
        case GAAT_DATASET_LIST:
341
0
        {
342
0
            std::vector<GDALArgDatasetValue> v;
343
0
            v.resize(1);
344
0
            v[0].Set(value);
345
0
            return Set(std::move(v));
346
0
        }
347
0
    }
348
349
0
    if (m_decl.GetType() != GAAT_STRING)
350
0
    {
351
0
        CPLError(CE_Failure, CPLE_AppDefined,
352
0
                 "Calling Set(std::string) on argument '%s' of type %s is not "
353
0
                 "supported",
354
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
355
0
        return false;
356
0
    }
357
358
0
    std::string newValue(value);
359
0
    return ProcessString(newValue) && SetInternal(newValue);
360
0
}
361
362
bool GDALAlgorithmArg::Set(int value)
363
0
{
364
0
    if (m_decl.GetType() == GAAT_BOOLEAN)
365
0
    {
366
0
        if (value == 1)
367
0
            return Set(true);
368
0
        else if (value == 0)
369
0
            return Set(false);
370
0
    }
371
0
    else if (m_decl.GetType() == GAAT_REAL)
372
0
    {
373
0
        return Set(static_cast<double>(value));
374
0
    }
375
0
    else if (m_decl.GetType() == GAAT_STRING)
376
0
    {
377
0
        return Set(std::to_string(value));
378
0
    }
379
0
    else if (m_decl.GetType() == GAAT_INTEGER_LIST)
380
0
    {
381
0
        return Set(std::vector<int>{value});
382
0
    }
383
0
    else if (m_decl.GetType() == GAAT_REAL_LIST)
384
0
    {
385
0
        return Set(std::vector<double>{static_cast<double>(value)});
386
0
    }
387
0
    else if (m_decl.GetType() == GAAT_STRING_LIST)
388
0
    {
389
0
        return Set(std::vector<std::string>{std::to_string(value)});
390
0
    }
391
392
0
    if (m_decl.GetType() != GAAT_INTEGER)
393
0
    {
394
0
        CPLError(
395
0
            CE_Failure, CPLE_AppDefined,
396
0
            "Calling Set(int) on argument '%s' of type %s is not supported",
397
0
            GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
398
0
        return false;
399
0
    }
400
0
    return SetInternal(value);
401
0
}
402
403
bool GDALAlgorithmArg::Set(double value)
404
0
{
405
0
    if (m_decl.GetType() == GAAT_INTEGER && value >= INT_MIN &&
406
0
        value <= INT_MAX && static_cast<int>(value) == value)
407
0
    {
408
0
        return Set(static_cast<int>(value));
409
0
    }
410
0
    else if (m_decl.GetType() == GAAT_STRING)
411
0
    {
412
0
        return Set(std::to_string(value));
413
0
    }
414
0
    else if (m_decl.GetType() == GAAT_INTEGER_LIST && value >= INT_MIN &&
415
0
             value <= INT_MAX && static_cast<int>(value) == value)
416
0
    {
417
0
        return Set(std::vector<int>{static_cast<int>(value)});
418
0
    }
419
0
    else if (m_decl.GetType() == GAAT_REAL_LIST)
420
0
    {
421
0
        return Set(std::vector<double>{value});
422
0
    }
423
0
    else if (m_decl.GetType() == GAAT_STRING_LIST)
424
0
    {
425
0
        return Set(std::vector<std::string>{std::to_string(value)});
426
0
    }
427
0
    else if (m_decl.GetType() != GAAT_REAL)
428
0
    {
429
0
        CPLError(
430
0
            CE_Failure, CPLE_AppDefined,
431
0
            "Calling Set(double) on argument '%s' of type %s is not supported",
432
0
            GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
433
0
        return false;
434
0
    }
435
0
    return SetInternal(value);
436
0
}
437
438
static bool CheckCanSetDatasetObject(const GDALAlgorithmArg *arg)
439
0
{
440
0
    if (arg->GetDatasetInputFlags() == GADV_NAME &&
441
0
        arg->GetDatasetOutputFlags() == GADV_OBJECT)
442
0
    {
443
0
        CPLError(
444
0
            CE_Failure, CPLE_AppDefined,
445
0
            "Dataset object '%s' is created by algorithm and cannot be set "
446
0
            "as an input.",
447
0
            arg->GetName().c_str());
448
0
        return false;
449
0
    }
450
0
    else if ((arg->GetDatasetInputFlags() & GADV_OBJECT) == 0)
451
0
    {
452
0
        CPLError(CE_Failure, CPLE_AppDefined,
453
0
                 "A dataset cannot be set as an input argument of '%s'.",
454
0
                 arg->GetName().c_str());
455
0
        return false;
456
0
    }
457
458
0
    return true;
459
0
}
460
461
bool GDALAlgorithmArg::Set(GDALDataset *ds)
462
0
{
463
0
    if (m_decl.GetType() != GAAT_DATASET)
464
0
    {
465
0
        CPLError(CE_Failure, CPLE_AppDefined,
466
0
                 "Calling Set(GDALDataset*, bool) on argument '%s' of type %s "
467
0
                 "is not supported",
468
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
469
0
        return false;
470
0
    }
471
0
    if (!CheckCanSetDatasetObject(this))
472
0
        return false;
473
0
    m_explicitlySet = true;
474
0
    auto &val = *std::get<GDALArgDatasetValue *>(m_value);
475
0
    val.Set(ds);
476
0
    return RunAllActions();
477
0
}
478
479
bool GDALAlgorithmArg::Set(std::unique_ptr<GDALDataset> ds)
480
0
{
481
0
    if (m_decl.GetType() != GAAT_DATASET)
482
0
    {
483
0
        CPLError(CE_Failure, CPLE_AppDefined,
484
0
                 "Calling Set(GDALDataset*, bool) on argument '%s' of type %s "
485
0
                 "is not supported",
486
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
487
0
        return false;
488
0
    }
489
0
    if (!CheckCanSetDatasetObject(this))
490
0
        return false;
491
0
    m_explicitlySet = true;
492
0
    auto &val = *std::get<GDALArgDatasetValue *>(m_value);
493
0
    val.Set(std::move(ds));
494
0
    return RunAllActions();
495
0
}
496
497
bool GDALAlgorithmArg::SetDatasetName(const std::string &name)
498
0
{
499
0
    if (m_decl.GetType() != GAAT_DATASET)
500
0
    {
501
0
        CPLError(CE_Failure, CPLE_AppDefined,
502
0
                 "Calling SetDatasetName() on argument '%s' of type %s is "
503
0
                 "not supported",
504
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
505
0
        return false;
506
0
    }
507
0
    m_explicitlySet = true;
508
0
    std::get<GDALArgDatasetValue *>(m_value)->Set(name);
509
0
    return RunAllActions();
510
0
}
511
512
bool GDALAlgorithmArg::SetFrom(const GDALArgDatasetValue &other)
513
0
{
514
0
    if (m_decl.GetType() != GAAT_DATASET)
515
0
    {
516
0
        CPLError(CE_Failure, CPLE_AppDefined,
517
0
                 "Calling SetFrom() on argument '%s' of type %s is "
518
0
                 "not supported",
519
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
520
0
        return false;
521
0
    }
522
0
    if (!CheckCanSetDatasetObject(this))
523
0
        return false;
524
0
    m_explicitlySet = true;
525
0
    std::get<GDALArgDatasetValue *>(m_value)->SetFrom(other);
526
0
    return RunAllActions();
527
0
}
528
529
bool GDALAlgorithmArg::Set(const std::vector<std::string> &value)
530
0
{
531
0
    if (m_decl.GetType() == GAAT_INTEGER_LIST)
532
0
    {
533
0
        std::vector<int> v_i;
534
0
        for (const std::string &s : value)
535
0
        {
536
0
            errno = 0;
537
0
            char *endptr = nullptr;
538
0
            const auto v = std::strtoll(s.c_str(), &endptr, 10);
539
0
            if (errno == 0 && v >= INT_MIN && v <= INT_MAX &&
540
0
                endptr == s.c_str() + s.size())
541
0
            {
542
0
                v_i.push_back(static_cast<int>(v));
543
0
            }
544
0
            else
545
0
            {
546
0
                break;
547
0
            }
548
0
        }
549
0
        if (v_i.size() == value.size())
550
0
            return Set(v_i);
551
0
    }
552
0
    else if (m_decl.GetType() == GAAT_REAL_LIST)
553
0
    {
554
0
        std::vector<double> v_d;
555
0
        for (const std::string &s : value)
556
0
        {
557
0
            char *endptr = nullptr;
558
0
            const double v = CPLStrtod(s.c_str(), &endptr);
559
0
            if (endptr == s.c_str() + s.size())
560
0
            {
561
0
                v_d.push_back(v);
562
0
            }
563
0
            else
564
0
            {
565
0
                break;
566
0
            }
567
0
        }
568
0
        if (v_d.size() == value.size())
569
0
            return Set(v_d);
570
0
    }
571
0
    else if ((m_decl.GetType() == GAAT_INTEGER ||
572
0
              m_decl.GetType() == GAAT_REAL ||
573
0
              m_decl.GetType() == GAAT_STRING) &&
574
0
             value.size() == 1)
575
0
    {
576
0
        return Set(value[0]);
577
0
    }
578
0
    else if (m_decl.GetType() == GAAT_DATASET_LIST)
579
0
    {
580
0
        std::vector<GDALArgDatasetValue> dsVector;
581
0
        for (const std::string &s : value)
582
0
            dsVector.emplace_back(s);
583
0
        return Set(std::move(dsVector));
584
0
    }
585
586
0
    if (m_decl.GetType() != GAAT_STRING_LIST)
587
0
    {
588
0
        CPLError(CE_Failure, CPLE_AppDefined,
589
0
                 "Calling Set(const std::vector<std::string> &) on argument "
590
0
                 "'%s' of type %s is not supported",
591
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
592
0
        return false;
593
0
    }
594
595
0
    if (m_decl.IsReadFromFileAtSyntaxAllowed() ||
596
0
        m_decl.IsRemoveSQLCommentsEnabled())
597
0
    {
598
0
        std::vector<std::string> newValue(value);
599
0
        for (auto &s : newValue)
600
0
        {
601
0
            if (!ProcessString(s))
602
0
                return false;
603
0
        }
604
0
        return SetInternal(newValue);
605
0
    }
606
0
    else
607
0
    {
608
0
        return SetInternal(value);
609
0
    }
610
0
}
611
612
bool GDALAlgorithmArg::Set(const std::vector<int> &value)
613
0
{
614
0
    if (m_decl.GetType() == GAAT_REAL_LIST)
615
0
    {
616
0
        std::vector<double> v_d;
617
0
        for (int i : value)
618
0
            v_d.push_back(i);
619
0
        return Set(v_d);
620
0
    }
621
0
    else if (m_decl.GetType() == GAAT_STRING_LIST)
622
0
    {
623
0
        std::vector<std::string> v_s;
624
0
        for (int i : value)
625
0
            v_s.push_back(std::to_string(i));
626
0
        return Set(v_s);
627
0
    }
628
0
    else if ((m_decl.GetType() == GAAT_INTEGER ||
629
0
              m_decl.GetType() == GAAT_REAL ||
630
0
              m_decl.GetType() == GAAT_STRING) &&
631
0
             value.size() == 1)
632
0
    {
633
0
        return Set(value[0]);
634
0
    }
635
636
0
    if (m_decl.GetType() != GAAT_INTEGER_LIST)
637
0
    {
638
0
        CPLError(CE_Failure, CPLE_AppDefined,
639
0
                 "Calling Set(const std::vector<int> &) on argument '%s' of "
640
0
                 "type %s is not supported",
641
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
642
0
        return false;
643
0
    }
644
0
    return SetInternal(value);
645
0
}
646
647
bool GDALAlgorithmArg::Set(const std::vector<double> &value)
648
0
{
649
0
    if (m_decl.GetType() == GAAT_INTEGER_LIST)
650
0
    {
651
0
        std::vector<int> v_i;
652
0
        for (double d : value)
653
0
        {
654
0
            if (d >= INT_MIN && d <= INT_MAX && static_cast<int>(d) == d)
655
0
            {
656
0
                v_i.push_back(static_cast<int>(d));
657
0
            }
658
0
            else
659
0
            {
660
0
                break;
661
0
            }
662
0
        }
663
0
        if (v_i.size() == value.size())
664
0
            return Set(v_i);
665
0
    }
666
0
    else if (m_decl.GetType() == GAAT_STRING_LIST)
667
0
    {
668
0
        std::vector<std::string> v_s;
669
0
        for (double d : value)
670
0
            v_s.push_back(std::to_string(d));
671
0
        return Set(v_s);
672
0
    }
673
0
    else if ((m_decl.GetType() == GAAT_INTEGER ||
674
0
              m_decl.GetType() == GAAT_REAL ||
675
0
              m_decl.GetType() == GAAT_STRING) &&
676
0
             value.size() == 1)
677
0
    {
678
0
        return Set(value[0]);
679
0
    }
680
681
0
    if (m_decl.GetType() != GAAT_REAL_LIST)
682
0
    {
683
0
        CPLError(CE_Failure, CPLE_AppDefined,
684
0
                 "Calling Set(const std::vector<double> &) on argument '%s' of "
685
0
                 "type %s is not supported",
686
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
687
0
        return false;
688
0
    }
689
0
    return SetInternal(value);
690
0
}
691
692
bool GDALAlgorithmArg::Set(std::vector<GDALArgDatasetValue> &&value)
693
0
{
694
0
    if (m_decl.GetType() != GAAT_DATASET_LIST)
695
0
    {
696
0
        CPLError(CE_Failure, CPLE_AppDefined,
697
0
                 "Calling Set(const std::vector<GDALArgDatasetValue> &&) on "
698
0
                 "argument '%s' of type %s is not supported",
699
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()));
700
0
        return false;
701
0
    }
702
0
    m_explicitlySet = true;
703
0
    *std::get<std::vector<GDALArgDatasetValue> *>(m_value) = std::move(value);
704
0
    return RunAllActions();
705
0
}
706
707
GDALAlgorithmArg &
708
GDALAlgorithmArg::operator=(std::unique_ptr<GDALDataset> value)
709
0
{
710
0
    Set(std::move(value));
711
0
    return *this;
712
0
}
713
714
bool GDALAlgorithmArg::Set(const OGRSpatialReference &value)
715
0
{
716
0
    const char *const apszOptions[] = {"FORMAT=WKT2_2019", nullptr};
717
0
    return Set(value.exportToWkt(apszOptions));
718
0
}
719
720
bool GDALAlgorithmArg::SetFrom(const GDALAlgorithmArg &other)
721
0
{
722
0
    if (m_decl.GetType() != other.GetType())
723
0
    {
724
0
        CPLError(CE_Failure, CPLE_AppDefined,
725
0
                 "Calling SetFrom() on argument '%s' of type %s whereas "
726
0
                 "other argument type is %s is not supported",
727
0
                 GetName().c_str(), GDALAlgorithmArgTypeName(m_decl.GetType()),
728
0
                 GDALAlgorithmArgTypeName(other.GetType()));
729
0
        return false;
730
0
    }
731
732
0
    switch (m_decl.GetType())
733
0
    {
734
0
        case GAAT_BOOLEAN:
735
0
            *std::get<bool *>(m_value) = *std::get<bool *>(other.m_value);
736
0
            break;
737
0
        case GAAT_STRING:
738
0
            *std::get<std::string *>(m_value) =
739
0
                *std::get<std::string *>(other.m_value);
740
0
            break;
741
0
        case GAAT_INTEGER:
742
0
            *std::get<int *>(m_value) = *std::get<int *>(other.m_value);
743
0
            break;
744
0
        case GAAT_REAL:
745
0
            *std::get<double *>(m_value) = *std::get<double *>(other.m_value);
746
0
            break;
747
0
        case GAAT_DATASET:
748
0
            return SetFrom(other.Get<GDALArgDatasetValue>());
749
0
        case GAAT_STRING_LIST:
750
0
            *std::get<std::vector<std::string> *>(m_value) =
751
0
                *std::get<std::vector<std::string> *>(other.m_value);
752
0
            break;
753
0
        case GAAT_INTEGER_LIST:
754
0
            *std::get<std::vector<int> *>(m_value) =
755
0
                *std::get<std::vector<int> *>(other.m_value);
756
0
            break;
757
0
        case GAAT_REAL_LIST:
758
0
            *std::get<std::vector<double> *>(m_value) =
759
0
                *std::get<std::vector<double> *>(other.m_value);
760
0
            break;
761
0
        case GAAT_DATASET_LIST:
762
0
        {
763
0
            std::get<std::vector<GDALArgDatasetValue> *>(m_value)->clear();
764
0
            for (const auto &val :
765
0
                 *std::get<std::vector<GDALArgDatasetValue> *>(other.m_value))
766
0
            {
767
0
                GDALArgDatasetValue v;
768
0
                v.SetFrom(val);
769
0
                std::get<std::vector<GDALArgDatasetValue> *>(m_value)
770
0
                    ->push_back(std::move(v));
771
0
            }
772
0
            break;
773
0
        }
774
0
    }
775
0
    m_explicitlySet = true;
776
0
    return RunAllActions();
777
0
}
778
779
/************************************************************************/
780
/*                  GDALAlgorithmArg::RunAllActions()                   */
781
/************************************************************************/
782
783
bool GDALAlgorithmArg::RunAllActions()
784
0
{
785
0
    if (!RunValidationActions())
786
0
        return false;
787
0
    RunActions();
788
0
    return true;
789
0
}
790
791
/************************************************************************/
792
/*                    GDALAlgorithmArg::RunActions()                    */
793
/************************************************************************/
794
795
void GDALAlgorithmArg::RunActions()
796
0
{
797
0
    for (const auto &f : m_actions)
798
0
        f();
799
0
}
800
801
/************************************************************************/
802
/*                  GDALAlgorithmArg::ValidateChoice()                  */
803
/************************************************************************/
804
805
// Returns the canonical value if matching a valid choice, or empty string
806
// otherwise.
807
std::string GDALAlgorithmArg::ValidateChoice(const std::string &value) const
808
0
{
809
0
    for (const std::string &choice : GetChoices())
810
0
    {
811
0
        if (EQUAL(value.c_str(), choice.c_str()))
812
0
        {
813
0
            return choice;
814
0
        }
815
0
    }
816
817
0
    for (const std::string &choice : GetHiddenChoices())
818
0
    {
819
0
        if (EQUAL(value.c_str(), choice.c_str()))
820
0
        {
821
0
            return choice;
822
0
        }
823
0
    }
824
825
0
    std::string expected;
826
0
    for (const auto &choice : GetChoices())
827
0
    {
828
0
        if (!expected.empty())
829
0
            expected += ", ";
830
0
        expected += '\'';
831
0
        expected += choice;
832
0
        expected += '\'';
833
0
    }
834
0
    if (m_owner && m_owner->IsCalledFromCommandLine() && value == "?")
835
0
    {
836
0
        return "?";
837
0
    }
838
0
    CPLError(CE_Failure, CPLE_IllegalArg,
839
0
             "Invalid value '%s' for string argument '%s'. Should be "
840
0
             "one among %s.",
841
0
             value.c_str(), GetName().c_str(), expected.c_str());
842
0
    return std::string();
843
0
}
844
845
/************************************************************************/
846
/*                 GDALAlgorithmArg::ValidateIntRange()                 */
847
/************************************************************************/
848
849
bool GDALAlgorithmArg::ValidateIntRange(int val) const
850
0
{
851
0
    bool ret = true;
852
853
0
    const auto [minVal, minValIsIncluded] = GetMinValue();
854
0
    if (!std::isnan(minVal))
855
0
    {
856
0
        if (minValIsIncluded && val < minVal)
857
0
        {
858
0
            CPLError(CE_Failure, CPLE_IllegalArg,
859
0
                     "Value of argument '%s' is %d, but should be >= %d",
860
0
                     GetName().c_str(), val, static_cast<int>(minVal));
861
0
            ret = false;
862
0
        }
863
0
        else if (!minValIsIncluded && val <= minVal)
864
0
        {
865
0
            CPLError(CE_Failure, CPLE_IllegalArg,
866
0
                     "Value of argument '%s' is %d, but should be > %d",
867
0
                     GetName().c_str(), val, static_cast<int>(minVal));
868
0
            ret = false;
869
0
        }
870
0
    }
871
872
0
    const auto [maxVal, maxValIsIncluded] = GetMaxValue();
873
0
    if (!std::isnan(maxVal))
874
0
    {
875
876
0
        if (maxValIsIncluded && val > maxVal)
877
0
        {
878
0
            CPLError(CE_Failure, CPLE_IllegalArg,
879
0
                     "Value of argument '%s' is %d, but should be <= %d",
880
0
                     GetName().c_str(), val, static_cast<int>(maxVal));
881
0
            ret = false;
882
0
        }
883
0
        else if (!maxValIsIncluded && val >= maxVal)
884
0
        {
885
0
            CPLError(CE_Failure, CPLE_IllegalArg,
886
0
                     "Value of argument '%s' is %d, but should be < %d",
887
0
                     GetName().c_str(), val, static_cast<int>(maxVal));
888
0
            ret = false;
889
0
        }
890
0
    }
891
892
0
    return ret;
893
0
}
894
895
/************************************************************************/
896
/*                GDALAlgorithmArg::ValidateRealRange()                 */
897
/************************************************************************/
898
899
bool GDALAlgorithmArg::ValidateRealRange(double val) const
900
0
{
901
0
    bool ret = true;
902
903
0
    const auto [minVal, minValIsIncluded] = GetMinValue();
904
0
    if (!std::isnan(minVal))
905
0
    {
906
0
        if (minValIsIncluded && !(val >= minVal))
907
0
        {
908
0
            CPLError(CE_Failure, CPLE_IllegalArg,
909
0
                     "Value of argument '%s' is %g, but should be >= %g",
910
0
                     GetName().c_str(), val, minVal);
911
0
            ret = false;
912
0
        }
913
0
        else if (!minValIsIncluded && !(val > minVal))
914
0
        {
915
0
            CPLError(CE_Failure, CPLE_IllegalArg,
916
0
                     "Value of argument '%s' is %g, but should be > %g",
917
0
                     GetName().c_str(), val, minVal);
918
0
            ret = false;
919
0
        }
920
0
    }
921
922
0
    const auto [maxVal, maxValIsIncluded] = GetMaxValue();
923
0
    if (!std::isnan(maxVal))
924
0
    {
925
926
0
        if (maxValIsIncluded && !(val <= maxVal))
927
0
        {
928
0
            CPLError(CE_Failure, CPLE_IllegalArg,
929
0
                     "Value of argument '%s' is %g, but should be <= %g",
930
0
                     GetName().c_str(), val, maxVal);
931
0
            ret = false;
932
0
        }
933
0
        else if (!maxValIsIncluded && !(val < maxVal))
934
0
        {
935
0
            CPLError(CE_Failure, CPLE_IllegalArg,
936
0
                     "Value of argument '%s' is %g, but should be < %g",
937
0
                     GetName().c_str(), val, maxVal);
938
0
            ret = false;
939
0
        }
940
0
    }
941
942
0
    return ret;
943
0
}
944
945
/************************************************************************/
946
/*               GDALAlgorithmArg::RunValidationActions()               */
947
/************************************************************************/
948
949
bool GDALAlgorithmArg::RunValidationActions()
950
0
{
951
0
    bool ret = true;
952
953
0
    if (GetType() == GAAT_STRING && !GetChoices().empty())
954
0
    {
955
0
        auto &val = Get<std::string>();
956
0
        std::string validVal = ValidateChoice(val);
957
0
        if (validVal.empty())
958
0
            ret = false;
959
0
        else
960
0
            val = std::move(validVal);
961
0
    }
962
0
    else if (GetType() == GAAT_STRING_LIST && !GetChoices().empty())
963
0
    {
964
0
        auto &values = Get<std::vector<std::string>>();
965
0
        for (std::string &val : values)
966
0
        {
967
0
            std::string validVal = ValidateChoice(val);
968
0
            if (validVal.empty())
969
0
                ret = false;
970
0
            else
971
0
                val = std::move(validVal);
972
0
        }
973
0
    }
974
975
0
    if (GetType() == GAAT_STRING)
976
0
    {
977
0
        const int nMinCharCount = GetMinCharCount();
978
0
        if (nMinCharCount > 0)
979
0
        {
980
0
            const auto &val = Get<std::string>();
981
0
            if (val.size() < static_cast<size_t>(nMinCharCount))
982
0
            {
983
0
                CPLError(
984
0
                    CE_Failure, CPLE_IllegalArg,
985
0
                    "Value of argument '%s' is '%s', but should have at least "
986
0
                    "%d character(s)",
987
0
                    GetName().c_str(), val.c_str(), nMinCharCount);
988
0
                ret = false;
989
0
            }
990
0
        }
991
0
    }
992
0
    else if (GetType() == GAAT_STRING_LIST)
993
0
    {
994
0
        const int nMinCharCount = GetMinCharCount();
995
0
        if (nMinCharCount > 0)
996
0
        {
997
0
            for (const auto &val : Get<std::vector<std::string>>())
998
0
            {
999
0
                if (val.size() < static_cast<size_t>(nMinCharCount))
1000
0
                {
1001
0
                    CPLError(
1002
0
                        CE_Failure, CPLE_IllegalArg,
1003
0
                        "Value of argument '%s' is '%s', but should have at "
1004
0
                        "least %d character(s)",
1005
0
                        GetName().c_str(), val.c_str(), nMinCharCount);
1006
0
                    ret = false;
1007
0
                }
1008
0
            }
1009
0
        }
1010
0
    }
1011
0
    else if (GetType() == GAAT_INTEGER)
1012
0
    {
1013
0
        ret = ValidateIntRange(Get<int>()) && ret;
1014
0
    }
1015
0
    else if (GetType() == GAAT_INTEGER_LIST)
1016
0
    {
1017
0
        for (int v : Get<std::vector<int>>())
1018
0
            ret = ValidateIntRange(v) && ret;
1019
0
    }
1020
0
    else if (GetType() == GAAT_REAL)
1021
0
    {
1022
0
        ret = ValidateRealRange(Get<double>()) && ret;
1023
0
    }
1024
0
    else if (GetType() == GAAT_REAL_LIST)
1025
0
    {
1026
0
        for (double v : Get<std::vector<double>>())
1027
0
            ret = ValidateRealRange(v) && ret;
1028
0
    }
1029
1030
0
    if (GDALAlgorithmArgTypeIsList(GetType()))
1031
0
    {
1032
0
        int valueCount = 0;
1033
0
        if (GetType() == GAAT_STRING_LIST)
1034
0
        {
1035
0
            valueCount =
1036
0
                static_cast<int>(Get<std::vector<std::string>>().size());
1037
0
        }
1038
0
        else if (GetType() == GAAT_INTEGER_LIST)
1039
0
        {
1040
0
            valueCount = static_cast<int>(Get<std::vector<int>>().size());
1041
0
        }
1042
0
        else if (GetType() == GAAT_REAL_LIST)
1043
0
        {
1044
0
            valueCount = static_cast<int>(Get<std::vector<double>>().size());
1045
0
        }
1046
0
        else if (GetType() == GAAT_DATASET_LIST)
1047
0
        {
1048
0
            valueCount = static_cast<int>(
1049
0
                Get<std::vector<GDALArgDatasetValue>>().size());
1050
0
        }
1051
1052
0
        if (valueCount != GetMinCount() && GetMinCount() == GetMaxCount())
1053
0
        {
1054
0
            ReportError(CE_Failure, CPLE_AppDefined,
1055
0
                        "%d value%s been specified for argument '%s', "
1056
0
                        "whereas exactly %d %s expected.",
1057
0
                        valueCount, valueCount > 1 ? "s have" : " has",
1058
0
                        GetName().c_str(), GetMinCount(),
1059
0
                        GetMinCount() > 1 ? "were" : "was");
1060
0
            ret = false;
1061
0
        }
1062
0
        else if (valueCount < GetMinCount())
1063
0
        {
1064
0
            ReportError(CE_Failure, CPLE_AppDefined,
1065
0
                        "Only %d value%s been specified for argument '%s', "
1066
0
                        "whereas at least %d %s expected.",
1067
0
                        valueCount, valueCount > 1 ? "s have" : " has",
1068
0
                        GetName().c_str(), GetMinCount(),
1069
0
                        GetMinCount() > 1 ? "were" : "was");
1070
0
            ret = false;
1071
0
        }
1072
0
        else if (valueCount > GetMaxCount())
1073
0
        {
1074
0
            ReportError(CE_Failure, CPLE_AppDefined,
1075
0
                        "%d value%s been specified for argument '%s', "
1076
0
                        "whereas at most %d %s expected.",
1077
0
                        valueCount, valueCount > 1 ? "s have" : " has",
1078
0
                        GetName().c_str(), GetMaxCount(),
1079
0
                        GetMaxCount() > 1 ? "were" : "was");
1080
0
            ret = false;
1081
0
        }
1082
0
    }
1083
1084
0
    if (ret)
1085
0
    {
1086
0
        for (const auto &f : m_validationActions)
1087
0
        {
1088
0
            if (!f())
1089
0
                ret = false;
1090
0
        }
1091
0
    }
1092
1093
0
    return ret;
1094
0
}
1095
1096
/************************************************************************/
1097
/*                   GDALAlgorithmArg::ReportError()                    */
1098
/************************************************************************/
1099
1100
void GDALAlgorithmArg::ReportError(CPLErr eErrClass, CPLErrorNum err_no,
1101
                                   const char *fmt, ...) const
1102
0
{
1103
0
    va_list args;
1104
0
    va_start(args, fmt);
1105
0
    if (m_owner)
1106
0
    {
1107
0
        m_owner->ReportError(eErrClass, err_no, "%s",
1108
0
                             CPLString().vPrintf(fmt, args).c_str());
1109
0
    }
1110
0
    else
1111
0
    {
1112
0
        CPLError(eErrClass, err_no, "%s",
1113
0
                 CPLString().vPrintf(fmt, args).c_str());
1114
0
    }
1115
0
    va_end(args);
1116
0
}
1117
1118
/************************************************************************/
1119
/*                 GDALAlgorithmArg::GetEscapedString()                 */
1120
/************************************************************************/
1121
1122
/* static */
1123
std::string GDALAlgorithmArg::GetEscapedString(const std::string &s)
1124
0
{
1125
0
    if (s.find_first_of("\" \\,") != std::string::npos &&
1126
0
        !(s.size() > 4 &&
1127
0
          s[0] == GDALAbstractPipelineAlgorithm::OPEN_NESTED_PIPELINE[0] &&
1128
0
          s[1] == ' ' && s[s.size() - 2] == ' ' &&
1129
0
          s.back() == GDALAbstractPipelineAlgorithm::CLOSE_NESTED_PIPELINE[0]))
1130
0
    {
1131
0
        return std::string("\"")
1132
0
            .append(
1133
0
                CPLString(s).replaceAll('\\', "\\\\").replaceAll('"', "\\\""))
1134
0
            .append("\"");
1135
0
    }
1136
0
    else
1137
0
    {
1138
0
        return s;
1139
0
    }
1140
0
}
1141
1142
/************************************************************************/
1143
/*                    GDALAlgorithmArg::Serialize()                     */
1144
/************************************************************************/
1145
1146
bool GDALAlgorithmArg::Serialize(std::string &serializedArg,
1147
                                 bool absolutePath) const
1148
0
{
1149
0
    serializedArg.clear();
1150
1151
0
    if (!IsExplicitlySet())
1152
0
    {
1153
0
        return false;
1154
0
    }
1155
1156
0
    std::string ret = "--";
1157
0
    ret += GetName();
1158
0
    if (GetType() == GAAT_BOOLEAN)
1159
0
    {
1160
0
        serializedArg = std::move(ret);
1161
0
        return true;
1162
0
    }
1163
1164
0
    const auto AddListValueSeparator = [this, &ret]()
1165
0
    {
1166
0
        if (GetPackedValuesAllowed())
1167
0
        {
1168
0
            ret += ',';
1169
0
        }
1170
0
        else
1171
0
        {
1172
0
            ret += " --";
1173
0
            ret += GetName();
1174
0
            ret += ' ';
1175
0
        }
1176
0
    };
1177
1178
0
    const auto MakeAbsolutePath = [](const std::string &filename)
1179
0
    {
1180
0
        VSIStatBufL sStat;
1181
0
        if (VSIStatL(filename.c_str(), &sStat) != 0 ||
1182
0
            !CPLIsFilenameRelative(filename.c_str()))
1183
0
            return filename;
1184
0
        char *pszCWD = CPLGetCurrentDir();
1185
0
        if (!pszCWD)
1186
0
            return filename;
1187
0
        const auto absPath =
1188
0
            CPLFormFilenameSafe(pszCWD, filename.c_str(), nullptr);
1189
0
        CPLFree(pszCWD);
1190
0
        return absPath;
1191
0
    };
1192
1193
0
    ret += ' ';
1194
0
    switch (GetType())
1195
0
    {
1196
0
        case GAAT_BOOLEAN:
1197
0
            break;
1198
0
        case GAAT_STRING:
1199
0
        {
1200
0
            const auto &val = Get<std::string>();
1201
0
            ret += GetEscapedString(val);
1202
0
            break;
1203
0
        }
1204
0
        case GAAT_INTEGER:
1205
0
        {
1206
0
            ret += CPLSPrintf("%d", Get<int>());
1207
0
            break;
1208
0
        }
1209
0
        case GAAT_REAL:
1210
0
        {
1211
0
            ret += CPLSPrintf("%.17g", Get<double>());
1212
0
            break;
1213
0
        }
1214
0
        case GAAT_DATASET:
1215
0
        {
1216
0
            const auto &val = Get<GDALArgDatasetValue>();
1217
0
            const auto &str = val.GetName();
1218
0
            if (str.empty())
1219
0
            {
1220
0
                return false;
1221
0
            }
1222
0
            ret += GetEscapedString(absolutePath ? MakeAbsolutePath(str) : str);
1223
0
            break;
1224
0
        }
1225
0
        case GAAT_STRING_LIST:
1226
0
        {
1227
0
            const auto &vals = Get<std::vector<std::string>>();
1228
0
            for (size_t i = 0; i < vals.size(); ++i)
1229
0
            {
1230
0
                if (i > 0)
1231
0
                    AddListValueSeparator();
1232
0
                ret += GetEscapedString(vals[i]);
1233
0
            }
1234
0
            break;
1235
0
        }
1236
0
        case GAAT_INTEGER_LIST:
1237
0
        {
1238
0
            const auto &vals = Get<std::vector<int>>();
1239
0
            for (size_t i = 0; i < vals.size(); ++i)
1240
0
            {
1241
0
                if (i > 0)
1242
0
                    AddListValueSeparator();
1243
0
                ret += CPLSPrintf("%d", vals[i]);
1244
0
            }
1245
0
            break;
1246
0
        }
1247
0
        case GAAT_REAL_LIST:
1248
0
        {
1249
0
            const auto &vals = Get<std::vector<double>>();
1250
0
            for (size_t i = 0; i < vals.size(); ++i)
1251
0
            {
1252
0
                if (i > 0)
1253
0
                    AddListValueSeparator();
1254
0
                ret += CPLSPrintf("%.17g", vals[i]);
1255
0
            }
1256
0
            break;
1257
0
        }
1258
0
        case GAAT_DATASET_LIST:
1259
0
        {
1260
0
            const auto &vals = Get<std::vector<GDALArgDatasetValue>>();
1261
0
            for (size_t i = 0; i < vals.size(); ++i)
1262
0
            {
1263
0
                if (i > 0)
1264
0
                    AddListValueSeparator();
1265
0
                const auto &val = vals[i];
1266
0
                const auto &str = val.GetName();
1267
0
                if (str.empty())
1268
0
                {
1269
0
                    return false;
1270
0
                }
1271
0
                ret += GetEscapedString(absolutePath ? MakeAbsolutePath(str)
1272
0
                                                     : str);
1273
0
            }
1274
0
            break;
1275
0
        }
1276
0
    }
1277
1278
0
    serializedArg = std::move(ret);
1279
0
    return true;
1280
0
}
1281
1282
/************************************************************************/
1283
/*                  ~GDALInConstructionAlgorithmArg()                   */
1284
/************************************************************************/
1285
1286
GDALInConstructionAlgorithmArg::~GDALInConstructionAlgorithmArg() = default;
1287
1288
/************************************************************************/
1289
/*              GDALInConstructionAlgorithmArg::AddAlias()              */
1290
/************************************************************************/
1291
1292
GDALInConstructionAlgorithmArg &
1293
GDALInConstructionAlgorithmArg::AddAlias(const std::string &alias)
1294
0
{
1295
0
    m_decl.AddAlias(alias);
1296
0
    if (m_owner)
1297
0
        m_owner->AddAliasFor(this, alias);
1298
0
    return *this;
1299
0
}
1300
1301
/************************************************************************/
1302
/*           GDALInConstructionAlgorithmArg::AddHiddenAlias()           */
1303
/************************************************************************/
1304
1305
GDALInConstructionAlgorithmArg &
1306
GDALInConstructionAlgorithmArg::AddHiddenAlias(const std::string &alias)
1307
0
{
1308
0
    m_decl.AddHiddenAlias(alias);
1309
0
    if (m_owner)
1310
0
        m_owner->AddAliasFor(this, alias);
1311
0
    return *this;
1312
0
}
1313
1314
/************************************************************************/
1315
/*         GDALInConstructionAlgorithmArg::AddShortNameAlias()          */
1316
/************************************************************************/
1317
1318
GDALInConstructionAlgorithmArg &
1319
GDALInConstructionAlgorithmArg::AddShortNameAlias(char shortNameAlias)
1320
0
{
1321
0
    m_decl.AddShortNameAlias(shortNameAlias);
1322
0
    if (m_owner)
1323
0
        m_owner->AddShortNameAliasFor(this, shortNameAlias);
1324
0
    return *this;
1325
0
}
1326
1327
/************************************************************************/
1328
/*           GDALInConstructionAlgorithmArg::SetPositional()            */
1329
/************************************************************************/
1330
1331
GDALInConstructionAlgorithmArg &GDALInConstructionAlgorithmArg::SetPositional()
1332
0
{
1333
0
    m_decl.SetPositional();
1334
0
    if (m_owner)
1335
0
        m_owner->SetPositional(this);
1336
0
    return *this;
1337
0
}
1338
1339
/************************************************************************/
1340
/*              GDALArgDatasetValue::GDALArgDatasetValue()              */
1341
/************************************************************************/
1342
1343
GDALArgDatasetValue::GDALArgDatasetValue(GDALDataset *poDS)
1344
0
    : m_poDS(poDS), m_name(m_poDS ? m_poDS->GetDescription() : std::string()),
1345
0
      m_nameSet(true)
1346
0
{
1347
0
    if (m_poDS)
1348
0
        m_poDS->Reference();
1349
0
}
1350
1351
/************************************************************************/
1352
/*                      GDALArgDatasetValue::Set()                      */
1353
/************************************************************************/
1354
1355
void GDALArgDatasetValue::Set(const std::string &name)
1356
0
{
1357
0
    Close();
1358
0
    m_name = name;
1359
0
    m_nameSet = true;
1360
0
    if (m_ownerArg)
1361
0
        m_ownerArg->NotifyValueSet();
1362
0
}
1363
1364
/************************************************************************/
1365
/*                      GDALArgDatasetValue::Set()                      */
1366
/************************************************************************/
1367
1368
void GDALArgDatasetValue::Set(std::unique_ptr<GDALDataset> poDS)
1369
0
{
1370
0
    Close();
1371
0
    m_poDS = poDS.release();
1372
0
    m_name = m_poDS ? m_poDS->GetDescription() : std::string();
1373
0
    m_nameSet = true;
1374
0
    if (m_ownerArg)
1375
0
        m_ownerArg->NotifyValueSet();
1376
0
}
1377
1378
/************************************************************************/
1379
/*                      GDALArgDatasetValue::Set()                      */
1380
/************************************************************************/
1381
1382
void GDALArgDatasetValue::Set(GDALDataset *poDS)
1383
0
{
1384
0
    Close();
1385
0
    m_poDS = poDS;
1386
0
    if (m_poDS)
1387
0
        m_poDS->Reference();
1388
0
    m_name = m_poDS ? m_poDS->GetDescription() : std::string();
1389
0
    m_nameSet = true;
1390
0
    if (m_ownerArg)
1391
0
        m_ownerArg->NotifyValueSet();
1392
0
}
1393
1394
/************************************************************************/
1395
/*                    GDALArgDatasetValue::SetFrom()                    */
1396
/************************************************************************/
1397
1398
void GDALArgDatasetValue::SetFrom(const GDALArgDatasetValue &other)
1399
0
{
1400
0
    Close();
1401
0
    m_name = other.m_name;
1402
0
    m_nameSet = other.m_nameSet;
1403
0
    m_poDS = other.m_poDS;
1404
0
    if (m_poDS)
1405
0
        m_poDS->Reference();
1406
0
}
1407
1408
/************************************************************************/
1409
/*             GDALArgDatasetValue::~GDALArgDatasetValue()              */
1410
/************************************************************************/
1411
1412
GDALArgDatasetValue::~GDALArgDatasetValue()
1413
0
{
1414
0
    Close();
1415
0
}
1416
1417
/************************************************************************/
1418
/*                     GDALArgDatasetValue::Close()                     */
1419
/************************************************************************/
1420
1421
bool GDALArgDatasetValue::Close()
1422
0
{
1423
0
    bool ret = true;
1424
0
    if (m_poDS && m_poDS->Dereference() == 0)
1425
0
    {
1426
0
        ret = m_poDS->Close() == CE_None;
1427
0
        delete m_poDS;
1428
0
    }
1429
0
    m_poDS = nullptr;
1430
0
    return ret;
1431
0
}
1432
1433
/************************************************************************/
1434
/*                   GDALArgDatasetValue::operator=()                   */
1435
/************************************************************************/
1436
1437
GDALArgDatasetValue &GDALArgDatasetValue::operator=(GDALArgDatasetValue &&other)
1438
0
{
1439
0
    Close();
1440
0
    m_poDS = other.m_poDS;
1441
0
    m_name = other.m_name;
1442
0
    m_nameSet = other.m_nameSet;
1443
0
    other.m_poDS = nullptr;
1444
0
    other.m_name.clear();
1445
0
    other.m_nameSet = false;
1446
0
    return *this;
1447
0
}
1448
1449
/************************************************************************/
1450
/*                  GDALArgDatasetValue::GetDataset()                   */
1451
/************************************************************************/
1452
1453
GDALDataset *GDALArgDatasetValue::GetDatasetIncreaseRefCount()
1454
0
{
1455
0
    if (m_poDS)
1456
0
        m_poDS->Reference();
1457
0
    return m_poDS;
1458
0
}
1459
1460
/************************************************************************/
1461
/*           GDALArgDatasetValue(GDALArgDatasetValue &&other)           */
1462
/************************************************************************/
1463
1464
GDALArgDatasetValue::GDALArgDatasetValue(GDALArgDatasetValue &&other)
1465
0
    : m_poDS(other.m_poDS), m_name(other.m_name), m_nameSet(other.m_nameSet)
1466
0
{
1467
0
    other.m_poDS = nullptr;
1468
0
    other.m_name.clear();
1469
0
}
1470
1471
/************************************************************************/
1472
/*            GDALInConstructionAlgorithmArg::SetIsCRSArg()             */
1473
/************************************************************************/
1474
1475
GDALInConstructionAlgorithmArg &GDALInConstructionAlgorithmArg::SetIsCRSArg(
1476
    bool noneAllowed, const std::vector<std::string> &specialValues)
1477
0
{
1478
0
    if (GetType() != GAAT_STRING)
1479
0
    {
1480
0
        CPLError(CE_Failure, CPLE_AppDefined,
1481
0
                 "SetIsCRSArg() can only be called on a String argument");
1482
0
        return *this;
1483
0
    }
1484
0
    AddValidationAction(
1485
0
        [this, noneAllowed, specialValues]()
1486
0
        {
1487
0
            const std::string &osVal =
1488
0
                static_cast<const GDALInConstructionAlgorithmArg *>(this)
1489
0
                    ->Get<std::string>();
1490
0
            if (osVal == "?" && m_owner && m_owner->IsCalledFromCommandLine())
1491
0
                return true;
1492
1493
0
            if ((!noneAllowed || (osVal != "none" && osVal != "null")) &&
1494
0
                std::find(specialValues.begin(), specialValues.end(), osVal) ==
1495
0
                    specialValues.end())
1496
0
            {
1497
0
                OGRSpatialReference oSRS;
1498
0
                if (oSRS.SetFromUserInput(osVal.c_str()) != OGRERR_NONE)
1499
0
                {
1500
0
                    m_owner->ReportError(CE_Failure, CPLE_AppDefined,
1501
0
                                         "Invalid value for '%s' argument",
1502
0
                                         GetName().c_str());
1503
0
                    return false;
1504
0
                }
1505
0
            }
1506
0
            return true;
1507
0
        });
1508
1509
0
    SetAutoCompleteFunction(
1510
0
        [this, noneAllowed, specialValues](const std::string &currentValue)
1511
0
        {
1512
0
            bool bIsRaster = false;
1513
0
            OGREnvelope sDatasetLongLatEnv;
1514
0
            std::string osCelestialBodyName;
1515
0
            if (GetName() == "dst-crs")
1516
0
            {
1517
0
                auto inputArg = m_owner->GetArg(GDAL_ARG_NAME_INPUT);
1518
0
                if (inputArg && inputArg->GetType() == GAAT_DATASET_LIST)
1519
0
                {
1520
0
                    auto &val =
1521
0
                        inputArg->Get<std::vector<GDALArgDatasetValue>>();
1522
0
                    if (val.size() == 1)
1523
0
                    {
1524
0
                        CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
1525
0
                        auto poDS = std::unique_ptr<GDALDataset>(
1526
0
                            GDALDataset::Open(val[0].GetName().c_str()));
1527
0
                        if (poDS)
1528
0
                        {
1529
0
                            bIsRaster = poDS->GetRasterCount() != 0;
1530
0
                            if (auto poCRS = poDS->GetSpatialRef())
1531
0
                            {
1532
0
                                const char *pszCelestialBodyName =
1533
0
                                    poCRS->GetCelestialBodyName();
1534
0
                                if (pszCelestialBodyName)
1535
0
                                    osCelestialBodyName = pszCelestialBodyName;
1536
1537
0
                                if (!pszCelestialBodyName ||
1538
0
                                    !EQUAL(pszCelestialBodyName, "Earth"))
1539
0
                                {
1540
0
                                    OGRSpatialReference oLongLat;
1541
0
                                    oLongLat.CopyGeogCSFrom(poCRS);
1542
0
                                    oLongLat.SetAxisMappingStrategy(
1543
0
                                        OAMS_TRADITIONAL_GIS_ORDER);
1544
0
                                    poDS->GetExtent(&sDatasetLongLatEnv,
1545
0
                                                    &oLongLat);
1546
0
                                }
1547
0
                                else
1548
0
                                {
1549
0
                                    poDS->GetExtentWGS84LongLat(
1550
0
                                        &sDatasetLongLatEnv);
1551
0
                                }
1552
0
                            }
1553
0
                        }
1554
0
                    }
1555
0
                }
1556
0
            }
1557
1558
0
            const auto IsCRSCompatible =
1559
0
                [bIsRaster, &sDatasetLongLatEnv,
1560
0
                 &osCelestialBodyName](const OSRCRSInfo *crsInfo)
1561
0
            {
1562
0
                if (!sDatasetLongLatEnv.IsInit())
1563
0
                    return true;
1564
0
                return crsInfo->eType != OSR_CRS_TYPE_VERTICAL &&
1565
0
                       !(bIsRaster &&
1566
0
                         crsInfo->eType == OSR_CRS_TYPE_GEOCENTRIC) &&
1567
0
                       crsInfo->dfWestLongitudeDeg <
1568
0
                           crsInfo->dfEastLongitudeDeg &&
1569
0
                       sDatasetLongLatEnv.MinX < crsInfo->dfEastLongitudeDeg &&
1570
0
                       sDatasetLongLatEnv.MaxX > crsInfo->dfWestLongitudeDeg &&
1571
0
                       sDatasetLongLatEnv.MinY < crsInfo->dfNorthLatitudeDeg &&
1572
0
                       sDatasetLongLatEnv.MaxY > crsInfo->dfSouthLatitudeDeg &&
1573
0
                       ((!osCelestialBodyName.empty() &&
1574
0
                         crsInfo->pszCelestialBodyName &&
1575
0
                         osCelestialBodyName ==
1576
0
                             crsInfo->pszCelestialBodyName) ||
1577
0
                        (osCelestialBodyName.empty() &&
1578
0
                         !crsInfo->pszCelestialBodyName));
1579
0
            };
1580
1581
0
            std::vector<std::string> oRet;
1582
0
            if (noneAllowed)
1583
0
                oRet.push_back("none");
1584
0
            oRet.insert(oRet.end(), specialValues.begin(), specialValues.end());
1585
0
            if (!currentValue.empty())
1586
0
            {
1587
0
                const CPLStringList aosTokens(
1588
0
                    CSLTokenizeString2(currentValue.c_str(), ":", 0));
1589
0
                int nCount = 0;
1590
0
                std::unique_ptr<OSRCRSInfo *, decltype(&OSRDestroyCRSInfoList)>
1591
0
                    pCRSList(OSRGetCRSInfoListFromDatabase(aosTokens[0],
1592
0
                                                           nullptr, &nCount),
1593
0
                             OSRDestroyCRSInfoList);
1594
0
                std::string osCode;
1595
1596
0
                std::vector<const OSRCRSInfo *> candidates;
1597
0
                for (int i = 0; i < nCount; ++i)
1598
0
                {
1599
0
                    const auto *entry = (pCRSList.get())[i];
1600
0
                    if (!entry->bDeprecated && IsCRSCompatible(entry))
1601
0
                    {
1602
0
                        if (aosTokens.size() == 1 ||
1603
0
                            STARTS_WITH(entry->pszCode, aosTokens[1]))
1604
0
                        {
1605
0
                            if (candidates.empty())
1606
0
                                osCode = entry->pszCode;
1607
0
                            candidates.push_back(entry);
1608
0
                        }
1609
0
                    }
1610
0
                }
1611
0
                if (candidates.size() == 1)
1612
0
                {
1613
0
                    oRet.push_back(std::move(osCode));
1614
0
                }
1615
0
                else
1616
0
                {
1617
0
                    if (sDatasetLongLatEnv.IsInit())
1618
0
                    {
1619
0
                        std::sort(
1620
0
                            candidates.begin(), candidates.end(),
1621
0
                            [](const OSRCRSInfo *a, const OSRCRSInfo *b)
1622
0
                            {
1623
0
                                const double dfXa =
1624
0
                                    a->dfWestLongitudeDeg >
1625
0
                                            a->dfEastLongitudeDeg
1626
0
                                        ? a->dfWestLongitudeDeg -
1627
0
                                              a->dfEastLongitudeDeg
1628
0
                                        : (180 - a->dfWestLongitudeDeg) +
1629
0
                                              (a->dfEastLongitudeDeg - -180);
1630
0
                                const double dfYa = a->dfNorthLatitudeDeg -
1631
0
                                                    a->dfSouthLatitudeDeg;
1632
0
                                const double dfXb =
1633
0
                                    b->dfWestLongitudeDeg >
1634
0
                                            b->dfEastLongitudeDeg
1635
0
                                        ? b->dfWestLongitudeDeg -
1636
0
                                              b->dfEastLongitudeDeg
1637
0
                                        : (180 - b->dfWestLongitudeDeg) +
1638
0
                                              (b->dfEastLongitudeDeg - -180);
1639
0
                                const double dfYb = b->dfNorthLatitudeDeg -
1640
0
                                                    b->dfSouthLatitudeDeg;
1641
0
                                const double diffArea =
1642
0
                                    dfXa * dfYa - dfXb * dfYb;
1643
0
                                if (diffArea < 0)
1644
0
                                    return true;
1645
0
                                if (diffArea == 0)
1646
0
                                {
1647
0
                                    if (std::string_view(a->pszName) ==
1648
0
                                        b->pszName)
1649
0
                                    {
1650
0
                                        if (a->eType ==
1651
0
                                                OSR_CRS_TYPE_GEOGRAPHIC_2D &&
1652
0
                                            b->eType !=
1653
0
                                                OSR_CRS_TYPE_GEOGRAPHIC_2D)
1654
0
                                            return true;
1655
0
                                        if (a->eType ==
1656
0
                                                OSR_CRS_TYPE_GEOGRAPHIC_3D &&
1657
0
                                            b->eType == OSR_CRS_TYPE_GEOCENTRIC)
1658
0
                                            return true;
1659
0
                                        return false;
1660
0
                                    }
1661
0
                                    return std::string_view(a->pszCode) <
1662
0
                                           b->pszCode;
1663
0
                                }
1664
0
                                return false;
1665
0
                            });
1666
0
                    }
1667
1668
0
                    for (const auto *entry : candidates)
1669
0
                    {
1670
0
                        std::string val = std::string(entry->pszCode)
1671
0
                                              .append(" -- ")
1672
0
                                              .append(entry->pszName);
1673
0
                        if (entry->eType == OSR_CRS_TYPE_GEOGRAPHIC_2D)
1674
0
                            val.append(" (geographic 2D)");
1675
0
                        else if (entry->eType == OSR_CRS_TYPE_GEOGRAPHIC_3D)
1676
0
                            val.append(" (geographic 3D)");
1677
0
                        else if (entry->eType == OSR_CRS_TYPE_GEOCENTRIC)
1678
0
                            val.append(" (geocentric)");
1679
0
                        oRet.push_back(std::move(val));
1680
0
                    }
1681
0
                }
1682
0
            }
1683
0
            if (currentValue.empty() || oRet.empty())
1684
0
            {
1685
0
                const CPLStringList aosAuthorities(
1686
0
                    OSRGetAuthorityListFromDatabase());
1687
0
                for (const char *pszAuth : cpl::Iterate(aosAuthorities))
1688
0
                {
1689
0
                    int nCount = 0;
1690
0
                    OSRDestroyCRSInfoList(OSRGetCRSInfoListFromDatabase(
1691
0
                        pszAuth, nullptr, &nCount));
1692
0
                    if (nCount)
1693
0
                        oRet.push_back(std::string(pszAuth).append(":"));
1694
0
                }
1695
0
            }
1696
0
            return oRet;
1697
0
        });
1698
1699
0
    return *this;
1700
0
}
1701
1702
/************************************************************************/
1703
/*                    GDALAlgorithm::GDALAlgorithm()                    */
1704
/************************************************************************/
1705
1706
GDALAlgorithm::GDALAlgorithm(const std::string &name,
1707
                             const std::string &description,
1708
                             const std::string &helpURL)
1709
0
    : m_name(name), m_description(description), m_helpURL(helpURL),
1710
0
      m_helpFullURL(!m_helpURL.empty() && m_helpURL[0] == '/'
1711
0
                        ? "https://gdal.org" + m_helpURL
1712
0
                        : m_helpURL)
1713
0
{
1714
0
    AddArg("help", 'h', _("Display help message and exit"), &m_helpRequested)
1715
0
        .SetHiddenForAPI()
1716
0
        .SetCategory(GAAC_COMMON)
1717
0
        .AddAction([this]() { m_specialActionRequested = true; });
1718
0
    AddArg("help-doc", 0, _("Display help message for use by documentation"),
1719
0
           &m_helpDocRequested)
1720
0
        .SetHidden()
1721
0
        .AddAction([this]() { m_specialActionRequested = true; });
1722
0
    AddArg("json-usage", 0, _("Display usage as JSON document and exit"),
1723
0
           &m_JSONUsageRequested)
1724
0
        .SetHiddenForAPI()
1725
0
        .SetCategory(GAAC_COMMON)
1726
0
        .AddAction([this]() { m_specialActionRequested = true; });
1727
0
    AddArg("config", 0, _("Configuration option"), &m_dummyConfigOptions)
1728
0
        .SetMetaVar("<KEY>=<VALUE>")
1729
0
        .SetHiddenForAPI()
1730
0
        .SetCategory(GAAC_COMMON)
1731
0
        .AddAction(
1732
0
            [this]()
1733
0
            {
1734
0
                ReportError(
1735
0
                    CE_Warning, CPLE_AppDefined,
1736
0
                    "Configuration options passed with the 'config' argument "
1737
0
                    "are ignored");
1738
0
            });
1739
0
}
1740
1741
/************************************************************************/
1742
/*                   GDALAlgorithm::~GDALAlgorithm()                    */
1743
/************************************************************************/
1744
1745
0
GDALAlgorithm::~GDALAlgorithm() = default;
1746
1747
/************************************************************************/
1748
/*                    GDALAlgorithm::ParseArgument()                    */
1749
/************************************************************************/
1750
1751
bool GDALAlgorithm::ParseArgument(
1752
    GDALAlgorithmArg *arg, const std::string &name, const std::string &value,
1753
    std::map<
1754
        GDALAlgorithmArg *,
1755
        std::variant<std::vector<std::string>, std::vector<int>,
1756
                     std::vector<double>, std::vector<GDALArgDatasetValue>>>
1757
        &inConstructionValues)
1758
0
{
1759
0
    const bool isListArg = GDALAlgorithmArgTypeIsList(arg->GetType());
1760
0
    if (arg->IsExplicitlySet() && !isListArg)
1761
0
    {
1762
        // Hack for "gdal info" to be able to pass an opened raster dataset
1763
        // by "gdal raster info" to the "gdal vector info" algorithm.
1764
0
        if (arg->SkipIfAlreadySet())
1765
0
        {
1766
0
            arg->SetSkipIfAlreadySet(false);
1767
0
            return true;
1768
0
        }
1769
1770
0
        ReportError(CE_Failure, CPLE_IllegalArg,
1771
0
                    "Argument '%s' has already been specified.", name.c_str());
1772
0
        return false;
1773
0
    }
1774
1775
0
    if (!arg->GetRepeatedArgAllowed() &&
1776
0
        cpl::contains(inConstructionValues, arg))
1777
0
    {
1778
0
        ReportError(CE_Failure, CPLE_IllegalArg,
1779
0
                    "Argument '%s' has already been specified.", name.c_str());
1780
0
        return false;
1781
0
    }
1782
1783
0
    switch (arg->GetType())
1784
0
    {
1785
0
        case GAAT_BOOLEAN:
1786
0
        {
1787
0
            if (value.empty() || value == "true")
1788
0
                return arg->Set(true);
1789
0
            else if (value == "false")
1790
0
                return arg->Set(false);
1791
0
            else
1792
0
            {
1793
0
                ReportError(
1794
0
                    CE_Failure, CPLE_IllegalArg,
1795
0
                    "Invalid value '%s' for boolean argument '%s'. Should be "
1796
0
                    "'true' or 'false'.",
1797
0
                    value.c_str(), name.c_str());
1798
0
                return false;
1799
0
            }
1800
0
        }
1801
1802
0
        case GAAT_STRING:
1803
0
        {
1804
0
            return arg->Set(value);
1805
0
        }
1806
1807
0
        case GAAT_INTEGER:
1808
0
        {
1809
0
            errno = 0;
1810
0
            char *endptr = nullptr;
1811
0
            const auto val = std::strtol(value.c_str(), &endptr, 10);
1812
0
            if (errno == 0 && endptr &&
1813
0
                endptr == value.c_str() + value.size() && val >= INT_MIN &&
1814
0
                val <= INT_MAX)
1815
0
            {
1816
0
                return arg->Set(static_cast<int>(val));
1817
0
            }
1818
0
            else
1819
0
            {
1820
0
                ReportError(CE_Failure, CPLE_IllegalArg,
1821
0
                            "Expected integer value for argument '%s', "
1822
0
                            "but got '%s'.",
1823
0
                            name.c_str(), value.c_str());
1824
0
                return false;
1825
0
            }
1826
0
        }
1827
1828
0
        case GAAT_REAL:
1829
0
        {
1830
0
            char *endptr = nullptr;
1831
0
            double dfValue = CPLStrtod(value.c_str(), &endptr);
1832
0
            if (endptr != value.c_str() + value.size())
1833
0
            {
1834
0
                ReportError(
1835
0
                    CE_Failure, CPLE_IllegalArg,
1836
0
                    "Expected real value for argument '%s', but got '%s'.",
1837
0
                    name.c_str(), value.c_str());
1838
0
                return false;
1839
0
            }
1840
0
            return arg->Set(dfValue);
1841
0
        }
1842
1843
0
        case GAAT_DATASET:
1844
0
        {
1845
0
            return arg->SetDatasetName(value);
1846
0
        }
1847
1848
0
        case GAAT_STRING_LIST:
1849
0
        {
1850
0
            const CPLStringList aosTokens(
1851
0
                arg->GetPackedValuesAllowed()
1852
0
                    ? CSLTokenizeString2(value.c_str(), ",",
1853
0
                                         CSLT_HONOURSTRINGS |
1854
0
                                             CSLT_PRESERVEQUOTES)
1855
0
                    : CSLAddString(nullptr, value.c_str()));
1856
0
            if (!cpl::contains(inConstructionValues, arg))
1857
0
            {
1858
0
                inConstructionValues[arg] = std::vector<std::string>();
1859
0
            }
1860
0
            auto &valueVector =
1861
0
                std::get<std::vector<std::string>>(inConstructionValues[arg]);
1862
0
            for (const char *v : aosTokens)
1863
0
            {
1864
0
                valueVector.push_back(v);
1865
0
            }
1866
0
            break;
1867
0
        }
1868
1869
0
        case GAAT_INTEGER_LIST:
1870
0
        {
1871
0
            const CPLStringList aosTokens(
1872
0
                arg->GetPackedValuesAllowed()
1873
0
                    ? CSLTokenizeString2(
1874
0
                          value.c_str(), ",",
1875
0
                          CSLT_HONOURSTRINGS | CSLT_STRIPLEADSPACES |
1876
0
                              CSLT_STRIPENDSPACES | CSLT_ALLOWEMPTYTOKENS)
1877
0
                    : CSLAddString(nullptr, value.c_str()));
1878
0
            if (!cpl::contains(inConstructionValues, arg))
1879
0
            {
1880
0
                inConstructionValues[arg] = std::vector<int>();
1881
0
            }
1882
0
            auto &valueVector =
1883
0
                std::get<std::vector<int>>(inConstructionValues[arg]);
1884
0
            for (const char *v : aosTokens)
1885
0
            {
1886
0
                errno = 0;
1887
0
                char *endptr = nullptr;
1888
0
                const auto val = std::strtol(v, &endptr, 10);
1889
0
                if (errno == 0 && endptr && endptr == v + strlen(v) &&
1890
0
                    val >= INT_MIN && val <= INT_MAX && strlen(v) > 0)
1891
0
                {
1892
0
                    valueVector.push_back(static_cast<int>(val));
1893
0
                }
1894
0
                else
1895
0
                {
1896
0
                    ReportError(
1897
0
                        CE_Failure, CPLE_IllegalArg,
1898
0
                        "Expected list of integer value for argument '%s', "
1899
0
                        "but got '%s'.",
1900
0
                        name.c_str(), value.c_str());
1901
0
                    return false;
1902
0
                }
1903
0
            }
1904
0
            break;
1905
0
        }
1906
1907
0
        case GAAT_REAL_LIST:
1908
0
        {
1909
0
            const CPLStringList aosTokens(
1910
0
                arg->GetPackedValuesAllowed()
1911
0
                    ? CSLTokenizeString2(
1912
0
                          value.c_str(), ",",
1913
0
                          CSLT_HONOURSTRINGS | CSLT_STRIPLEADSPACES |
1914
0
                              CSLT_STRIPENDSPACES | CSLT_ALLOWEMPTYTOKENS)
1915
0
                    : CSLAddString(nullptr, value.c_str()));
1916
0
            if (!cpl::contains(inConstructionValues, arg))
1917
0
            {
1918
0
                inConstructionValues[arg] = std::vector<double>();
1919
0
            }
1920
0
            auto &valueVector =
1921
0
                std::get<std::vector<double>>(inConstructionValues[arg]);
1922
0
            for (const char *v : aosTokens)
1923
0
            {
1924
0
                char *endptr = nullptr;
1925
0
                double dfValue = CPLStrtod(v, &endptr);
1926
0
                if (strlen(v) == 0 || endptr != v + strlen(v))
1927
0
                {
1928
0
                    ReportError(
1929
0
                        CE_Failure, CPLE_IllegalArg,
1930
0
                        "Expected list of real value for argument '%s', "
1931
0
                        "but got '%s'.",
1932
0
                        name.c_str(), value.c_str());
1933
0
                    return false;
1934
0
                }
1935
0
                valueVector.push_back(dfValue);
1936
0
            }
1937
0
            break;
1938
0
        }
1939
1940
0
        case GAAT_DATASET_LIST:
1941
0
        {
1942
0
            if (!cpl::contains(inConstructionValues, arg))
1943
0
            {
1944
0
                inConstructionValues[arg] = std::vector<GDALArgDatasetValue>();
1945
0
            }
1946
0
            auto &valueVector = std::get<std::vector<GDALArgDatasetValue>>(
1947
0
                inConstructionValues[arg]);
1948
0
            if (!value.empty() && value[0] == '{' && value.back() == '}')
1949
0
            {
1950
0
                valueVector.push_back(GDALArgDatasetValue(value));
1951
0
            }
1952
0
            else
1953
0
            {
1954
0
                const CPLStringList aosTokens(
1955
0
                    arg->GetPackedValuesAllowed()
1956
0
                        ? CSLTokenizeString2(value.c_str(), ",",
1957
0
                                             CSLT_HONOURSTRINGS |
1958
0
                                                 CSLT_STRIPLEADSPACES)
1959
0
                        : CSLAddString(nullptr, value.c_str()));
1960
0
                for (const char *v : aosTokens)
1961
0
                {
1962
0
                    valueVector.push_back(GDALArgDatasetValue(v));
1963
0
                }
1964
0
            }
1965
0
            break;
1966
0
        }
1967
0
    }
1968
1969
0
    return true;
1970
0
}
1971
1972
/************************************************************************/
1973
/*              GDALAlgorithm::ParseCommandLineArguments()              */
1974
/************************************************************************/
1975
1976
bool GDALAlgorithm::ParseCommandLineArguments(
1977
    const std::vector<std::string> &args)
1978
0
{
1979
0
    if (m_parsedSubStringAlreadyCalled)
1980
0
    {
1981
0
        ReportError(CE_Failure, CPLE_AppDefined,
1982
0
                    "ParseCommandLineArguments() can only be called once per "
1983
0
                    "instance.");
1984
0
        return false;
1985
0
    }
1986
0
    m_parsedSubStringAlreadyCalled = true;
1987
1988
    // AWS like syntax supported too (not advertized)
1989
0
    if (args.size() == 1 && args[0] == "help")
1990
0
    {
1991
0
        auto arg = GetArg("help");
1992
0
        assert(arg);
1993
0
        arg->Set(true);
1994
0
        arg->RunActions();
1995
0
        return true;
1996
0
    }
1997
1998
0
    if (HasSubAlgorithms())
1999
0
    {
2000
0
        if (args.empty())
2001
0
        {
2002
0
            ReportError(CE_Failure, CPLE_AppDefined, "Missing %s name.",
2003
0
                        m_callPath.size() == 1 ? "command" : "subcommand");
2004
0
            return false;
2005
0
        }
2006
0
        if (!args[0].empty() && args[0][0] == '-')
2007
0
        {
2008
            // go on argument parsing
2009
0
        }
2010
0
        else
2011
0
        {
2012
0
            const auto nCounter = CPLGetErrorCounter();
2013
0
            m_selectedSubAlgHolder = InstantiateSubAlgorithm(args[0]);
2014
0
            if (m_selectedSubAlgHolder)
2015
0
            {
2016
0
                m_selectedSubAlg = m_selectedSubAlgHolder.get();
2017
0
                m_selectedSubAlg->SetReferencePathForRelativePaths(
2018
0
                    m_referencePath);
2019
0
                m_selectedSubAlg->m_executionForStreamOutput =
2020
0
                    m_executionForStreamOutput;
2021
0
                m_selectedSubAlg->m_calledFromCommandLine =
2022
0
                    m_calledFromCommandLine;
2023
0
                m_selectedSubAlg->m_skipValidationInParseCommandLine =
2024
0
                    m_skipValidationInParseCommandLine;
2025
0
                bool bRet = m_selectedSubAlg->ParseCommandLineArguments(
2026
0
                    std::vector<std::string>(args.begin() + 1, args.end()));
2027
0
                m_selectedSubAlg->PropagateSpecialActionTo(this);
2028
0
                return bRet;
2029
0
            }
2030
0
            else
2031
0
            {
2032
0
                if (!(CPLGetErrorCounter() == nCounter + 1 &&
2033
0
                      strstr(CPLGetLastErrorMsg(), "Do you mean")))
2034
0
                {
2035
0
                    ReportError(CE_Failure, CPLE_AppDefined,
2036
0
                                "Unknown command: '%s'", args[0].c_str());
2037
0
                }
2038
0
                return false;
2039
0
            }
2040
0
        }
2041
0
    }
2042
2043
0
    std::map<
2044
0
        GDALAlgorithmArg *,
2045
0
        std::variant<std::vector<std::string>, std::vector<int>,
2046
0
                     std::vector<double>, std::vector<GDALArgDatasetValue>>>
2047
0
        inConstructionValues;
2048
2049
0
    std::vector<std::string> lArgs(args);
2050
0
    bool helpValueRequested = false;
2051
0
    for (size_t i = 0; i < lArgs.size(); /* incremented in loop */)
2052
0
    {
2053
0
        const auto &strArg = lArgs[i];
2054
0
        GDALAlgorithmArg *arg = nullptr;
2055
0
        std::string name;
2056
0
        std::string value;
2057
0
        bool hasValue = false;
2058
0
        if (m_calledFromCommandLine && cpl::ends_with(strArg, "=?"))
2059
0
            helpValueRequested = true;
2060
0
        if (strArg.size() >= 2 && strArg[0] == '-' && strArg[1] == '-')
2061
0
        {
2062
0
            const auto equalPos = strArg.find('=');
2063
0
            name = (equalPos != std::string::npos) ? strArg.substr(0, equalPos)
2064
0
                                                   : strArg;
2065
0
            const std::string nameWithoutDash = name.substr(2);
2066
0
            auto iterArg = m_mapLongNameToArg.find(nameWithoutDash);
2067
0
            if (m_arbitraryLongNameArgsAllowed &&
2068
0
                iterArg == m_mapLongNameToArg.end())
2069
0
            {
2070
0
                GetArg(nameWithoutDash);
2071
0
                iterArg = m_mapLongNameToArg.find(nameWithoutDash);
2072
0
            }
2073
0
            if (iterArg == m_mapLongNameToArg.end())
2074
0
            {
2075
0
                const std::string bestCandidate =
2076
0
                    GetSuggestionForArgumentName(nameWithoutDash);
2077
0
                if (!bestCandidate.empty())
2078
0
                {
2079
0
                    ReportError(CE_Failure, CPLE_IllegalArg,
2080
0
                                "Option '%s' is unknown. Do you mean '--%s'?",
2081
0
                                name.c_str(), bestCandidate.c_str());
2082
0
                }
2083
0
                else
2084
0
                {
2085
0
                    ReportError(CE_Failure, CPLE_IllegalArg,
2086
0
                                "Option '%s' is unknown.", name.c_str());
2087
0
                }
2088
0
                return false;
2089
0
            }
2090
0
            arg = iterArg->second;
2091
0
            if (equalPos != std::string::npos)
2092
0
            {
2093
0
                hasValue = true;
2094
0
                value = strArg.substr(equalPos + 1);
2095
0
            }
2096
0
        }
2097
0
        else if (strArg.size() >= 2 && strArg[0] == '-' &&
2098
0
                 CPLGetValueType(strArg.c_str()) == CPL_VALUE_STRING)
2099
0
        {
2100
0
            for (size_t j = 1; j < strArg.size(); ++j)
2101
0
            {
2102
0
                name.clear();
2103
0
                name += strArg[j];
2104
0
                const auto iterArg = m_mapShortNameToArg.find(name);
2105
0
                if (iterArg == m_mapShortNameToArg.end())
2106
0
                {
2107
0
                    const std::string nameWithoutDash = strArg.substr(1);
2108
0
                    if (m_mapLongNameToArg.find(nameWithoutDash) !=
2109
0
                        m_mapLongNameToArg.end())
2110
0
                    {
2111
0
                        ReportError(CE_Failure, CPLE_IllegalArg,
2112
0
                                    "Short name option '%s' is unknown. Do you "
2113
0
                                    "mean '--%s' (with leading double dash) ?",
2114
0
                                    name.c_str(), nameWithoutDash.c_str());
2115
0
                    }
2116
0
                    else
2117
0
                    {
2118
0
                        const std::string bestCandidate =
2119
0
                            GetSuggestionForArgumentName(nameWithoutDash);
2120
0
                        if (!bestCandidate.empty())
2121
0
                        {
2122
0
                            ReportError(
2123
0
                                CE_Failure, CPLE_IllegalArg,
2124
0
                                "Short name option '%s' is unknown. Do you "
2125
0
                                "mean '--%s' (with leading double dash) ?",
2126
0
                                name.c_str(), bestCandidate.c_str());
2127
0
                        }
2128
0
                        else
2129
0
                        {
2130
0
                            ReportError(CE_Failure, CPLE_IllegalArg,
2131
0
                                        "Short name option '%s' is unknown.",
2132
0
                                        name.c_str());
2133
0
                        }
2134
0
                    }
2135
0
                    return false;
2136
0
                }
2137
0
                arg = iterArg->second;
2138
0
                if (strArg.size() > 2)
2139
0
                {
2140
0
                    if (arg->GetType() != GAAT_BOOLEAN)
2141
0
                    {
2142
0
                        ReportError(CE_Failure, CPLE_IllegalArg,
2143
0
                                    "Invalid argument '%s'. Option '%s' is not "
2144
0
                                    "a boolean option.",
2145
0
                                    strArg.c_str(), name.c_str());
2146
0
                        return false;
2147
0
                    }
2148
2149
0
                    if (!ParseArgument(arg, name, "true", inConstructionValues))
2150
0
                        return false;
2151
0
                }
2152
0
            }
2153
0
            if (strArg.size() > 2)
2154
0
            {
2155
0
                lArgs.erase(lArgs.begin() + i);
2156
0
                continue;
2157
0
            }
2158
0
        }
2159
0
        else
2160
0
        {
2161
0
            ++i;
2162
0
            continue;
2163
0
        }
2164
0
        CPLAssert(arg);
2165
2166
0
        if (arg && arg->GetType() == GAAT_BOOLEAN)
2167
0
        {
2168
0
            if (!hasValue)
2169
0
            {
2170
0
                hasValue = true;
2171
0
                value = "true";
2172
0
            }
2173
0
        }
2174
2175
0
        if (!hasValue)
2176
0
        {
2177
0
            if (i + 1 == lArgs.size())
2178
0
            {
2179
0
                if (m_parseForAutoCompletion)
2180
0
                {
2181
0
                    lArgs.erase(lArgs.begin() + i);
2182
0
                    break;
2183
0
                }
2184
0
                ReportError(
2185
0
                    CE_Failure, CPLE_IllegalArg,
2186
0
                    "Expected value for argument '%s', but ran short of tokens",
2187
0
                    name.c_str());
2188
0
                return false;
2189
0
            }
2190
0
            value = lArgs[i + 1];
2191
0
            lArgs.erase(lArgs.begin() + i + 1);
2192
0
        }
2193
2194
0
        if (arg && !ParseArgument(arg, name, value, inConstructionValues))
2195
0
            return false;
2196
2197
0
        lArgs.erase(lArgs.begin() + i);
2198
0
    }
2199
2200
0
    if (m_specialActionRequested)
2201
0
    {
2202
0
        return true;
2203
0
    }
2204
2205
0
    const auto ProcessInConstructionValues = [&inConstructionValues]()
2206
0
    {
2207
0
        for (auto &[arg, value] : inConstructionValues)
2208
0
        {
2209
0
            if (arg->GetType() == GAAT_STRING_LIST)
2210
0
            {
2211
0
                if (!arg->Set(std::get<std::vector<std::string>>(
2212
0
                        inConstructionValues[arg])))
2213
0
                {
2214
0
                    return false;
2215
0
                }
2216
0
            }
2217
0
            else if (arg->GetType() == GAAT_INTEGER_LIST)
2218
0
            {
2219
0
                if (!arg->Set(
2220
0
                        std::get<std::vector<int>>(inConstructionValues[arg])))
2221
0
                {
2222
0
                    return false;
2223
0
                }
2224
0
            }
2225
0
            else if (arg->GetType() == GAAT_REAL_LIST)
2226
0
            {
2227
0
                if (!arg->Set(std::get<std::vector<double>>(
2228
0
                        inConstructionValues[arg])))
2229
0
                {
2230
0
                    return false;
2231
0
                }
2232
0
            }
2233
0
            else if (arg->GetType() == GAAT_DATASET_LIST)
2234
0
            {
2235
0
                if (!arg->Set(
2236
0
                        std::move(std::get<std::vector<GDALArgDatasetValue>>(
2237
0
                            inConstructionValues[arg]))))
2238
0
                {
2239
0
                    return false;
2240
0
                }
2241
0
            }
2242
0
        }
2243
0
        return true;
2244
0
    };
2245
2246
    // Process positional arguments that have not been set through their
2247
    // option name.
2248
0
    size_t i = 0;
2249
0
    size_t iCurPosArg = 0;
2250
2251
    // Special case for <INPUT> <AUXILIARY>... <OUTPUT>
2252
0
    if (m_positionalArgs.size() == 3 &&
2253
0
        (m_positionalArgs[0]->IsRequired() ||
2254
0
         m_positionalArgs[0]->GetMinCount() == 1) &&
2255
0
        m_positionalArgs[0]->GetMaxCount() == 1 &&
2256
0
        (m_positionalArgs[1]->IsRequired() ||
2257
0
         m_positionalArgs[1]->GetMinCount() == 1) &&
2258
        /* Second argument may have several occurrences */
2259
0
        m_positionalArgs[1]->GetMaxCount() >= 1 &&
2260
0
        (m_positionalArgs[2]->IsRequired() ||
2261
0
         m_positionalArgs[2]->GetMinCount() == 1) &&
2262
0
        m_positionalArgs[2]->GetMaxCount() == 1 &&
2263
0
        !m_positionalArgs[0]->IsExplicitlySet() &&
2264
0
        !m_positionalArgs[1]->IsExplicitlySet() &&
2265
0
        !m_positionalArgs[2]->IsExplicitlySet())
2266
0
    {
2267
0
        if (lArgs.size() - i < 3)
2268
0
        {
2269
0
            ReportError(CE_Failure, CPLE_AppDefined,
2270
0
                        "Not enough positional values.");
2271
0
            return false;
2272
0
        }
2273
0
        bool ok = ParseArgument(m_positionalArgs[0],
2274
0
                                m_positionalArgs[0]->GetName().c_str(),
2275
0
                                lArgs[i], inConstructionValues);
2276
0
        if (ok)
2277
0
        {
2278
0
            ++i;
2279
0
            for (; i + 1 < lArgs.size() && ok; ++i)
2280
0
            {
2281
0
                ok = ParseArgument(m_positionalArgs[1],
2282
0
                                   m_positionalArgs[1]->GetName().c_str(),
2283
0
                                   lArgs[i], inConstructionValues);
2284
0
            }
2285
0
        }
2286
0
        if (ok)
2287
0
        {
2288
0
            ok = ParseArgument(m_positionalArgs[2],
2289
0
                               m_positionalArgs[2]->GetName().c_str(), lArgs[i],
2290
0
                               inConstructionValues);
2291
0
            ++i;
2292
0
        }
2293
0
        if (!ok)
2294
0
        {
2295
0
            ProcessInConstructionValues();
2296
0
            return false;
2297
0
        }
2298
0
    }
2299
2300
0
    if (m_inputDatasetCanBeOmitted && m_positionalArgs.size() >= 1 &&
2301
0
        !m_positionalArgs[0]->IsExplicitlySet() &&
2302
0
        m_positionalArgs[0]->GetName() == GDAL_ARG_NAME_INPUT &&
2303
0
        (m_positionalArgs[0]->GetType() == GAAT_DATASET ||
2304
0
         m_positionalArgs[0]->GetType() == GAAT_DATASET_LIST))
2305
0
    {
2306
0
        ++iCurPosArg;
2307
0
    }
2308
2309
0
    while (i < lArgs.size() && iCurPosArg < m_positionalArgs.size())
2310
0
    {
2311
0
        GDALAlgorithmArg *arg = m_positionalArgs[iCurPosArg];
2312
0
        while (arg->IsExplicitlySet())
2313
0
        {
2314
0
            ++iCurPosArg;
2315
0
            if (iCurPosArg == m_positionalArgs.size())
2316
0
                break;
2317
0
            arg = m_positionalArgs[iCurPosArg];
2318
0
        }
2319
0
        if (iCurPosArg == m_positionalArgs.size())
2320
0
        {
2321
0
            break;
2322
0
        }
2323
0
        if (GDALAlgorithmArgTypeIsList(arg->GetType()) &&
2324
0
            arg->GetMinCount() != arg->GetMaxCount())
2325
0
        {
2326
0
            if (iCurPosArg == 0)
2327
0
            {
2328
0
                size_t nCountAtEnd = 0;
2329
0
                for (size_t j = 1; j < m_positionalArgs.size(); j++)
2330
0
                {
2331
0
                    const auto *otherArg = m_positionalArgs[j];
2332
0
                    if (GDALAlgorithmArgTypeIsList(otherArg->GetType()))
2333
0
                    {
2334
0
                        if (otherArg->GetMinCount() != otherArg->GetMaxCount())
2335
0
                        {
2336
0
                            ReportError(
2337
0
                                CE_Failure, CPLE_AppDefined,
2338
0
                                "Ambiguity in definition of positional "
2339
0
                                "argument "
2340
0
                                "'%s' given it has a varying number of values, "
2341
0
                                "but follows argument '%s' which also has a "
2342
0
                                "varying number of values",
2343
0
                                otherArg->GetName().c_str(),
2344
0
                                arg->GetName().c_str());
2345
0
                            ProcessInConstructionValues();
2346
0
                            return false;
2347
0
                        }
2348
0
                        nCountAtEnd += otherArg->GetMinCount();
2349
0
                    }
2350
0
                    else
2351
0
                    {
2352
0
                        if (!otherArg->IsRequired())
2353
0
                        {
2354
0
                            ReportError(
2355
0
                                CE_Failure, CPLE_AppDefined,
2356
0
                                "Ambiguity in definition of positional "
2357
0
                                "argument "
2358
0
                                "'%s', given it is not required but follows "
2359
0
                                "argument '%s' which has a varying number of "
2360
0
                                "values",
2361
0
                                otherArg->GetName().c_str(),
2362
0
                                arg->GetName().c_str());
2363
0
                            ProcessInConstructionValues();
2364
0
                            return false;
2365
0
                        }
2366
0
                        nCountAtEnd++;
2367
0
                    }
2368
0
                }
2369
0
                if (lArgs.size() < nCountAtEnd)
2370
0
                {
2371
0
                    ReportError(CE_Failure, CPLE_AppDefined,
2372
0
                                "Not enough positional values.");
2373
0
                    ProcessInConstructionValues();
2374
0
                    return false;
2375
0
                }
2376
0
                for (; i < lArgs.size() - nCountAtEnd; ++i)
2377
0
                {
2378
0
                    if (!ParseArgument(arg, arg->GetName().c_str(), lArgs[i],
2379
0
                                       inConstructionValues))
2380
0
                    {
2381
0
                        ProcessInConstructionValues();
2382
0
                        return false;
2383
0
                    }
2384
0
                }
2385
0
            }
2386
0
            else if (iCurPosArg == m_positionalArgs.size() - 1)
2387
0
            {
2388
0
                for (; i < lArgs.size(); ++i)
2389
0
                {
2390
0
                    if (!ParseArgument(arg, arg->GetName().c_str(), lArgs[i],
2391
0
                                       inConstructionValues))
2392
0
                    {
2393
0
                        ProcessInConstructionValues();
2394
0
                        return false;
2395
0
                    }
2396
0
                }
2397
0
            }
2398
0
            else
2399
0
            {
2400
0
                ReportError(CE_Failure, CPLE_AppDefined,
2401
0
                            "Ambiguity in definition of positional arguments: "
2402
0
                            "arguments with varying number of values must be "
2403
0
                            "first or last one.");
2404
0
                return false;
2405
0
            }
2406
0
        }
2407
0
        else
2408
0
        {
2409
0
            if (lArgs.size() - i < static_cast<size_t>(arg->GetMaxCount()))
2410
0
            {
2411
0
                ReportError(CE_Failure, CPLE_AppDefined,
2412
0
                            "Not enough positional values.");
2413
0
                return false;
2414
0
            }
2415
0
            const size_t iMax = i + arg->GetMaxCount();
2416
0
            for (; i < iMax; ++i)
2417
0
            {
2418
0
                if (!ParseArgument(arg, arg->GetName().c_str(), lArgs[i],
2419
0
                                   inConstructionValues))
2420
0
                {
2421
0
                    ProcessInConstructionValues();
2422
0
                    return false;
2423
0
                }
2424
0
            }
2425
0
        }
2426
0
        ++iCurPosArg;
2427
0
    }
2428
2429
0
    if (i < lArgs.size())
2430
0
    {
2431
0
        ReportError(CE_Failure, CPLE_AppDefined,
2432
0
                    "Positional values starting at '%s' are not expected.",
2433
0
                    lArgs[i].c_str());
2434
0
        return false;
2435
0
    }
2436
2437
0
    if (!ProcessInConstructionValues())
2438
0
    {
2439
0
        return false;
2440
0
    }
2441
2442
    // Skip to first unset positional argument.
2443
0
    while (iCurPosArg < m_positionalArgs.size() &&
2444
0
           m_positionalArgs[iCurPosArg]->IsExplicitlySet())
2445
0
    {
2446
0
        ++iCurPosArg;
2447
0
    }
2448
    // Check if this positional argument is required.
2449
0
    if (iCurPosArg < m_positionalArgs.size() && !helpValueRequested &&
2450
0
        (GDALAlgorithmArgTypeIsList(m_positionalArgs[iCurPosArg]->GetType())
2451
0
             ? m_positionalArgs[iCurPosArg]->GetMinCount() > 0
2452
0
             : m_positionalArgs[iCurPosArg]->IsRequired()))
2453
0
    {
2454
0
        ReportError(CE_Failure, CPLE_AppDefined,
2455
0
                    "Positional arguments starting at '%s' have not been "
2456
0
                    "specified.",
2457
0
                    m_positionalArgs[iCurPosArg]->GetMetaVar().c_str());
2458
0
        return false;
2459
0
    }
2460
2461
0
    if (m_calledFromCommandLine)
2462
0
    {
2463
0
        for (auto &arg : m_args)
2464
0
        {
2465
0
            if (arg->IsExplicitlySet() &&
2466
0
                ((arg->GetType() == GAAT_STRING &&
2467
0
                  arg->Get<std::string>() == "?") ||
2468
0
                 (arg->GetType() == GAAT_STRING_LIST &&
2469
0
                  arg->Get<std::vector<std::string>>().size() == 1 &&
2470
0
                  arg->Get<std::vector<std::string>>()[0] == "?")))
2471
0
            {
2472
0
                {
2473
0
                    CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
2474
0
                    ValidateArguments();
2475
0
                }
2476
2477
0
                auto choices = arg->GetChoices();
2478
0
                if (choices.empty())
2479
0
                    choices = arg->GetAutoCompleteChoices(std::string());
2480
0
                if (!choices.empty())
2481
0
                {
2482
0
                    if (choices.size() == 1)
2483
0
                    {
2484
0
                        ReportError(
2485
0
                            CE_Failure, CPLE_AppDefined,
2486
0
                            "Single potential value for argument '%s' is '%s'",
2487
0
                            arg->GetName().c_str(), choices.front().c_str());
2488
0
                    }
2489
0
                    else
2490
0
                    {
2491
0
                        std::string msg("Potential values for argument '");
2492
0
                        msg += arg->GetName();
2493
0
                        msg += "' are:";
2494
0
                        for (const auto &v : choices)
2495
0
                        {
2496
0
                            msg += "\n- ";
2497
0
                            msg += v;
2498
0
                        }
2499
0
                        ReportError(CE_Failure, CPLE_AppDefined, "%s",
2500
0
                                    msg.c_str());
2501
0
                    }
2502
0
                    return false;
2503
0
                }
2504
0
            }
2505
0
        }
2506
0
    }
2507
2508
0
    return m_skipValidationInParseCommandLine || ValidateArguments();
2509
0
}
2510
2511
/************************************************************************/
2512
/*                     GDALAlgorithm::ReportError()                     */
2513
/************************************************************************/
2514
2515
//! @cond Doxygen_Suppress
2516
void GDALAlgorithm::ReportError(CPLErr eErrClass, CPLErrorNum err_no,
2517
                                const char *fmt, ...) const
2518
0
{
2519
0
    va_list args;
2520
0
    va_start(args, fmt);
2521
0
    CPLError(eErrClass, err_no, "%s",
2522
0
             std::string(m_name)
2523
0
                 .append(": ")
2524
0
                 .append(CPLString().vPrintf(fmt, args))
2525
0
                 .c_str());
2526
0
    va_end(args);
2527
0
}
2528
2529
//! @endcond
2530
2531
/************************************************************************/
2532
/*                  GDALAlgorithm::ProcessDatasetArg()                  */
2533
/************************************************************************/
2534
2535
bool GDALAlgorithm::ProcessDatasetArg(GDALAlgorithmArg *arg,
2536
                                      GDALAlgorithm *algForOutput)
2537
0
{
2538
0
    bool ret = true;
2539
2540
0
    const auto updateArg = algForOutput->GetArg(GDAL_ARG_NAME_UPDATE);
2541
0
    const bool hasUpdateArg = updateArg && updateArg->GetType() == GAAT_BOOLEAN;
2542
0
    const bool update = hasUpdateArg && updateArg->Get<bool>();
2543
0
    const auto overwriteArg = algForOutput->GetArg(GDAL_ARG_NAME_OVERWRITE);
2544
0
    const bool overwrite =
2545
0
        (arg->IsOutput() && overwriteArg &&
2546
0
         overwriteArg->GetType() == GAAT_BOOLEAN && overwriteArg->Get<bool>());
2547
0
    auto outputArg = algForOutput->GetArg(GDAL_ARG_NAME_OUTPUT);
2548
0
    auto &val = [arg]() -> GDALArgDatasetValue &
2549
0
    {
2550
0
        if (arg->GetType() == GAAT_DATASET_LIST)
2551
0
            return arg->Get<std::vector<GDALArgDatasetValue>>()[0];
2552
0
        else
2553
0
            return arg->Get<GDALArgDatasetValue>();
2554
0
    }();
2555
0
    const bool onlyInputSpecifiedInUpdateAndOutputNotRequired =
2556
0
        arg->GetName() == GDAL_ARG_NAME_INPUT && outputArg &&
2557
0
        !outputArg->IsExplicitlySet() && !outputArg->IsRequired() && update &&
2558
0
        !overwrite;
2559
0
    if (!val.GetDatasetRef() && !val.IsNameSet())
2560
0
    {
2561
0
        ReportError(CE_Failure, CPLE_AppDefined,
2562
0
                    "Argument '%s' has no dataset object or dataset name.",
2563
0
                    arg->GetName().c_str());
2564
0
        ret = false;
2565
0
    }
2566
0
    else if (val.GetDatasetRef() && !CheckCanSetDatasetObject(arg))
2567
0
    {
2568
0
        return false;
2569
0
    }
2570
0
    else if (m_inputDatasetCanBeOmitted &&
2571
0
             val.GetName() == GDAL_DATASET_PIPELINE_PLACEHOLDER_VALUE &&
2572
0
             !arg->IsOutput())
2573
0
    {
2574
0
        return true;
2575
0
    }
2576
0
    else if (!val.GetDatasetRef() && arg->AutoOpenDataset() &&
2577
0
             (!arg->IsOutput() || (arg == outputArg && update && !overwrite) ||
2578
0
              onlyInputSpecifiedInUpdateAndOutputNotRequired))
2579
0
    {
2580
0
        int flags = arg->GetDatasetType();
2581
0
        bool assignToOutputArg = false;
2582
2583
        // Check if input and output parameters point to the same
2584
        // filename (for vector datasets)
2585
0
        if (arg->GetName() == GDAL_ARG_NAME_INPUT && update && !overwrite &&
2586
0
            outputArg && outputArg->GetType() == GAAT_DATASET)
2587
0
        {
2588
0
            auto &outputVal = outputArg->Get<GDALArgDatasetValue>();
2589
0
            if (!outputVal.GetDatasetRef() &&
2590
0
                outputVal.GetName() == val.GetName() &&
2591
0
                (outputArg->GetDatasetInputFlags() & GADV_OBJECT) != 0)
2592
0
            {
2593
0
                assignToOutputArg = true;
2594
0
                flags |= GDAL_OF_UPDATE | GDAL_OF_VERBOSE_ERROR;
2595
0
            }
2596
0
            else if (onlyInputSpecifiedInUpdateAndOutputNotRequired)
2597
0
            {
2598
0
                flags |= GDAL_OF_UPDATE | GDAL_OF_VERBOSE_ERROR;
2599
0
            }
2600
0
        }
2601
2602
0
        if (!arg->IsOutput() || arg->GetDatasetInputFlags() == GADV_NAME)
2603
0
            flags |= GDAL_OF_VERBOSE_ERROR;
2604
0
        if ((arg == outputArg || !outputArg) && update)
2605
0
            flags |= GDAL_OF_UPDATE | GDAL_OF_VERBOSE_ERROR;
2606
2607
0
        const auto readOnlyArg = GetArg(GDAL_ARG_NAME_READ_ONLY);
2608
0
        const bool readOnly =
2609
0
            (readOnlyArg && readOnlyArg->GetType() == GAAT_BOOLEAN &&
2610
0
             readOnlyArg->Get<bool>());
2611
0
        if (readOnly)
2612
0
            flags &= ~GDAL_OF_UPDATE;
2613
2614
0
        CPLStringList aosOpenOptions;
2615
0
        CPLStringList aosAllowedDrivers;
2616
0
        if (arg->IsInput())
2617
0
        {
2618
0
            if (arg == outputArg)
2619
0
            {
2620
0
                if (update && !overwrite)
2621
0
                {
2622
0
                    const auto ooArg = GetArg(GDAL_ARG_NAME_OUTPUT_OPEN_OPTION);
2623
0
                    if (ooArg && ooArg->GetType() == GAAT_STRING_LIST)
2624
0
                        aosOpenOptions = CPLStringList(
2625
0
                            ooArg->Get<std::vector<std::string>>());
2626
0
                }
2627
0
            }
2628
0
            else
2629
0
            {
2630
0
                const auto ooArg = GetArg(GDAL_ARG_NAME_OPEN_OPTION);
2631
0
                if (ooArg && ooArg->GetType() == GAAT_STRING_LIST)
2632
0
                    aosOpenOptions =
2633
0
                        CPLStringList(ooArg->Get<std::vector<std::string>>());
2634
2635
0
                const auto ifArg = GetArg(GDAL_ARG_NAME_INPUT_FORMAT);
2636
0
                if (ifArg && ifArg->GetType() == GAAT_STRING_LIST)
2637
0
                    aosAllowedDrivers =
2638
0
                        CPLStringList(ifArg->Get<std::vector<std::string>>());
2639
0
            }
2640
0
        }
2641
2642
0
        std::string osDatasetName = val.GetName();
2643
0
        if (!m_referencePath.empty())
2644
0
        {
2645
0
            osDatasetName = GDALDataset::BuildFilename(
2646
0
                osDatasetName.c_str(), m_referencePath.c_str(), true);
2647
0
        }
2648
0
        if (osDatasetName == "-" && (flags & GDAL_OF_UPDATE) == 0)
2649
0
            osDatasetName = "/vsistdin/";
2650
2651
        // Handle special case of overview delete in GTiff which would fail
2652
        // if it is COG without IGNORE_COG_LAYOUT_BREAK=YES open option.
2653
0
        if ((flags & GDAL_OF_UPDATE) != 0 && m_callPath.size() == 4 &&
2654
0
            m_callPath[2] == "overview" && m_callPath[3] == "delete" &&
2655
0
            aosOpenOptions.FetchNameValue("IGNORE_COG_LAYOUT_BREAK") == nullptr)
2656
0
        {
2657
0
            CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
2658
0
            GDALDriverH hDrv =
2659
0
                GDALIdentifyDriver(osDatasetName.c_str(), nullptr);
2660
0
            if (hDrv && EQUAL(GDALGetDescription(hDrv), "GTiff"))
2661
0
            {
2662
                // Cleaning does not break COG layout
2663
0
                aosOpenOptions.SetNameValue("IGNORE_COG_LAYOUT_BREAK", "YES");
2664
0
            }
2665
0
        }
2666
2667
0
        auto oIter = m_oMapDatasetNameToDataset.find(osDatasetName.c_str());
2668
0
        GDALDataset *poDS;
2669
0
        {
2670
            // The PostGISRaster may emit an error message, that is not
2671
            // relevant, if it is the vector driver that was intended
2672
0
            std::unique_ptr<CPLErrorStateBackuper> poBackuper;
2673
0
            if (cpl::starts_with(osDatasetName, "PG:") &&
2674
0
                (flags & (GDAL_OF_RASTER | GDAL_OF_VECTOR)) != 0)
2675
0
            {
2676
0
                poBackuper = std::make_unique<CPLErrorStateBackuper>(
2677
0
                    CPLQuietErrorHandler);
2678
0
            }
2679
2680
0
            CPL_IGNORE_RET_VAL(poBackuper);
2681
0
            poDS = oIter != m_oMapDatasetNameToDataset.end()
2682
0
                       ? oIter->second
2683
0
                       : GDALDataset::Open(osDatasetName.c_str(), flags,
2684
0
                                           aosAllowedDrivers.List(),
2685
0
                                           aosOpenOptions.List());
2686
2687
            // Retry with PostGIS vector driver
2688
0
            if (!poDS && poBackuper &&
2689
0
                GetGDALDriverManager()->GetDriverByName("PostGISRaster") &&
2690
0
                aosAllowedDrivers.empty() && aosOpenOptions.empty())
2691
0
            {
2692
0
                poBackuper.reset();
2693
0
                poDS = GDALDataset::Open(
2694
0
                    osDatasetName.c_str(), flags & ~GDAL_OF_RASTER,
2695
0
                    aosAllowedDrivers.List(), aosOpenOptions.List());
2696
0
            }
2697
0
        }
2698
2699
0
        if (poDS)
2700
0
        {
2701
0
            if (oIter != m_oMapDatasetNameToDataset.end())
2702
0
            {
2703
0
                if (arg->GetType() == GAAT_DATASET)
2704
0
                    arg->Get<GDALArgDatasetValue>().Set(poDS->GetDescription());
2705
0
                poDS->Reference();
2706
0
                m_oMapDatasetNameToDataset.erase(oIter);
2707
0
            }
2708
2709
            // A bit of a hack for situations like 'gdal raster clip --like "PG:..."'
2710
            // where the PG: dataset will be first opened with the PostGISRaster
2711
            // driver whereas the PostgreSQL (vector) one is actually wanted.
2712
0
            if (poDS->GetRasterCount() == 0 && (flags & GDAL_OF_RASTER) != 0 &&
2713
0
                (flags & GDAL_OF_VECTOR) != 0 && aosAllowedDrivers.empty() &&
2714
0
                aosOpenOptions.empty())
2715
0
            {
2716
0
                auto poDrv = poDS->GetDriver();
2717
0
                if (poDrv && EQUAL(poDrv->GetDescription(), "PostGISRaster"))
2718
0
                {
2719
                    // Retry with PostgreSQL (vector) driver
2720
0
                    std::unique_ptr<GDALDataset> poTmpDS(GDALDataset::Open(
2721
0
                        osDatasetName.c_str(), flags & ~GDAL_OF_RASTER));
2722
0
                    if (poTmpDS)
2723
0
                    {
2724
0
                        poDS->ReleaseRef();
2725
0
                        poDS = poTmpDS.release();
2726
0
                    }
2727
0
                }
2728
0
            }
2729
2730
0
            if (assignToOutputArg)
2731
0
            {
2732
                // Avoid opening twice the same datasource if it is both
2733
                // the input and output.
2734
                // Known to cause problems with at least FGdb, SQLite
2735
                // and GPKG drivers. See #4270
2736
                // Restrict to those 3 drivers. For example it is known
2737
                // to break with the PG driver due to the way it
2738
                // manages transactions.
2739
0
                auto poDriver = poDS->GetDriver();
2740
0
                if (poDriver && (EQUAL(poDriver->GetDescription(), "FileGDB") ||
2741
0
                                 EQUAL(poDriver->GetDescription(), "SQLite") ||
2742
0
                                 EQUAL(poDriver->GetDescription(), "GPKG")))
2743
0
                {
2744
0
                    outputArg->Get<GDALArgDatasetValue>().Set(poDS);
2745
0
                }
2746
0
            }
2747
0
            val.SetDatasetOpenedByAlgorithm();
2748
0
            val.Set(poDS);
2749
0
            poDS->ReleaseRef();
2750
0
        }
2751
0
        else
2752
0
        {
2753
0
            ret = false;
2754
0
        }
2755
0
    }
2756
2757
    // Deal with overwriting the output dataset
2758
0
    if (ret && arg == outputArg && val.GetDatasetRef() == nullptr)
2759
0
    {
2760
0
        const auto appendArg = algForOutput->GetArg(GDAL_ARG_NAME_APPEND);
2761
0
        const bool hasAppendArg =
2762
0
            appendArg && appendArg->GetType() == GAAT_BOOLEAN;
2763
0
        const bool append = (hasAppendArg && appendArg->Get<bool>());
2764
0
        if (!append)
2765
0
        {
2766
            // If outputting to MEM, do not try to erase a real file of the same name!
2767
0
            const auto outputFormatArg =
2768
0
                algForOutput->GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
2769
0
            if (!(outputFormatArg &&
2770
0
                  outputFormatArg->GetType() == GAAT_STRING &&
2771
0
                  (EQUAL(outputFormatArg->Get<std::string>().c_str(), "MEM") ||
2772
0
                   EQUAL(outputFormatArg->Get<std::string>().c_str(),
2773
0
                         "stream") ||
2774
0
                   EQUAL(outputFormatArg->Get<std::string>().c_str(),
2775
0
                         "Memory"))))
2776
0
            {
2777
0
                const char *pszType = "";
2778
0
                GDALDriver *poDriver = nullptr;
2779
0
                if (!val.GetName().empty() &&
2780
0
                    GDALDoesFileOrDatasetExist(val.GetName().c_str(), &pszType,
2781
0
                                               &poDriver))
2782
0
                {
2783
0
                    if (!overwrite)
2784
0
                    {
2785
0
                        std::string options;
2786
0
                        if (algForOutput->GetArg(GDAL_ARG_NAME_OVERWRITE_LAYER))
2787
0
                        {
2788
0
                            options += "--";
2789
0
                            options += GDAL_ARG_NAME_OVERWRITE_LAYER;
2790
0
                        }
2791
0
                        if (hasAppendArg)
2792
0
                        {
2793
0
                            if (!options.empty())
2794
0
                                options += '/';
2795
0
                            options += "--";
2796
0
                            options += GDAL_ARG_NAME_APPEND;
2797
0
                        }
2798
0
                        if (hasUpdateArg)
2799
0
                        {
2800
0
                            if (!options.empty())
2801
0
                                options += '/';
2802
0
                            options += "--";
2803
0
                            options += GDAL_ARG_NAME_UPDATE;
2804
0
                        }
2805
2806
0
                        if (poDriver)
2807
0
                        {
2808
0
                            const char *pszPrefix = poDriver->GetMetadataItem(
2809
0
                                GDAL_DMD_CONNECTION_PREFIX);
2810
0
                            if (pszPrefix &&
2811
0
                                STARTS_WITH_CI(val.GetName().c_str(),
2812
0
                                               pszPrefix))
2813
0
                            {
2814
0
                                bool bExists = false;
2815
0
                                {
2816
0
                                    CPLErrorStateBackuper oBackuper(
2817
0
                                        CPLQuietErrorHandler);
2818
0
                                    bExists = std::unique_ptr<GDALDataset>(
2819
0
                                                  GDALDataset::Open(
2820
0
                                                      val.GetName().c_str())) !=
2821
0
                                              nullptr;
2822
0
                                }
2823
0
                                if (bExists)
2824
0
                                {
2825
0
                                    if (!options.empty())
2826
0
                                        options = " You may specify the " +
2827
0
                                                  options + " option.";
2828
0
                                    ReportError(CE_Failure, CPLE_AppDefined,
2829
0
                                                "%s '%s' already exists.%s",
2830
0
                                                pszType, val.GetName().c_str(),
2831
0
                                                options.c_str());
2832
0
                                    return false;
2833
0
                                }
2834
2835
0
                                return true;
2836
0
                            }
2837
0
                        }
2838
2839
0
                        if (!options.empty())
2840
0
                            options = '/' + options;
2841
0
                        ReportError(
2842
0
                            CE_Failure, CPLE_AppDefined,
2843
0
                            "%s '%s' already exists. You may specify the "
2844
0
                            "--overwrite%s option.",
2845
0
                            pszType, val.GetName().c_str(), options.c_str());
2846
0
                        return false;
2847
0
                    }
2848
0
                    else if (EQUAL(pszType, "File"))
2849
0
                    {
2850
0
                        VSIUnlink(val.GetName().c_str());
2851
0
                    }
2852
0
                    else if (EQUAL(pszType, "Directory"))
2853
0
                    {
2854
                        // We don't want the user to accidentally erase a non-GDAL dataset
2855
0
                        ReportError(CE_Failure, CPLE_AppDefined,
2856
0
                                    "Directory '%s' already exists, but is not "
2857
0
                                    "recognized as a valid GDAL dataset. "
2858
0
                                    "Please manually delete it before retrying",
2859
0
                                    val.GetName().c_str());
2860
0
                        return false;
2861
0
                    }
2862
0
                    else if (poDriver)
2863
0
                    {
2864
0
                        CPLStringList aosDrivers;
2865
0
                        aosDrivers.AddString(poDriver->GetDescription());
2866
0
                        CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
2867
0
                        GDALDriver::QuietDelete(val.GetName().c_str(),
2868
0
                                                aosDrivers.List());
2869
0
                    }
2870
0
                }
2871
0
            }
2872
0
        }
2873
0
    }
2874
2875
    // If outputting to stdout, automatically turn off progress bar
2876
0
    if (arg == outputArg && val.GetName() == "/vsistdout/")
2877
0
    {
2878
0
        auto quietArg = GetArg(GDAL_ARG_NAME_QUIET);
2879
0
        if (quietArg && quietArg->GetType() == GAAT_BOOLEAN)
2880
0
            quietArg->Set(true);
2881
0
    }
2882
2883
0
    return ret;
2884
0
}
2885
2886
/************************************************************************/
2887
/*                  GDALAlgorithm::ValidateArguments()                  */
2888
/************************************************************************/
2889
2890
bool GDALAlgorithm::ValidateArguments()
2891
0
{
2892
0
    if (m_selectedSubAlg)
2893
0
        return m_selectedSubAlg->ValidateArguments();
2894
2895
0
    if (m_specialActionRequested)
2896
0
        return true;
2897
2898
0
    m_arbitraryLongNameArgsAllowed = false;
2899
2900
    // If only --output=format=MEM/stream is specified and not --output,
2901
    // then set empty name for --output.
2902
0
    auto outputArg = GetArg(GDAL_ARG_NAME_OUTPUT);
2903
0
    auto outputFormatArg = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
2904
0
    if (outputArg && outputFormatArg && outputFormatArg->IsExplicitlySet() &&
2905
0
        !outputArg->IsExplicitlySet() &&
2906
0
        outputFormatArg->GetType() == GAAT_STRING &&
2907
0
        (EQUAL(outputFormatArg->Get<std::string>().c_str(), "MEM") ||
2908
0
         EQUAL(outputFormatArg->Get<std::string>().c_str(), "stream")) &&
2909
0
        outputArg->GetType() == GAAT_DATASET &&
2910
0
        (outputArg->GetDatasetInputFlags() & GADV_NAME))
2911
0
    {
2912
0
        outputArg->Get<GDALArgDatasetValue>().Set("");
2913
0
    }
2914
2915
    // The method may emit several errors if several constraints are not met.
2916
0
    bool ret = true;
2917
0
    std::map<std::string, std::string> mutualExclusionGroupUsed;
2918
0
    for (auto &arg : m_args)
2919
0
    {
2920
        // Check mutually exclusive arguments
2921
0
        if (arg->IsExplicitlySet())
2922
0
        {
2923
0
            const auto &mutualExclusionGroup = arg->GetMutualExclusionGroup();
2924
0
            if (!mutualExclusionGroup.empty())
2925
0
            {
2926
0
                auto oIter =
2927
0
                    mutualExclusionGroupUsed.find(mutualExclusionGroup);
2928
0
                if (oIter != mutualExclusionGroupUsed.end())
2929
0
                {
2930
0
                    ret = false;
2931
0
                    ReportError(
2932
0
                        CE_Failure, CPLE_AppDefined,
2933
0
                        "Argument '%s' is mutually exclusive with '%s'.",
2934
0
                        arg->GetName().c_str(), oIter->second.c_str());
2935
0
                }
2936
0
                else
2937
0
                {
2938
0
                    mutualExclusionGroupUsed[mutualExclusionGroup] =
2939
0
                        arg->GetName();
2940
0
                }
2941
0
            }
2942
0
        }
2943
2944
0
        if (arg->IsRequired() && !arg->IsExplicitlySet() &&
2945
0
            !arg->HasDefaultValue())
2946
0
        {
2947
0
            bool emitError = true;
2948
0
            const auto &mutualExclusionGroup = arg->GetMutualExclusionGroup();
2949
0
            if (!mutualExclusionGroup.empty())
2950
0
            {
2951
0
                for (const auto &otherArg : m_args)
2952
0
                {
2953
0
                    if (otherArg->GetMutualExclusionGroup() ==
2954
0
                            mutualExclusionGroup &&
2955
0
                        otherArg->IsExplicitlySet())
2956
0
                    {
2957
0
                        emitError = false;
2958
0
                        break;
2959
0
                    }
2960
0
                }
2961
0
            }
2962
0
            if (emitError && !(m_inputDatasetCanBeOmitted &&
2963
0
                               arg->GetName() == GDAL_ARG_NAME_INPUT &&
2964
0
                               (arg->GetType() == GAAT_DATASET ||
2965
0
                                arg->GetType() == GAAT_DATASET_LIST)))
2966
0
            {
2967
0
                ReportError(CE_Failure, CPLE_AppDefined,
2968
0
                            "Required argument '%s' has not been specified.",
2969
0
                            arg->GetName().c_str());
2970
0
                ret = false;
2971
0
            }
2972
0
        }
2973
0
        else if (arg->IsExplicitlySet() && arg->GetType() == GAAT_DATASET)
2974
0
        {
2975
0
            if (!ProcessDatasetArg(arg.get(), this))
2976
0
                ret = false;
2977
0
        }
2978
2979
0
        if (arg->IsExplicitlySet() && arg->GetType() == GAAT_DATASET_LIST &&
2980
0
            arg->AutoOpenDataset())
2981
0
        {
2982
0
            auto &listVal = arg->Get<std::vector<GDALArgDatasetValue>>();
2983
0
            if (listVal.size() == 1)
2984
0
            {
2985
0
                if (!ProcessDatasetArg(arg.get(), this))
2986
0
                    ret = false;
2987
0
            }
2988
0
            else
2989
0
            {
2990
0
                for (auto &val : listVal)
2991
0
                {
2992
0
                    if (!val.GetDatasetRef() && val.GetName().empty())
2993
0
                    {
2994
0
                        ReportError(CE_Failure, CPLE_AppDefined,
2995
0
                                    "Argument '%s' has no dataset object or "
2996
0
                                    "dataset name.",
2997
0
                                    arg->GetName().c_str());
2998
0
                        ret = false;
2999
0
                    }
3000
0
                    else if (!val.GetDatasetRef())
3001
0
                    {
3002
0
                        int flags =
3003
0
                            arg->GetDatasetType() | GDAL_OF_VERBOSE_ERROR;
3004
3005
0
                        CPLStringList aosOpenOptions;
3006
0
                        CPLStringList aosAllowedDrivers;
3007
0
                        if (arg->GetName() == GDAL_ARG_NAME_INPUT)
3008
0
                        {
3009
0
                            const auto ooArg =
3010
0
                                GetArg(GDAL_ARG_NAME_OPEN_OPTION);
3011
0
                            if (ooArg && ooArg->GetType() == GAAT_STRING_LIST)
3012
0
                            {
3013
0
                                aosOpenOptions = CPLStringList(
3014
0
                                    ooArg->Get<std::vector<std::string>>());
3015
0
                            }
3016
3017
0
                            const auto ifArg =
3018
0
                                GetArg(GDAL_ARG_NAME_INPUT_FORMAT);
3019
0
                            if (ifArg && ifArg->GetType() == GAAT_STRING_LIST)
3020
0
                            {
3021
0
                                aosAllowedDrivers = CPLStringList(
3022
0
                                    ifArg->Get<std::vector<std::string>>());
3023
0
                            }
3024
3025
0
                            const auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
3026
0
                            if (updateArg &&
3027
0
                                updateArg->GetType() == GAAT_BOOLEAN &&
3028
0
                                updateArg->Get<bool>())
3029
0
                            {
3030
0
                                flags |= GDAL_OF_UPDATE;
3031
0
                            }
3032
0
                        }
3033
3034
0
                        auto poDS = std::unique_ptr<GDALDataset>(
3035
0
                            GDALDataset::Open(val.GetName().c_str(), flags,
3036
0
                                              aosAllowedDrivers.List(),
3037
0
                                              aosOpenOptions.List()));
3038
0
                        if (poDS)
3039
0
                        {
3040
0
                            val.Set(std::move(poDS));
3041
0
                        }
3042
0
                        else
3043
0
                        {
3044
0
                            ret = false;
3045
0
                        }
3046
0
                    }
3047
0
                }
3048
0
            }
3049
0
        }
3050
3051
0
        if (arg->IsExplicitlySet() && !arg->RunValidationActions())
3052
0
        {
3053
0
            ret = false;
3054
0
        }
3055
0
    }
3056
3057
0
    for (const auto &f : m_validationActions)
3058
0
    {
3059
0
        if (!f())
3060
0
            ret = false;
3061
0
    }
3062
3063
0
    return ret;
3064
0
}
3065
3066
/************************************************************************/
3067
/*                GDALAlgorithm::InstantiateSubAlgorithm                */
3068
/************************************************************************/
3069
3070
std::unique_ptr<GDALAlgorithm>
3071
GDALAlgorithm::InstantiateSubAlgorithm(const std::string &name,
3072
                                       bool suggestionAllowed) const
3073
0
{
3074
0
    auto ret = m_subAlgRegistry.Instantiate(name);
3075
0
    auto childCallPath = m_callPath;
3076
0
    childCallPath.push_back(name);
3077
0
    if (!ret)
3078
0
    {
3079
0
        ret = GDALGlobalAlgorithmRegistry::GetSingleton()
3080
0
                  .InstantiateDeclaredSubAlgorithm(childCallPath);
3081
0
    }
3082
0
    if (ret)
3083
0
    {
3084
0
        ret->SetCallPath(childCallPath);
3085
0
    }
3086
0
    else if (suggestionAllowed)
3087
0
    {
3088
0
        std::string bestCandidate;
3089
0
        size_t bestDistance = std::numeric_limits<size_t>::max();
3090
0
        for (const std::string &candidate : GetSubAlgorithmNames())
3091
0
        {
3092
0
            const size_t distance =
3093
0
                CPLLevenshteinDistance(name.c_str(), candidate.c_str(),
3094
0
                                       /* transpositionAllowed = */ true);
3095
0
            if (distance < bestDistance)
3096
0
            {
3097
0
                bestCandidate = candidate;
3098
0
                bestDistance = distance;
3099
0
            }
3100
0
            else if (distance == bestDistance)
3101
0
            {
3102
0
                bestCandidate.clear();
3103
0
            }
3104
0
        }
3105
0
        if (!bestCandidate.empty() && bestDistance <= 2)
3106
0
        {
3107
0
            CPLError(CE_Failure, CPLE_AppDefined,
3108
0
                     "Algorithm '%s' is unknown. Do you mean '%s'?",
3109
0
                     name.c_str(), bestCandidate.c_str());
3110
0
        }
3111
0
    }
3112
0
    return ret;
3113
0
}
3114
3115
/************************************************************************/
3116
/*            GDALAlgorithm::GetSuggestionForArgumentName()             */
3117
/************************************************************************/
3118
3119
std::string
3120
GDALAlgorithm::GetSuggestionForArgumentName(const std::string &osName) const
3121
0
{
3122
0
    if (osName.size() >= 3)
3123
0
    {
3124
0
        std::string bestCandidate;
3125
0
        size_t bestDistance = std::numeric_limits<size_t>::max();
3126
0
        for (const auto &[key, value] : m_mapLongNameToArg)
3127
0
        {
3128
0
            CPL_IGNORE_RET_VAL(value);
3129
0
            const size_t distance = CPLLevenshteinDistance(
3130
0
                osName.c_str(), key.c_str(), /* transpositionAllowed = */ true);
3131
0
            if (distance < bestDistance)
3132
0
            {
3133
0
                bestCandidate = key;
3134
0
                bestDistance = distance;
3135
0
            }
3136
0
            else if (distance == bestDistance)
3137
0
            {
3138
0
                bestCandidate.clear();
3139
0
            }
3140
0
        }
3141
0
        if (!bestCandidate.empty() &&
3142
0
            bestDistance <= (bestCandidate.size() >= 4U ? 2U : 1U))
3143
0
        {
3144
0
            return bestCandidate;
3145
0
        }
3146
0
    }
3147
0
    return std::string();
3148
0
}
3149
3150
/************************************************************************/
3151
/*         GDALAlgorithm::IsKnownOutputRelatedBooleanArgName()          */
3152
/************************************************************************/
3153
3154
/* static */
3155
bool GDALAlgorithm::IsKnownOutputRelatedBooleanArgName(std::string_view osName)
3156
0
{
3157
0
    return osName == GDAL_ARG_NAME_APPEND || osName == GDAL_ARG_NAME_UPDATE ||
3158
0
           osName == GDAL_ARG_NAME_OVERWRITE ||
3159
0
           osName == GDAL_ARG_NAME_OVERWRITE_LAYER;
3160
0
}
3161
3162
/************************************************************************/
3163
/*                   GDALAlgorithm::HasOutputString()                   */
3164
/************************************************************************/
3165
3166
bool GDALAlgorithm::HasOutputString() const
3167
0
{
3168
0
    auto outputStringArg = GetArg(GDAL_ARG_NAME_OUTPUT_STRING);
3169
0
    return outputStringArg && outputStringArg->IsOutput();
3170
0
}
3171
3172
/************************************************************************/
3173
/*                       GDALAlgorithm::GetArg()                        */
3174
/************************************************************************/
3175
3176
GDALAlgorithmArg *GDALAlgorithm::GetArg(const std::string &osName,
3177
                                        bool suggestionAllowed, bool isConst)
3178
0
{
3179
0
    const auto nPos = osName.find_first_not_of('-');
3180
0
    if (nPos == std::string::npos)
3181
0
        return nullptr;
3182
0
    std::string osKey = osName.substr(nPos);
3183
0
    {
3184
0
        const auto oIter = m_mapLongNameToArg.find(osKey);
3185
0
        if (oIter != m_mapLongNameToArg.end())
3186
0
            return oIter->second;
3187
0
    }
3188
0
    {
3189
0
        const auto oIter = m_mapShortNameToArg.find(osKey);
3190
0
        if (oIter != m_mapShortNameToArg.end())
3191
0
            return oIter->second;
3192
0
    }
3193
3194
0
    if (!isConst && m_arbitraryLongNameArgsAllowed)
3195
0
    {
3196
0
        const auto nDotPos = osKey.find('.');
3197
0
        const std::string osKeyEnd =
3198
0
            nDotPos == std::string::npos ? osKey : osKey.substr(nDotPos + 1);
3199
0
        if (IsKnownOutputRelatedBooleanArgName(osKeyEnd))
3200
0
        {
3201
0
            m_arbitraryLongNameArgsValuesBool.emplace_back(
3202
0
                std::make_unique<bool>());
3203
0
            AddArg(osKey, 0, std::string("User-provided argument ") + osKey,
3204
0
                   m_arbitraryLongNameArgsValuesBool.back().get())
3205
0
                .SetUserProvided();
3206
0
        }
3207
0
        else
3208
0
        {
3209
0
            const std::string osKeyInit = osKey;
3210
0
            if (osKey == "oo")
3211
0
                osKey = GDAL_ARG_NAME_OPEN_OPTION;
3212
0
            else if (osKey == "co")
3213
0
                osKey = GDAL_ARG_NAME_CREATION_OPTION;
3214
0
            else if (osKey == "of")
3215
0
                osKey = GDAL_ARG_NAME_OUTPUT_FORMAT;
3216
0
            else if (osKey == "if")
3217
0
                osKey = GDAL_ARG_NAME_INPUT_FORMAT;
3218
0
            m_arbitraryLongNameArgsValuesStr.emplace_back(
3219
0
                std::make_unique<std::string>());
3220
0
            auto &arg =
3221
0
                AddArg(osKey, 0, std::string("User-provided argument ") + osKey,
3222
0
                       m_arbitraryLongNameArgsValuesStr.back().get())
3223
0
                    .SetUserProvided();
3224
0
            if (osKey != osKeyInit)
3225
0
                arg.AddAlias(osKeyInit);
3226
0
        }
3227
0
        const auto oIter = m_mapLongNameToArg.find(osKey);
3228
0
        CPLAssert(oIter != m_mapLongNameToArg.end());
3229
0
        return oIter->second;
3230
0
    }
3231
3232
0
    if (suggestionAllowed)
3233
0
    {
3234
0
        const std::string bestCandidate = GetSuggestionForArgumentName(osName);
3235
0
        if (!bestCandidate.empty())
3236
0
        {
3237
0
            CPLError(CE_Failure, CPLE_AppDefined,
3238
0
                     "Argument '%s' is unknown. Do you mean '%s'?",
3239
0
                     osName.c_str(), bestCandidate.c_str());
3240
0
        }
3241
0
    }
3242
3243
0
    return nullptr;
3244
0
}
3245
3246
/************************************************************************/
3247
/*                     GDALAlgorithm::AddAliasFor()                     */
3248
/************************************************************************/
3249
3250
//! @cond Doxygen_Suppress
3251
void GDALAlgorithm::AddAliasFor(GDALInConstructionAlgorithmArg *arg,
3252
                                const std::string &alias)
3253
0
{
3254
0
    if (cpl::contains(m_mapLongNameToArg, alias))
3255
0
    {
3256
0
        ReportError(CE_Failure, CPLE_AppDefined, "Name '%s' already declared.",
3257
0
                    alias.c_str());
3258
0
    }
3259
0
    else
3260
0
    {
3261
0
        m_mapLongNameToArg[alias] = arg;
3262
0
    }
3263
0
}
3264
3265
//! @endcond
3266
3267
/************************************************************************/
3268
/*                GDALAlgorithm::AddShortNameAliasFor()                 */
3269
/************************************************************************/
3270
3271
//! @cond Doxygen_Suppress
3272
void GDALAlgorithm::AddShortNameAliasFor(GDALInConstructionAlgorithmArg *arg,
3273
                                         char shortNameAlias)
3274
0
{
3275
0
    std::string alias;
3276
0
    alias += shortNameAlias;
3277
0
    if (cpl::contains(m_mapShortNameToArg, alias))
3278
0
    {
3279
0
        ReportError(CE_Failure, CPLE_AppDefined,
3280
0
                    "Short name '%s' already declared.", alias.c_str());
3281
0
    }
3282
0
    else
3283
0
    {
3284
0
        m_mapShortNameToArg[alias] = arg;
3285
0
    }
3286
0
}
3287
3288
//! @endcond
3289
3290
/************************************************************************/
3291
/*                    GDALAlgorithm::SetPositional()                    */
3292
/************************************************************************/
3293
3294
//! @cond Doxygen_Suppress
3295
void GDALAlgorithm::SetPositional(GDALInConstructionAlgorithmArg *arg)
3296
0
{
3297
0
    CPLAssert(std::find(m_positionalArgs.begin(), m_positionalArgs.end(),
3298
0
                        arg) == m_positionalArgs.end());
3299
0
    m_positionalArgs.push_back(arg);
3300
0
}
3301
3302
//! @endcond
3303
3304
/************************************************************************/
3305
/*                  GDALAlgorithm::HasSubAlgorithms()                   */
3306
/************************************************************************/
3307
3308
bool GDALAlgorithm::HasSubAlgorithms() const
3309
0
{
3310
0
    if (!m_subAlgRegistry.empty())
3311
0
        return true;
3312
0
    return !GDALGlobalAlgorithmRegistry::GetSingleton()
3313
0
                .GetDeclaredSubAlgorithmNames(m_callPath)
3314
0
                .empty();
3315
0
}
3316
3317
/************************************************************************/
3318
/*                GDALAlgorithm::GetSubAlgorithmNames()                 */
3319
/************************************************************************/
3320
3321
std::vector<std::string> GDALAlgorithm::GetSubAlgorithmNames() const
3322
0
{
3323
0
    std::vector<std::string> ret = m_subAlgRegistry.GetNames();
3324
0
    const auto other = GDALGlobalAlgorithmRegistry::GetSingleton()
3325
0
                           .GetDeclaredSubAlgorithmNames(m_callPath);
3326
0
    ret.insert(ret.end(), other.begin(), other.end());
3327
0
    if (!other.empty())
3328
0
        std::sort(ret.begin(), ret.end());
3329
0
    return ret;
3330
0
}
3331
3332
/************************************************************************/
3333
/*                       GDALAlgorithm::AddArg()                        */
3334
/************************************************************************/
3335
3336
GDALInConstructionAlgorithmArg &
3337
GDALAlgorithm::AddArg(std::unique_ptr<GDALInConstructionAlgorithmArg> arg)
3338
0
{
3339
0
    auto argRaw = arg.get();
3340
0
    const auto &longName = argRaw->GetName();
3341
0
    if (!longName.empty())
3342
0
    {
3343
0
        if (longName[0] == '-')
3344
0
        {
3345
0
            ReportError(CE_Failure, CPLE_AppDefined,
3346
0
                        "Long name '%s' should not start with '-'",
3347
0
                        longName.c_str());
3348
0
        }
3349
0
        if (longName.find('=') != std::string::npos)
3350
0
        {
3351
0
            ReportError(CE_Failure, CPLE_AppDefined,
3352
0
                        "Long name '%s' should not contain a '=' character",
3353
0
                        longName.c_str());
3354
0
        }
3355
0
        if (cpl::contains(m_mapLongNameToArg, longName))
3356
0
        {
3357
0
            ReportError(CE_Failure, CPLE_AppDefined,
3358
0
                        "Long name '%s' already declared", longName.c_str());
3359
0
        }
3360
0
        m_mapLongNameToArg[longName] = argRaw;
3361
0
    }
3362
0
    const auto &shortName = argRaw->GetShortName();
3363
0
    if (!shortName.empty())
3364
0
    {
3365
0
        if (shortName.size() != 1 ||
3366
0
            !((shortName[0] >= 'a' && shortName[0] <= 'z') ||
3367
0
              (shortName[0] >= 'A' && shortName[0] <= 'Z') ||
3368
0
              (shortName[0] >= '0' && shortName[0] <= '9')))
3369
0
        {
3370
0
            ReportError(CE_Failure, CPLE_AppDefined,
3371
0
                        "Short name '%s' should be a single letter or digit",
3372
0
                        shortName.c_str());
3373
0
        }
3374
0
        if (cpl::contains(m_mapShortNameToArg, shortName))
3375
0
        {
3376
0
            ReportError(CE_Failure, CPLE_AppDefined,
3377
0
                        "Short name '%s' already declared", shortName.c_str());
3378
0
        }
3379
0
        m_mapShortNameToArg[shortName] = argRaw;
3380
0
    }
3381
0
    m_args.emplace_back(std::move(arg));
3382
0
    return *(
3383
0
        cpl::down_cast<GDALInConstructionAlgorithmArg *>(m_args.back().get()));
3384
0
}
3385
3386
GDALInConstructionAlgorithmArg &
3387
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3388
                      const std::string &helpMessage, bool *pValue)
3389
0
{
3390
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3391
0
        this,
3392
0
        GDALAlgorithmArgDecl(longName, chShortName, helpMessage, GAAT_BOOLEAN),
3393
0
        pValue));
3394
0
}
3395
3396
GDALInConstructionAlgorithmArg &
3397
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3398
                      const std::string &helpMessage, std::string *pValue)
3399
0
{
3400
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3401
0
        this,
3402
0
        GDALAlgorithmArgDecl(longName, chShortName, helpMessage, GAAT_STRING),
3403
0
        pValue));
3404
0
}
3405
3406
GDALInConstructionAlgorithmArg &
3407
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3408
                      const std::string &helpMessage, int *pValue)
3409
0
{
3410
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3411
0
        this,
3412
0
        GDALAlgorithmArgDecl(longName, chShortName, helpMessage, GAAT_INTEGER),
3413
0
        pValue));
3414
0
}
3415
3416
GDALInConstructionAlgorithmArg &
3417
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3418
                      const std::string &helpMessage, double *pValue)
3419
0
{
3420
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3421
0
        this,
3422
0
        GDALAlgorithmArgDecl(longName, chShortName, helpMessage, GAAT_REAL),
3423
0
        pValue));
3424
0
}
3425
3426
GDALInConstructionAlgorithmArg &
3427
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3428
                      const std::string &helpMessage,
3429
                      GDALArgDatasetValue *pValue, GDALArgDatasetType type)
3430
0
{
3431
0
    auto &arg = AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3432
0
                           this,
3433
0
                           GDALAlgorithmArgDecl(longName, chShortName,
3434
0
                                                helpMessage, GAAT_DATASET),
3435
0
                           pValue))
3436
0
                    .SetDatasetType(type);
3437
0
    pValue->SetOwnerArgument(&arg);
3438
0
    return arg;
3439
0
}
3440
3441
GDALInConstructionAlgorithmArg &
3442
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3443
                      const std::string &helpMessage,
3444
                      std::vector<std::string> *pValue)
3445
0
{
3446
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3447
0
        this,
3448
0
        GDALAlgorithmArgDecl(longName, chShortName, helpMessage,
3449
0
                             GAAT_STRING_LIST),
3450
0
        pValue));
3451
0
}
3452
3453
GDALInConstructionAlgorithmArg &
3454
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3455
                      const std::string &helpMessage, std::vector<int> *pValue)
3456
0
{
3457
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3458
0
        this,
3459
0
        GDALAlgorithmArgDecl(longName, chShortName, helpMessage,
3460
0
                             GAAT_INTEGER_LIST),
3461
0
        pValue));
3462
0
}
3463
3464
GDALInConstructionAlgorithmArg &
3465
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3466
                      const std::string &helpMessage,
3467
                      std::vector<double> *pValue)
3468
0
{
3469
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3470
0
        this,
3471
0
        GDALAlgorithmArgDecl(longName, chShortName, helpMessage,
3472
0
                             GAAT_REAL_LIST),
3473
0
        pValue));
3474
0
}
3475
3476
GDALInConstructionAlgorithmArg &
3477
GDALAlgorithm::AddArg(const std::string &longName, char chShortName,
3478
                      const std::string &helpMessage,
3479
                      std::vector<GDALArgDatasetValue> *pValue,
3480
                      GDALArgDatasetType type)
3481
0
{
3482
0
    return AddArg(std::make_unique<GDALInConstructionAlgorithmArg>(
3483
0
                      this,
3484
0
                      GDALAlgorithmArgDecl(longName, chShortName, helpMessage,
3485
0
                                           GAAT_DATASET_LIST),
3486
0
                      pValue))
3487
0
        .SetDatasetType(type);
3488
0
}
3489
3490
/************************************************************************/
3491
/*                            MsgOrDefault()                            */
3492
/************************************************************************/
3493
3494
inline const char *MsgOrDefault(const char *helpMessage,
3495
                                const char *defaultMessage)
3496
0
{
3497
0
    return helpMessage && helpMessage[0] ? helpMessage : defaultMessage;
3498
0
}
3499
3500
/************************************************************************/
3501
/*         GDALAlgorithm::SetAutoCompleteFunctionForFilename()          */
3502
/************************************************************************/
3503
3504
/* static */
3505
void GDALAlgorithm::SetAutoCompleteFunctionForFilename(
3506
    GDALInConstructionAlgorithmArg &arg, GDALArgDatasetType type)
3507
0
{
3508
0
    arg.SetAutoCompleteFunction(
3509
0
        [&arg,
3510
0
         type](const std::string &currentValue) -> std::vector<std::string>
3511
0
        {
3512
0
            std::vector<std::string> oRet;
3513
3514
0
            if (arg.IsHidden())
3515
0
                return oRet;
3516
3517
0
            {
3518
0
                CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
3519
0
                VSIStatBufL sStat;
3520
0
                if (!currentValue.empty() && currentValue.back() != '/' &&
3521
0
                    VSIStatL(currentValue.c_str(), &sStat) == 0)
3522
0
                {
3523
0
                    return oRet;
3524
0
                }
3525
0
            }
3526
3527
0
            auto poDM = GetGDALDriverManager();
3528
0
            std::set<std::string> oExtensions;
3529
0
            if (type)
3530
0
            {
3531
0
                for (int i = 0; i < poDM->GetDriverCount(); ++i)
3532
0
                {
3533
0
                    auto poDriver = poDM->GetDriver(i);
3534
0
                    if (((type & GDAL_OF_RASTER) != 0 &&
3535
0
                         poDriver->GetMetadataItem(GDAL_DCAP_RASTER)) ||
3536
0
                        ((type & GDAL_OF_VECTOR) != 0 &&
3537
0
                         poDriver->GetMetadataItem(GDAL_DCAP_VECTOR)) ||
3538
0
                        ((type & GDAL_OF_MULTIDIM_RASTER) != 0 &&
3539
0
                         poDriver->GetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER)))
3540
0
                    {
3541
0
                        const char *pszExtensions =
3542
0
                            poDriver->GetMetadataItem(GDAL_DMD_EXTENSIONS);
3543
0
                        if (pszExtensions)
3544
0
                        {
3545
0
                            const CPLStringList aosExts(
3546
0
                                CSLTokenizeString2(pszExtensions, " ", 0));
3547
0
                            for (const char *pszExt : cpl::Iterate(aosExts))
3548
0
                                oExtensions.insert(CPLString(pszExt).tolower());
3549
0
                        }
3550
0
                    }
3551
0
                }
3552
0
            }
3553
3554
0
            std::string osDir;
3555
0
            const CPLStringList aosVSIPrefixes(VSIGetFileSystemsPrefixes());
3556
0
            std::string osPrefix;
3557
0
            if (STARTS_WITH(currentValue.c_str(), "/vsi"))
3558
0
            {
3559
0
                for (const char *pszPrefix : cpl::Iterate(aosVSIPrefixes))
3560
0
                {
3561
0
                    if (STARTS_WITH(currentValue.c_str(), pszPrefix))
3562
0
                    {
3563
0
                        osPrefix = pszPrefix;
3564
0
                        break;
3565
0
                    }
3566
0
                }
3567
0
                if (osPrefix.empty())
3568
0
                    return aosVSIPrefixes;
3569
0
                if (currentValue == osPrefix)
3570
0
                    osDir = osPrefix;
3571
0
            }
3572
0
            if (osDir.empty())
3573
0
            {
3574
0
                osDir = CPLGetDirnameSafe(currentValue.c_str());
3575
0
                if (!osPrefix.empty() && osDir.size() < osPrefix.size())
3576
0
                    osDir = std::move(osPrefix);
3577
0
            }
3578
3579
0
            auto psDir = VSIOpenDir(osDir.c_str(), 0, nullptr);
3580
0
            const std::string osSep = VSIGetDirectorySeparator(osDir.c_str());
3581
0
            if (currentValue.empty())
3582
0
                osDir.clear();
3583
0
            const std::string currentFilename =
3584
0
                CPLGetFilename(currentValue.c_str());
3585
0
            if (psDir)
3586
0
            {
3587
0
                while (const VSIDIREntry *psEntry = VSIGetNextDirEntry(psDir))
3588
0
                {
3589
0
                    if ((currentFilename.empty() ||
3590
0
                         STARTS_WITH(psEntry->pszName,
3591
0
                                     currentFilename.c_str())) &&
3592
0
                        strcmp(psEntry->pszName, ".") != 0 &&
3593
0
                        strcmp(psEntry->pszName, "..") != 0 &&
3594
0
                        (oExtensions.empty() ||
3595
0
                         !strstr(psEntry->pszName, ".aux.xml")))
3596
0
                    {
3597
0
                        if (oExtensions.empty() ||
3598
0
                            cpl::contains(
3599
0
                                oExtensions,
3600
0
                                CPLString(CPLGetExtensionSafe(psEntry->pszName))
3601
0
                                    .tolower()) ||
3602
0
                            VSI_ISDIR(psEntry->nMode))
3603
0
                        {
3604
0
                            std::string osVal;
3605
0
                            if (osDir.empty() || osDir == ".")
3606
0
                                osVal = psEntry->pszName;
3607
0
                            else
3608
0
                                osVal = CPLFormFilenameSafe(
3609
0
                                    osDir.c_str(), psEntry->pszName, nullptr);
3610
0
                            if (VSI_ISDIR(psEntry->nMode))
3611
0
                                osVal += osSep;
3612
0
                            oRet.push_back(std::move(osVal));
3613
0
                        }
3614
0
                    }
3615
0
                }
3616
0
                VSICloseDir(psDir);
3617
0
            }
3618
0
            return oRet;
3619
0
        });
3620
0
}
3621
3622
/************************************************************************/
3623
/*                 GDALAlgorithm::AddInputDatasetArg()                  */
3624
/************************************************************************/
3625
3626
GDALInConstructionAlgorithmArg &GDALAlgorithm::AddInputDatasetArg(
3627
    GDALArgDatasetValue *pValue, GDALArgDatasetType type,
3628
    bool positionalAndRequired, const char *helpMessage)
3629
0
{
3630
0
    auto &arg = AddArg(
3631
0
        GDAL_ARG_NAME_INPUT, 'i',
3632
0
        MsgOrDefault(helpMessage,
3633
0
                     CPLSPrintf("Input %s dataset",
3634
0
                                GDALAlgorithmArgDatasetTypeName(type).c_str())),
3635
0
        pValue, type);
3636
0
    if (positionalAndRequired)
3637
0
        arg.SetPositional().SetRequired();
3638
3639
0
    SetAutoCompleteFunctionForFilename(arg, type);
3640
3641
0
    AddValidationAction(
3642
0
        [pValue]()
3643
0
        {
3644
0
            if (pValue->GetName() == "-")
3645
0
                pValue->Set("/vsistdin/");
3646
0
            return true;
3647
0
        });
3648
3649
0
    return arg;
3650
0
}
3651
3652
/************************************************************************/
3653
/*                 GDALAlgorithm::AddInputDatasetArg()                  */
3654
/************************************************************************/
3655
3656
GDALInConstructionAlgorithmArg &GDALAlgorithm::AddInputDatasetArg(
3657
    std::vector<GDALArgDatasetValue> *pValue, GDALArgDatasetType type,
3658
    bool positionalAndRequired, const char *helpMessage)
3659
0
{
3660
0
    auto &arg =
3661
0
        AddArg(GDAL_ARG_NAME_INPUT, 'i',
3662
0
               MsgOrDefault(
3663
0
                   helpMessage,
3664
0
                   CPLSPrintf("Input %s datasets",
3665
0
                              GDALAlgorithmArgDatasetTypeName(type).c_str())),
3666
0
               pValue, type)
3667
0
            .SetPackedValuesAllowed(false);
3668
0
    if (positionalAndRequired)
3669
0
        arg.SetPositional().SetRequired();
3670
3671
0
    SetAutoCompleteFunctionForFilename(arg, type);
3672
3673
0
    AddValidationAction(
3674
0
        [pValue]()
3675
0
        {
3676
0
            for (auto &val : *pValue)
3677
0
            {
3678
0
                if (val.GetName() == "-")
3679
0
                    val.Set("/vsistdin/");
3680
0
            }
3681
0
            return true;
3682
0
        });
3683
0
    return arg;
3684
0
}
3685
3686
/************************************************************************/
3687
/*                 GDALAlgorithm::AddOutputDatasetArg()                 */
3688
/************************************************************************/
3689
3690
GDALInConstructionAlgorithmArg &GDALAlgorithm::AddOutputDatasetArg(
3691
    GDALArgDatasetValue *pValue, GDALArgDatasetType type,
3692
    bool positionalAndRequired, const char *helpMessage)
3693
0
{
3694
0
    auto &arg =
3695
0
        AddArg(GDAL_ARG_NAME_OUTPUT, 'o',
3696
0
               MsgOrDefault(
3697
0
                   helpMessage,
3698
0
                   CPLSPrintf("Output %s dataset",
3699
0
                              GDALAlgorithmArgDatasetTypeName(type).c_str())),
3700
0
               pValue, type)
3701
0
            .SetIsInput(true)
3702
0
            .SetIsOutput(true)
3703
0
            .SetDatasetInputFlags(GADV_NAME)
3704
0
            .SetDatasetOutputFlags(GADV_OBJECT);
3705
0
    if (positionalAndRequired)
3706
0
        arg.SetPositional().SetRequired();
3707
3708
0
    AddValidationAction(
3709
0
        [this, &arg, pValue]()
3710
0
        {
3711
0
            if (pValue->GetName() == "-")
3712
0
                pValue->Set("/vsistdout/");
3713
3714
0
            auto outputFormatArg = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
3715
0
            if (outputFormatArg && outputFormatArg->GetType() == GAAT_STRING &&
3716
0
                (!outputFormatArg->IsExplicitlySet() ||
3717
0
                 outputFormatArg->Get<std::string>().empty()) &&
3718
0
                arg.IsExplicitlySet())
3719
0
            {
3720
0
                const auto vrtCompatible =
3721
0
                    outputFormatArg->GetMetadataItem(GAAMDI_VRT_COMPATIBLE);
3722
0
                if (vrtCompatible && !vrtCompatible->empty() &&
3723
0
                    vrtCompatible->front() == "false" &&
3724
0
                    EQUAL(
3725
0
                        CPLGetExtensionSafe(pValue->GetName().c_str()).c_str(),
3726
0
                        "VRT"))
3727
0
                {
3728
0
                    ReportError(
3729
0
                        CE_Failure, CPLE_NotSupported,
3730
0
                        "VRT output is not supported.%s",
3731
0
                        outputFormatArg->GetDescription().find("GDALG") !=
3732
0
                                std::string::npos
3733
0
                            ? " Consider using the GDALG driver instead (files "
3734
0
                              "with .gdalg.json extension)"
3735
0
                            : "");
3736
0
                    return false;
3737
0
                }
3738
0
                else if (pValue->GetName().size() > strlen(".gdalg.json") &&
3739
0
                         EQUAL(pValue->GetName()
3740
0
                                   .substr(pValue->GetName().size() -
3741
0
                                           strlen(".gdalg.json"))
3742
0
                                   .c_str(),
3743
0
                               ".gdalg.json") &&
3744
0
                         outputFormatArg->GetDescription().find("GDALG") ==
3745
0
                             std::string::npos)
3746
0
                {
3747
0
                    ReportError(CE_Failure, CPLE_NotSupported,
3748
0
                                "GDALG output is not supported");
3749
0
                    return false;
3750
0
                }
3751
0
            }
3752
0
            return true;
3753
0
        });
3754
3755
0
    return arg;
3756
0
}
3757
3758
/************************************************************************/
3759
/*                   GDALAlgorithm::AddOverwriteArg()                   */
3760
/************************************************************************/
3761
3762
GDALInConstructionAlgorithmArg &
3763
GDALAlgorithm::AddOverwriteArg(bool *pValue, const char *helpMessage)
3764
0
{
3765
0
    return AddArg(GDAL_ARG_NAME_OVERWRITE, 0,
3766
0
                  MsgOrDefault(
3767
0
                      helpMessage,
3768
0
                      _("Whether overwriting existing output is allowed")),
3769
0
                  pValue)
3770
0
        .SetDefault(false);
3771
0
}
3772
3773
/************************************************************************/
3774
/*                GDALAlgorithm::AddOverwriteLayerArg()                 */
3775
/************************************************************************/
3776
3777
GDALInConstructionAlgorithmArg &
3778
GDALAlgorithm::AddOverwriteLayerArg(bool *pValue, const char *helpMessage)
3779
0
{
3780
0
    AddValidationAction(
3781
0
        [this]
3782
0
        {
3783
0
            auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
3784
0
            if (!(updateArg && updateArg->GetType() == GAAT_BOOLEAN))
3785
0
            {
3786
0
                ReportError(CE_Failure, CPLE_AppDefined,
3787
0
                            "--update argument must exist for "
3788
0
                            "--overwrite-layer, even if hidden");
3789
0
                return false;
3790
0
            }
3791
0
            return true;
3792
0
        });
3793
0
    return AddArg(GDAL_ARG_NAME_OVERWRITE_LAYER, 0,
3794
0
                  MsgOrDefault(
3795
0
                      helpMessage,
3796
0
                      _("Whether overwriting existing output is allowed")),
3797
0
                  pValue)
3798
0
        .SetDefault(false)
3799
0
        .AddAction(
3800
0
            [this]
3801
0
            {
3802
0
                auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
3803
0
                if (updateArg && updateArg->GetType() == GAAT_BOOLEAN)
3804
0
                {
3805
0
                    updateArg->Set(true);
3806
0
                }
3807
0
            });
3808
0
}
3809
3810
/************************************************************************/
3811
/*                    GDALAlgorithm::AddUpdateArg()                     */
3812
/************************************************************************/
3813
3814
GDALInConstructionAlgorithmArg &
3815
GDALAlgorithm::AddUpdateArg(bool *pValue, const char *helpMessage)
3816
0
{
3817
0
    return AddArg(GDAL_ARG_NAME_UPDATE, 0,
3818
0
                  MsgOrDefault(
3819
0
                      helpMessage,
3820
0
                      _("Whether to open existing dataset in update mode")),
3821
0
                  pValue)
3822
0
        .SetDefault(false);
3823
0
}
3824
3825
/************************************************************************/
3826
/*                  GDALAlgorithm::AddAppendLayerArg()                  */
3827
/************************************************************************/
3828
3829
GDALInConstructionAlgorithmArg &
3830
GDALAlgorithm::AddAppendLayerArg(bool *pValue, const char *helpMessage)
3831
0
{
3832
0
    AddValidationAction(
3833
0
        [this]
3834
0
        {
3835
0
            auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
3836
0
            if (!(updateArg && updateArg->GetType() == GAAT_BOOLEAN))
3837
0
            {
3838
0
                ReportError(CE_Failure, CPLE_AppDefined,
3839
0
                            "--update argument must exist for --append, even "
3840
0
                            "if hidden");
3841
0
                return false;
3842
0
            }
3843
0
            return true;
3844
0
        });
3845
0
    return AddArg(GDAL_ARG_NAME_APPEND, 0,
3846
0
                  MsgOrDefault(
3847
0
                      helpMessage,
3848
0
                      _("Whether appending to existing layer is allowed")),
3849
0
                  pValue)
3850
0
        .SetDefault(false)
3851
0
        .AddAction(
3852
0
            [this]
3853
0
            {
3854
0
                auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
3855
0
                if (updateArg && updateArg->GetType() == GAAT_BOOLEAN)
3856
0
                {
3857
0
                    updateArg->Set(true);
3858
0
                }
3859
0
            });
3860
0
}
3861
3862
/************************************************************************/
3863
/*                GDALAlgorithm::AddOptionsSuggestions()                */
3864
/************************************************************************/
3865
3866
/* static */
3867
bool GDALAlgorithm::AddOptionsSuggestions(const char *pszXML, int datasetType,
3868
                                          const std::string &currentValue,
3869
                                          std::vector<std::string> &oRet)
3870
0
{
3871
0
    if (!pszXML)
3872
0
        return false;
3873
0
    CPLXMLTreeCloser poTree(CPLParseXMLString(pszXML));
3874
0
    if (!poTree)
3875
0
        return false;
3876
3877
0
    std::string typedOptionName = currentValue;
3878
0
    const auto posEqual = typedOptionName.find('=');
3879
0
    std::string typedValue;
3880
0
    if (posEqual != 0 && posEqual != std::string::npos)
3881
0
    {
3882
0
        typedValue = currentValue.substr(posEqual + 1);
3883
0
        typedOptionName.resize(posEqual);
3884
0
    }
3885
3886
0
    for (const CPLXMLNode *psChild = poTree.get()->psChild; psChild;
3887
0
         psChild = psChild->psNext)
3888
0
    {
3889
0
        const char *pszName = CPLGetXMLValue(psChild, "name", nullptr);
3890
0
        if (pszName && typedOptionName == pszName &&
3891
0
            (strcmp(psChild->pszValue, "Option") == 0 ||
3892
0
             strcmp(psChild->pszValue, "Argument") == 0))
3893
0
        {
3894
0
            const char *pszType = CPLGetXMLValue(psChild, "type", "");
3895
0
            const char *pszMin = CPLGetXMLValue(psChild, "min", nullptr);
3896
0
            const char *pszMax = CPLGetXMLValue(psChild, "max", nullptr);
3897
0
            if (EQUAL(pszType, "string-select"))
3898
0
            {
3899
0
                for (const CPLXMLNode *psChild2 = psChild->psChild; psChild2;
3900
0
                     psChild2 = psChild2->psNext)
3901
0
                {
3902
0
                    if (EQUAL(psChild2->pszValue, "Value"))
3903
0
                    {
3904
0
                        oRet.push_back(CPLGetXMLValue(psChild2, "", ""));
3905
0
                    }
3906
0
                }
3907
0
            }
3908
0
            else if (EQUAL(pszType, "boolean"))
3909
0
            {
3910
0
                if (typedValue == "YES" || typedValue == "NO")
3911
0
                {
3912
0
                    oRet.push_back(currentValue);
3913
0
                    return true;
3914
0
                }
3915
0
                oRet.push_back("NO");
3916
0
                oRet.push_back("YES");
3917
0
            }
3918
0
            else if (EQUAL(pszType, "int"))
3919
0
            {
3920
0
                if (pszMin && pszMax && atoi(pszMax) - atoi(pszMin) > 0 &&
3921
0
                    atoi(pszMax) - atoi(pszMin) < 25)
3922
0
                {
3923
0
                    const int nMax = atoi(pszMax);
3924
0
                    for (int i = atoi(pszMin); i <= nMax; ++i)
3925
0
                        oRet.push_back(std::to_string(i));
3926
0
                }
3927
0
            }
3928
3929
0
            if (oRet.empty())
3930
0
            {
3931
0
                if (pszMin && pszMax)
3932
0
                {
3933
0
                    oRet.push_back(std::string("##"));
3934
0
                    oRet.push_back(std::string("validity range: [")
3935
0
                                       .append(pszMin)
3936
0
                                       .append(",")
3937
0
                                       .append(pszMax)
3938
0
                                       .append("]"));
3939
0
                }
3940
0
                else if (pszMin)
3941
0
                {
3942
0
                    oRet.push_back(std::string("##"));
3943
0
                    oRet.push_back(
3944
0
                        std::string("validity range: >= ").append(pszMin));
3945
0
                }
3946
0
                else if (pszMax)
3947
0
                {
3948
0
                    oRet.push_back(std::string("##"));
3949
0
                    oRet.push_back(
3950
0
                        std::string("validity range: <= ").append(pszMax));
3951
0
                }
3952
0
                else if (const char *pszDescription =
3953
0
                             CPLGetXMLValue(psChild, "description", nullptr))
3954
0
                {
3955
0
                    oRet.push_back(std::string("##"));
3956
0
                    oRet.push_back(std::string("type: ")
3957
0
                                       .append(pszType)
3958
0
                                       .append(", description: ")
3959
0
                                       .append(pszDescription));
3960
0
                }
3961
0
            }
3962
3963
0
            return true;
3964
0
        }
3965
0
    }
3966
3967
0
    for (const CPLXMLNode *psChild = poTree.get()->psChild; psChild;
3968
0
         psChild = psChild->psNext)
3969
0
    {
3970
0
        const char *pszName = CPLGetXMLValue(psChild, "name", nullptr);
3971
0
        if (pszName && (strcmp(psChild->pszValue, "Option") == 0 ||
3972
0
                        strcmp(psChild->pszValue, "Argument") == 0))
3973
0
        {
3974
0
            const char *pszScope = CPLGetXMLValue(psChild, "scope", nullptr);
3975
0
            if (!pszScope ||
3976
0
                (EQUAL(pszScope, "raster") &&
3977
0
                 (datasetType & GDAL_OF_RASTER) != 0) ||
3978
0
                (EQUAL(pszScope, "vector") &&
3979
0
                 (datasetType & GDAL_OF_VECTOR) != 0))
3980
0
            {
3981
0
                oRet.push_back(std::string(pszName).append("="));
3982
0
            }
3983
0
        }
3984
0
    }
3985
3986
0
    return false;
3987
0
}
3988
3989
/************************************************************************/
3990
/*             GDALAlgorithm::OpenOptionCompleteFunction()              */
3991
/************************************************************************/
3992
3993
//! @cond Doxygen_Suppress
3994
std::vector<std::string>
3995
GDALAlgorithm::OpenOptionCompleteFunction(const std::string &currentValue) const
3996
0
{
3997
0
    std::vector<std::string> oRet;
3998
3999
0
    int datasetType = GDAL_OF_RASTER | GDAL_OF_VECTOR | GDAL_OF_MULTIDIM_RASTER;
4000
0
    auto inputArg = GetArg(GDAL_ARG_NAME_INPUT);
4001
0
    if (inputArg && (inputArg->GetType() == GAAT_DATASET ||
4002
0
                     inputArg->GetType() == GAAT_DATASET_LIST))
4003
0
    {
4004
0
        datasetType = inputArg->GetDatasetType();
4005
0
    }
4006
4007
0
    auto inputFormat = GetArg(GDAL_ARG_NAME_INPUT_FORMAT);
4008
0
    if (inputFormat && inputFormat->GetType() == GAAT_STRING_LIST &&
4009
0
        inputFormat->IsExplicitlySet())
4010
0
    {
4011
0
        const auto &aosAllowedDrivers =
4012
0
            inputFormat->Get<std::vector<std::string>>();
4013
0
        if (aosAllowedDrivers.size() == 1)
4014
0
        {
4015
0
            auto poDriver = GetGDALDriverManager()->GetDriverByName(
4016
0
                aosAllowedDrivers[0].c_str());
4017
0
            if (poDriver)
4018
0
            {
4019
0
                AddOptionsSuggestions(
4020
0
                    poDriver->GetMetadataItem(GDAL_DMD_OPENOPTIONLIST),
4021
0
                    datasetType, currentValue, oRet);
4022
0
            }
4023
0
            return oRet;
4024
0
        }
4025
0
    }
4026
4027
0
    const auto AddSuggestions = [datasetType, &currentValue,
4028
0
                                 &oRet](const GDALArgDatasetValue &datasetValue)
4029
0
    {
4030
0
        auto poDM = GetGDALDriverManager();
4031
4032
0
        const auto &osDSName = datasetValue.GetName();
4033
0
        const std::string osExt = CPLGetExtensionSafe(osDSName.c_str());
4034
0
        if (!osExt.empty())
4035
0
        {
4036
0
            std::set<std::string> oVisitedExtensions;
4037
0
            for (int i = 0; i < poDM->GetDriverCount(); ++i)
4038
0
            {
4039
0
                auto poDriver = poDM->GetDriver(i);
4040
0
                if (((datasetType & GDAL_OF_RASTER) != 0 &&
4041
0
                     poDriver->GetMetadataItem(GDAL_DCAP_RASTER)) ||
4042
0
                    ((datasetType & GDAL_OF_VECTOR) != 0 &&
4043
0
                     poDriver->GetMetadataItem(GDAL_DCAP_VECTOR)) ||
4044
0
                    ((datasetType & GDAL_OF_MULTIDIM_RASTER) != 0 &&
4045
0
                     poDriver->GetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER)))
4046
0
                {
4047
0
                    const char *pszExtensions =
4048
0
                        poDriver->GetMetadataItem(GDAL_DMD_EXTENSIONS);
4049
0
                    if (pszExtensions)
4050
0
                    {
4051
0
                        const CPLStringList aosExts(
4052
0
                            CSLTokenizeString2(pszExtensions, " ", 0));
4053
0
                        for (const char *pszExt : cpl::Iterate(aosExts))
4054
0
                        {
4055
0
                            if (EQUAL(pszExt, osExt.c_str()) &&
4056
0
                                !cpl::contains(oVisitedExtensions, pszExt))
4057
0
                            {
4058
0
                                oVisitedExtensions.insert(pszExt);
4059
0
                                if (AddOptionsSuggestions(
4060
0
                                        poDriver->GetMetadataItem(
4061
0
                                            GDAL_DMD_OPENOPTIONLIST),
4062
0
                                        datasetType, currentValue, oRet))
4063
0
                                {
4064
0
                                    return;
4065
0
                                }
4066
0
                                break;
4067
0
                            }
4068
0
                        }
4069
0
                    }
4070
0
                }
4071
0
            }
4072
0
        }
4073
0
    };
4074
4075
0
    if (inputArg && inputArg->GetType() == GAAT_DATASET)
4076
0
    {
4077
0
        auto &datasetValue = inputArg->Get<GDALArgDatasetValue>();
4078
0
        AddSuggestions(datasetValue);
4079
0
    }
4080
0
    else if (inputArg && inputArg->GetType() == GAAT_DATASET_LIST)
4081
0
    {
4082
0
        auto &datasetValues = inputArg->Get<std::vector<GDALArgDatasetValue>>();
4083
0
        if (datasetValues.size() == 1)
4084
0
            AddSuggestions(datasetValues[0]);
4085
0
    }
4086
4087
0
    return oRet;
4088
0
}
4089
4090
//! @endcond
4091
4092
/************************************************************************/
4093
/*                  GDALAlgorithm::AddOpenOptionsArg()                  */
4094
/************************************************************************/
4095
4096
GDALInConstructionAlgorithmArg &
4097
GDALAlgorithm::AddOpenOptionsArg(std::vector<std::string> *pValue,
4098
                                 const char *helpMessage)
4099
0
{
4100
0
    auto &arg = AddArg(GDAL_ARG_NAME_OPEN_OPTION, 0,
4101
0
                       MsgOrDefault(helpMessage, _("Open options")), pValue)
4102
0
                    .AddAlias("oo")
4103
0
                    .SetMetaVar("<KEY>=<VALUE>")
4104
0
                    .SetPackedValuesAllowed(false)
4105
0
                    .SetCategory(GAAC_ADVANCED);
4106
4107
0
    arg.AddValidationAction([this, &arg]()
4108
0
                            { return ParseAndValidateKeyValue(arg); });
4109
4110
0
    arg.SetAutoCompleteFunction(
4111
0
        [this](const std::string &currentValue)
4112
0
        { return OpenOptionCompleteFunction(currentValue); });
4113
4114
0
    return arg;
4115
0
}
4116
4117
/************************************************************************/
4118
/*               GDALAlgorithm::AddOutputOpenOptionsArg()               */
4119
/************************************************************************/
4120
4121
GDALInConstructionAlgorithmArg &
4122
GDALAlgorithm::AddOutputOpenOptionsArg(std::vector<std::string> *pValue,
4123
                                       const char *helpMessage)
4124
0
{
4125
0
    auto &arg =
4126
0
        AddArg(GDAL_ARG_NAME_OUTPUT_OPEN_OPTION, 0,
4127
0
               MsgOrDefault(helpMessage, _("Output open options")), pValue)
4128
0
            .AddAlias("output-oo")
4129
0
            .SetMetaVar("<KEY>=<VALUE>")
4130
0
            .SetPackedValuesAllowed(false)
4131
0
            .SetCategory(GAAC_ADVANCED);
4132
4133
0
    arg.AddValidationAction([this, &arg]()
4134
0
                            { return ParseAndValidateKeyValue(arg); });
4135
4136
0
    arg.SetAutoCompleteFunction(
4137
0
        [this](const std::string &currentValue)
4138
0
        { return OpenOptionCompleteFunction(currentValue); });
4139
4140
0
    return arg;
4141
0
}
4142
4143
/************************************************************************/
4144
/*                           ValidateFormat()                           */
4145
/************************************************************************/
4146
4147
bool GDALAlgorithm::ValidateFormat(const GDALAlgorithmArg &arg,
4148
                                   bool bStreamAllowed,
4149
                                   bool bGDALGAllowed) const
4150
0
{
4151
0
    if (arg.GetChoices().empty())
4152
0
    {
4153
0
        const auto Validate =
4154
0
            [this, &arg, bStreamAllowed, bGDALGAllowed](const std::string &val)
4155
0
        {
4156
0
            if (const auto extraFormats =
4157
0
                    arg.GetMetadataItem(GAAMDI_EXTRA_FORMATS))
4158
0
            {
4159
0
                for (const auto &extraFormat : *extraFormats)
4160
0
                {
4161
0
                    if (EQUAL(val.c_str(), extraFormat.c_str()))
4162
0
                        return true;
4163
0
                }
4164
0
            }
4165
4166
0
            if (bStreamAllowed && EQUAL(val.c_str(), "stream"))
4167
0
                return true;
4168
4169
0
            if (EQUAL(val.c_str(), "GDALG") &&
4170
0
                arg.GetName() == GDAL_ARG_NAME_OUTPUT_FORMAT)
4171
0
            {
4172
0
                if (bGDALGAllowed)
4173
0
                {
4174
0
                    return true;
4175
0
                }
4176
0
                else
4177
0
                {
4178
0
                    ReportError(CE_Failure, CPLE_NotSupported,
4179
0
                                "GDALG output is not supported.");
4180
0
                    return false;
4181
0
                }
4182
0
            }
4183
4184
0
            const auto vrtCompatible =
4185
0
                arg.GetMetadataItem(GAAMDI_VRT_COMPATIBLE);
4186
0
            if (vrtCompatible && !vrtCompatible->empty() &&
4187
0
                vrtCompatible->front() == "false" && EQUAL(val.c_str(), "VRT"))
4188
0
            {
4189
0
                ReportError(CE_Failure, CPLE_NotSupported,
4190
0
                            "VRT output is not supported.%s",
4191
0
                            bGDALGAllowed
4192
0
                                ? " Consider using the GDALG driver instead "
4193
0
                                  "(files with .gdalg.json extension)."
4194
0
                                : "");
4195
0
                return false;
4196
0
            }
4197
4198
0
            const auto allowedFormats =
4199
0
                arg.GetMetadataItem(GAAMDI_ALLOWED_FORMATS);
4200
0
            if (allowedFormats && !allowedFormats->empty() &&
4201
0
                std::find(allowedFormats->begin(), allowedFormats->end(),
4202
0
                          val) != allowedFormats->end())
4203
0
            {
4204
0
                return true;
4205
0
            }
4206
4207
0
            const auto excludedFormats =
4208
0
                arg.GetMetadataItem(GAAMDI_EXCLUDED_FORMATS);
4209
0
            if (excludedFormats && !excludedFormats->empty() &&
4210
0
                std::find(excludedFormats->begin(), excludedFormats->end(),
4211
0
                          val) != excludedFormats->end())
4212
0
            {
4213
0
                ReportError(CE_Failure, CPLE_NotSupported,
4214
0
                            "%s output is not supported.", val.c_str());
4215
0
                return false;
4216
0
            }
4217
4218
0
            auto hDriver = GDALGetDriverByName(val.c_str());
4219
0
            if (!hDriver)
4220
0
            {
4221
0
                auto poMissingDriver =
4222
0
                    GetGDALDriverManager()->GetHiddenDriverByName(val.c_str());
4223
0
                if (poMissingDriver)
4224
0
                {
4225
0
                    const std::string msg =
4226
0
                        GDALGetMessageAboutMissingPluginDriver(poMissingDriver);
4227
0
                    ReportError(CE_Failure, CPLE_AppDefined,
4228
0
                                "Invalid value for argument '%s'. Driver '%s' "
4229
0
                                "not found but is known. However plugin %s",
4230
0
                                arg.GetName().c_str(), val.c_str(),
4231
0
                                msg.c_str());
4232
0
                }
4233
0
                else
4234
0
                {
4235
0
                    ReportError(CE_Failure, CPLE_AppDefined,
4236
0
                                "Invalid value for argument '%s'. Driver '%s' "
4237
0
                                "does not exist.",
4238
0
                                arg.GetName().c_str(), val.c_str());
4239
0
                }
4240
0
                return false;
4241
0
            }
4242
4243
0
            const auto caps = arg.GetMetadataItem(GAAMDI_REQUIRED_CAPABILITIES);
4244
0
            if (caps)
4245
0
            {
4246
0
                for (const std::string &cap : *caps)
4247
0
                {
4248
0
                    const char *pszVal =
4249
0
                        GDALGetMetadataItem(hDriver, cap.c_str(), nullptr);
4250
0
                    if (!(pszVal && pszVal[0]))
4251
0
                    {
4252
0
                        if (cap == GDAL_DCAP_CREATECOPY &&
4253
0
                            std::find(caps->begin(), caps->end(),
4254
0
                                      GDAL_DCAP_RASTER) != caps->end() &&
4255
0
                            GDALGetMetadataItem(hDriver, GDAL_DCAP_RASTER,
4256
0
                                                nullptr) &&
4257
0
                            GDALGetMetadataItem(hDriver, GDAL_DCAP_CREATE,
4258
0
                                                nullptr))
4259
0
                        {
4260
                            // if it supports Create, it supports CreateCopy
4261
0
                        }
4262
0
                        else if (cap == GDAL_DMD_EXTENSIONS)
4263
0
                        {
4264
0
                            ReportError(
4265
0
                                CE_Failure, CPLE_AppDefined,
4266
0
                                "Invalid value for argument '%s'. Driver '%s' "
4267
0
                                "does "
4268
0
                                "not advertise any file format extension.",
4269
0
                                arg.GetName().c_str(), val.c_str());
4270
0
                            return false;
4271
0
                        }
4272
0
                        else
4273
0
                        {
4274
0
                            if (cap == GDAL_DCAP_CREATE)
4275
0
                            {
4276
0
                                auto updateArg = GetArg(GDAL_ARG_NAME_UPDATE);
4277
0
                                if (updateArg &&
4278
0
                                    updateArg->GetType() == GAAT_BOOLEAN &&
4279
0
                                    updateArg->IsExplicitlySet())
4280
0
                                {
4281
0
                                    continue;
4282
0
                                }
4283
4284
0
                                ReportError(
4285
0
                                    CE_Failure, CPLE_AppDefined,
4286
0
                                    "Invalid value for argument '%s'. "
4287
0
                                    "Driver '%s' does not have write support.",
4288
0
                                    arg.GetName().c_str(), val.c_str());
4289
0
                                return false;
4290
0
                            }
4291
0
                            else
4292
0
                            {
4293
0
                                ReportError(
4294
0
                                    CE_Failure, CPLE_AppDefined,
4295
0
                                    "Invalid value for argument '%s'. Driver "
4296
0
                                    "'%s' "
4297
0
                                    "does "
4298
0
                                    "not expose the required '%s' capability.",
4299
0
                                    arg.GetName().c_str(), val.c_str(),
4300
0
                                    cap.c_str());
4301
0
                                return false;
4302
0
                            }
4303
0
                        }
4304
0
                    }
4305
0
                }
4306
0
            }
4307
0
            return true;
4308
0
        };
4309
4310
0
        if (arg.GetType() == GAAT_STRING)
4311
0
        {
4312
0
            return Validate(arg.Get<std::string>());
4313
0
        }
4314
0
        else if (arg.GetType() == GAAT_STRING_LIST)
4315
0
        {
4316
0
            for (const auto &val : arg.Get<std::vector<std::string>>())
4317
0
            {
4318
0
                if (!Validate(val))
4319
0
                    return false;
4320
0
            }
4321
0
        }
4322
0
    }
4323
4324
0
    return true;
4325
0
}
4326
4327
/************************************************************************/
4328
/*                     FormatAutoCompleteFunction()                     */
4329
/************************************************************************/
4330
4331
/* static */
4332
std::vector<std::string> GDALAlgorithm::FormatAutoCompleteFunction(
4333
    const GDALAlgorithmArg &arg, bool /* bStreamAllowed */, bool bGDALGAllowed)
4334
0
{
4335
0
    std::vector<std::string> res;
4336
0
    auto poDM = GetGDALDriverManager();
4337
0
    const auto vrtCompatible = arg.GetMetadataItem(GAAMDI_VRT_COMPATIBLE);
4338
0
    const auto allowedFormats = arg.GetMetadataItem(GAAMDI_ALLOWED_FORMATS);
4339
0
    const auto excludedFormats = arg.GetMetadataItem(GAAMDI_EXCLUDED_FORMATS);
4340
0
    const auto caps = arg.GetMetadataItem(GAAMDI_REQUIRED_CAPABILITIES);
4341
0
    if (auto extraFormats = arg.GetMetadataItem(GAAMDI_EXTRA_FORMATS))
4342
0
        res = std::move(*extraFormats);
4343
0
    for (int i = 0; i < poDM->GetDriverCount(); ++i)
4344
0
    {
4345
0
        auto poDriver = poDM->GetDriver(i);
4346
4347
0
        if (vrtCompatible && !vrtCompatible->empty() &&
4348
0
            vrtCompatible->front() == "false" &&
4349
0
            EQUAL(poDriver->GetDescription(), "VRT"))
4350
0
        {
4351
            // do nothing
4352
0
        }
4353
0
        else if (allowedFormats && !allowedFormats->empty() &&
4354
0
                 std::find(allowedFormats->begin(), allowedFormats->end(),
4355
0
                           poDriver->GetDescription()) != allowedFormats->end())
4356
0
        {
4357
0
            res.push_back(poDriver->GetDescription());
4358
0
        }
4359
0
        else if (excludedFormats && !excludedFormats->empty() &&
4360
0
                 std::find(excludedFormats->begin(), excludedFormats->end(),
4361
0
                           poDriver->GetDescription()) !=
4362
0
                     excludedFormats->end())
4363
0
        {
4364
0
            continue;
4365
0
        }
4366
0
        else if (caps)
4367
0
        {
4368
0
            bool ok = true;
4369
0
            for (const std::string &cap : *caps)
4370
0
            {
4371
0
                if (cap == GDAL_ALG_DCAP_RASTER_OR_MULTIDIM_RASTER)
4372
0
                {
4373
0
                    if (!poDriver->GetMetadataItem(GDAL_DCAP_RASTER) &&
4374
0
                        !poDriver->GetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER))
4375
0
                    {
4376
0
                        ok = false;
4377
0
                        break;
4378
0
                    }
4379
0
                }
4380
0
                else if (const char *pszVal =
4381
0
                             poDriver->GetMetadataItem(cap.c_str());
4382
0
                         pszVal && pszVal[0])
4383
0
                {
4384
0
                }
4385
0
                else if (cap == GDAL_DCAP_CREATECOPY &&
4386
0
                         (std::find(caps->begin(), caps->end(),
4387
0
                                    GDAL_DCAP_RASTER) != caps->end() &&
4388
0
                          poDriver->GetMetadataItem(GDAL_DCAP_RASTER)) &&
4389
0
                         poDriver->GetMetadataItem(GDAL_DCAP_CREATE))
4390
0
                {
4391
                    // if it supports Create, it supports CreateCopy
4392
0
                }
4393
0
                else
4394
0
                {
4395
0
                    ok = false;
4396
0
                    break;
4397
0
                }
4398
0
            }
4399
0
            if (ok)
4400
0
            {
4401
0
                res.push_back(poDriver->GetDescription());
4402
0
            }
4403
0
        }
4404
0
    }
4405
0
    if (bGDALGAllowed)
4406
0
        res.push_back("GDALG");
4407
0
    return res;
4408
0
}
4409
4410
/************************************************************************/
4411
/*                 GDALAlgorithm::AddInputFormatsArg()                  */
4412
/************************************************************************/
4413
4414
GDALInConstructionAlgorithmArg &
4415
GDALAlgorithm::AddInputFormatsArg(std::vector<std::string> *pValue,
4416
                                  const char *helpMessage)
4417
0
{
4418
0
    auto &arg = AddArg(GDAL_ARG_NAME_INPUT_FORMAT, 0,
4419
0
                       MsgOrDefault(helpMessage, _("Input formats")), pValue)
4420
0
                    .AddAlias("if")
4421
0
                    .SetCategory(GAAC_ADVANCED);
4422
0
    arg.AddValidationAction([this, &arg]()
4423
0
                            { return ValidateFormat(arg, false, false); });
4424
0
    arg.SetAutoCompleteFunction(
4425
0
        [&arg](const std::string &)
4426
0
        { return FormatAutoCompleteFunction(arg, false, false); });
4427
0
    return arg;
4428
0
}
4429
4430
/************************************************************************/
4431
/*                 GDALAlgorithm::AddOutputFormatArg()                  */
4432
/************************************************************************/
4433
4434
GDALInConstructionAlgorithmArg &
4435
GDALAlgorithm::AddOutputFormatArg(std::string *pValue, bool bStreamAllowed,
4436
                                  bool bGDALGAllowed, const char *helpMessage)
4437
0
{
4438
0
    auto &arg = AddArg(GDAL_ARG_NAME_OUTPUT_FORMAT, 'f',
4439
0
                       MsgOrDefault(helpMessage,
4440
0
                                    bGDALGAllowed
4441
0
                                        ? _("Output format (\"GDALG\" allowed)")
4442
0
                                        : _("Output format")),
4443
0
                       pValue)
4444
0
                    .AddAlias("of")
4445
0
                    .AddAlias("format");
4446
0
    arg.AddValidationAction(
4447
0
        [this, &arg, bStreamAllowed, bGDALGAllowed]()
4448
0
        { return ValidateFormat(arg, bStreamAllowed, bGDALGAllowed); });
4449
0
    arg.SetAutoCompleteFunction(
4450
0
        [&arg, bStreamAllowed, bGDALGAllowed](const std::string &)
4451
0
        {
4452
0
            return FormatAutoCompleteFunction(arg, bStreamAllowed,
4453
0
                                              bGDALGAllowed);
4454
0
        });
4455
0
    return arg;
4456
0
}
4457
4458
/************************************************************************/
4459
/*                GDALAlgorithm::AddOutputDataTypeArg()                 */
4460
/************************************************************************/
4461
GDALInConstructionAlgorithmArg &
4462
GDALAlgorithm::AddOutputDataTypeArg(std::string *pValue,
4463
                                    const char *helpMessage)
4464
0
{
4465
0
    auto &arg =
4466
0
        AddArg(GDAL_ARG_NAME_OUTPUT_DATA_TYPE, 0,
4467
0
               MsgOrDefault(helpMessage, _("Output data type")), pValue)
4468
0
            .AddAlias("ot")
4469
0
            .AddAlias("datatype")
4470
0
            .AddMetadataItem("type", {"GDALDataType"})
4471
0
            .SetChoices("UInt8", "Int8", "UInt16", "Int16", "UInt32", "Int32",
4472
0
                        "UInt64", "Int64", "CInt16", "CInt32", "Float16",
4473
0
                        "Float32", "Float64", "CFloat32", "CFloat64")
4474
0
            .SetHiddenChoices("Byte");
4475
0
    return arg;
4476
0
}
4477
4478
/************************************************************************/
4479
/*                    GDALAlgorithm::AddNodataArg()                     */
4480
/************************************************************************/
4481
4482
GDALInConstructionAlgorithmArg &
4483
GDALAlgorithm::AddNodataArg(std::string *pValue, bool noneAllowed,
4484
                            const std::string &optionName,
4485
                            const char *helpMessage)
4486
0
{
4487
0
    auto &arg = AddArg(
4488
0
        optionName, 0,
4489
0
        MsgOrDefault(helpMessage,
4490
0
                     noneAllowed
4491
0
                         ? _("Assign a specified nodata value to output bands "
4492
0
                             "('none', numeric value, 'nan', 'inf', '-inf')")
4493
0
                         : _("Assign a specified nodata value to output bands "
4494
0
                             "(numeric value, 'nan', 'inf', '-inf')")),
4495
0
        pValue);
4496
0
    arg.AddValidationAction(
4497
0
        [this, pValue, noneAllowed, optionName]()
4498
0
        {
4499
0
            if (!(noneAllowed && EQUAL(pValue->c_str(), "none")))
4500
0
            {
4501
0
                char *endptr = nullptr;
4502
0
                CPLStrtod(pValue->c_str(), &endptr);
4503
0
                if (endptr != pValue->c_str() + pValue->size())
4504
0
                {
4505
0
                    ReportError(CE_Failure, CPLE_IllegalArg,
4506
0
                                "Value of '%s' should be %sa "
4507
0
                                "numeric value, 'nan', 'inf' or '-inf'",
4508
0
                                optionName.c_str(),
4509
0
                                noneAllowed ? "'none', " : "");
4510
0
                    return false;
4511
0
                }
4512
0
            }
4513
0
            return true;
4514
0
        });
4515
0
    return arg;
4516
0
}
4517
4518
/************************************************************************/
4519
/*                 GDALAlgorithm::AddOutputStringArg()                  */
4520
/************************************************************************/
4521
4522
GDALInConstructionAlgorithmArg &
4523
GDALAlgorithm::AddOutputStringArg(std::string *pValue, const char *helpMessage)
4524
0
{
4525
0
    return AddArg(
4526
0
               GDAL_ARG_NAME_OUTPUT_STRING, 0,
4527
0
               MsgOrDefault(helpMessage,
4528
0
                            _("Output string, in which the result is placed")),
4529
0
               pValue)
4530
0
        .SetHiddenForCLI()
4531
0
        .SetIsInput(false)
4532
0
        .SetIsOutput(true);
4533
0
}
4534
4535
/************************************************************************/
4536
/*                    GDALAlgorithm::AddStdoutArg()                     */
4537
/************************************************************************/
4538
4539
GDALInConstructionAlgorithmArg &
4540
GDALAlgorithm::AddStdoutArg(bool *pValue, const char *helpMessage)
4541
0
{
4542
0
    return AddArg(GDAL_ARG_NAME_STDOUT, 0,
4543
0
                  MsgOrDefault(helpMessage,
4544
0
                               _("Directly output on stdout. If enabled, "
4545
0
                                 "output-string will be empty")),
4546
0
                  pValue)
4547
0
        .SetHidden();
4548
0
}
4549
4550
/************************************************************************/
4551
/*                   GDALAlgorithm::AddLayerNameArg()                   */
4552
/************************************************************************/
4553
4554
GDALInConstructionAlgorithmArg &
4555
GDALAlgorithm::AddLayerNameArg(std::string *pValue, const char *helpMessage)
4556
0
{
4557
0
    return AddArg(GDAL_ARG_NAME_INPUT_LAYER, 'l',
4558
0
                  MsgOrDefault(helpMessage, _("Input layer name")), pValue);
4559
0
}
4560
4561
/************************************************************************/
4562
/*                   GDALAlgorithm::AddArrayNameArg()                   */
4563
/************************************************************************/
4564
4565
GDALInConstructionAlgorithmArg &
4566
GDALAlgorithm::AddArrayNameArg(std::string *pValue, const char *helpMessage)
4567
0
{
4568
0
    return AddArg("array", 0, MsgOrDefault(helpMessage, _("Array name")),
4569
0
                  pValue)
4570
0
        .SetAutoCompleteFunction([this](const std::string &)
4571
0
                                 { return AutoCompleteArrayName(); });
4572
0
}
4573
4574
/************************************************************************/
4575
/*                   GDALAlgorithm::AddArrayNameArg()                   */
4576
/************************************************************************/
4577
4578
GDALInConstructionAlgorithmArg &
4579
GDALAlgorithm::AddArrayNameArg(std::vector<std::string> *pValue,
4580
                               const char *helpMessage)
4581
0
{
4582
0
    return AddArg("array", 0, MsgOrDefault(helpMessage, _("Array name(s)")),
4583
0
                  pValue)
4584
0
        .SetAutoCompleteFunction([this](const std::string &)
4585
0
                                 { return AutoCompleteArrayName(); });
4586
0
}
4587
4588
/************************************************************************/
4589
/*                GDALAlgorithm::AutoCompleteArrayName()                */
4590
/************************************************************************/
4591
4592
std::vector<std::string> GDALAlgorithm::AutoCompleteArrayName() const
4593
0
{
4594
0
    std::vector<std::string> ret;
4595
0
    std::string osDSName;
4596
0
    auto inputArg = GetArg(GDAL_ARG_NAME_INPUT);
4597
0
    if (inputArg && inputArg->GetType() == GAAT_DATASET_LIST)
4598
0
    {
4599
0
        auto &inputDatasets = inputArg->Get<std::vector<GDALArgDatasetValue>>();
4600
0
        if (!inputDatasets.empty())
4601
0
        {
4602
0
            osDSName = inputDatasets[0].GetName();
4603
0
        }
4604
0
    }
4605
0
    else if (inputArg && inputArg->GetType() == GAAT_DATASET)
4606
0
    {
4607
0
        auto &inputDataset = inputArg->Get<GDALArgDatasetValue>();
4608
0
        osDSName = inputDataset.GetName();
4609
0
    }
4610
4611
0
    if (!osDSName.empty())
4612
0
    {
4613
0
        CPLStringList aosAllowedDrivers;
4614
0
        const auto ifArg = GetArg(GDAL_ARG_NAME_INPUT_FORMAT);
4615
0
        if (ifArg && ifArg->GetType() == GAAT_STRING_LIST)
4616
0
            aosAllowedDrivers =
4617
0
                CPLStringList(ifArg->Get<std::vector<std::string>>());
4618
4619
0
        CPLStringList aosOpenOptions;
4620
0
        const auto ooArg = GetArg(GDAL_ARG_NAME_OPEN_OPTION);
4621
0
        if (ooArg && ooArg->GetType() == GAAT_STRING_LIST)
4622
0
            aosOpenOptions =
4623
0
                CPLStringList(ooArg->Get<std::vector<std::string>>());
4624
4625
0
        if (auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
4626
0
                osDSName.c_str(), GDAL_OF_MULTIDIM_RASTER,
4627
0
                aosAllowedDrivers.List(), aosOpenOptions.List(), nullptr)))
4628
0
        {
4629
0
            if (auto poRG = poDS->GetRootGroup())
4630
0
            {
4631
0
                ret = poRG->GetMDArrayFullNamesRecursive();
4632
0
            }
4633
0
        }
4634
0
    }
4635
4636
0
    return ret;
4637
0
}
4638
4639
/************************************************************************/
4640
/*                  GDALAlgorithm::AddMemorySizeArg()                   */
4641
/************************************************************************/
4642
4643
GDALInConstructionAlgorithmArg &
4644
GDALAlgorithm::AddMemorySizeArg(size_t *pValue, std::string *pStrValue,
4645
                                const std::string &optionName,
4646
                                const char *helpMessage)
4647
0
{
4648
0
    return AddArg(optionName, 0, helpMessage, pStrValue)
4649
0
        .SetDefault(*pStrValue)
4650
0
        .AddValidationAction(
4651
0
            [this, pValue, pStrValue]()
4652
0
            {
4653
0
                CPLDebug("GDAL", "StrValue `%s`", pStrValue->c_str());
4654
0
                GIntBig nBytes;
4655
0
                bool bUnitSpecified;
4656
0
                if (CPLParseMemorySize(pStrValue->c_str(), &nBytes,
4657
0
                                       &bUnitSpecified) != CE_None)
4658
0
                {
4659
0
                    return false;
4660
0
                }
4661
0
                if (!bUnitSpecified)
4662
0
                {
4663
0
                    ReportError(CE_Failure, CPLE_AppDefined,
4664
0
                                "Memory size must have a unit or be a "
4665
0
                                "percentage of usable RAM (2GB, 5%%, etc.)");
4666
0
                    return false;
4667
0
                }
4668
                if constexpr (sizeof(std::uint64_t) > sizeof(size_t))
4669
                {
4670
                    // -1 to please CoverityScan
4671
                    if (static_cast<std::uint64_t>(nBytes) >
4672
                        std::numeric_limits<size_t>::max() - 1U)
4673
                    {
4674
                        ReportError(CE_Failure, CPLE_AppDefined,
4675
                                    "Memory size %s is too large.",
4676
                                    pStrValue->c_str());
4677
                        return false;
4678
                    }
4679
                }
4680
4681
0
                *pValue = static_cast<size_t>(nBytes);
4682
0
                return true;
4683
0
            });
4684
0
}
4685
4686
/************************************************************************/
4687
/*                GDALAlgorithm::AddOutputLayerNameArg()                */
4688
/************************************************************************/
4689
4690
GDALInConstructionAlgorithmArg &
4691
GDALAlgorithm::AddOutputLayerNameArg(std::string *pValue,
4692
                                     const char *helpMessage)
4693
0
{
4694
0
    return AddArg(GDAL_ARG_NAME_OUTPUT_LAYER, 0,
4695
0
                  MsgOrDefault(helpMessage, _("Output layer name")), pValue);
4696
0
}
4697
4698
/************************************************************************/
4699
/*                   GDALAlgorithm::AddLayerNameArg()                   */
4700
/************************************************************************/
4701
4702
GDALInConstructionAlgorithmArg &
4703
GDALAlgorithm::AddLayerNameArg(std::vector<std::string> *pValue,
4704
                               const char *helpMessage)
4705
0
{
4706
0
    return AddArg(GDAL_ARG_NAME_INPUT_LAYER, 'l',
4707
0
                  MsgOrDefault(helpMessage, _("Input layer name")), pValue);
4708
0
}
4709
4710
/************************************************************************/
4711
/*                 GDALAlgorithm::AddGeometryTypeArg()                  */
4712
/************************************************************************/
4713
4714
GDALInConstructionAlgorithmArg &
4715
GDALAlgorithm::AddGeometryTypeArg(std::string *pValue, const char *helpMessage)
4716
0
{
4717
0
    return AddArg("geometry-type", 0,
4718
0
                  MsgOrDefault(helpMessage, _("Geometry type")), pValue)
4719
0
        .SetAutoCompleteFunction(
4720
0
            [](const std::string &currentValue)
4721
0
            {
4722
0
                std::vector<std::string> oRet;
4723
0
                for (const char *type :
4724
0
                     {"GEOMETRY", "POINT", "LINESTRING", "POLYGON",
4725
0
                      "MULTIPOINT", "MULTILINESTRING", "MULTIPOLYGON",
4726
0
                      "GEOMETRYCOLLECTION", "CURVE", "CIRCULARSTRING",
4727
0
                      "COMPOUNDCURVE", "SURFACE", "CURVEPOLYGON", "MULTICURVE",
4728
0
                      "MULTISURFACE", "POLYHEDRALSURFACE", "TIN"})
4729
0
                {
4730
0
                    if (currentValue.empty() ||
4731
0
                        STARTS_WITH(type, currentValue.c_str()))
4732
0
                    {
4733
0
                        oRet.push_back(type);
4734
0
                        oRet.push_back(std::string(type).append("Z"));
4735
0
                        oRet.push_back(std::string(type).append("M"));
4736
0
                        oRet.push_back(std::string(type).append("ZM"));
4737
0
                    }
4738
0
                }
4739
0
                return oRet;
4740
0
            })
4741
0
        .AddValidationAction(
4742
0
            [this, pValue]()
4743
0
            {
4744
0
                if (wkbFlatten(OGRFromOGCGeomType(pValue->c_str())) ==
4745
0
                        wkbUnknown &&
4746
0
                    !STARTS_WITH_CI(pValue->c_str(), "GEOMETRY"))
4747
0
                {
4748
0
                    ReportError(CE_Failure, CPLE_AppDefined,
4749
0
                                "Invalid geometry type '%s'", pValue->c_str());
4750
0
                    return false;
4751
0
                }
4752
0
                return true;
4753
0
            });
4754
0
}
4755
4756
/************************************************************************/
4757
/*         GDALAlgorithm::SetAutoCompleteFunctionForLayerName()         */
4758
/************************************************************************/
4759
4760
/* static */
4761
void GDALAlgorithm::SetAutoCompleteFunctionForLayerName(
4762
    GDALInConstructionAlgorithmArg &layerArg, GDALAlgorithmArg &datasetArg)
4763
0
{
4764
0
    CPLAssert(datasetArg.GetType() == GAAT_DATASET ||
4765
0
              datasetArg.GetType() == GAAT_DATASET_LIST);
4766
4767
0
    layerArg.SetAutoCompleteFunction(
4768
0
        [&datasetArg](const std::string &currentValue)
4769
0
        {
4770
0
            std::vector<std::string> ret;
4771
0
            CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
4772
0
            GDALArgDatasetValue *dsVal = nullptr;
4773
0
            if (datasetArg.GetType() == GAAT_DATASET)
4774
0
            {
4775
0
                dsVal = &(datasetArg.Get<GDALArgDatasetValue>());
4776
0
            }
4777
0
            else
4778
0
            {
4779
0
                auto &val = datasetArg.Get<std::vector<GDALArgDatasetValue>>();
4780
0
                if (val.size() == 1)
4781
0
                {
4782
0
                    dsVal = &val[0];
4783
0
                }
4784
0
            }
4785
0
            if (dsVal && !dsVal->GetName().empty())
4786
0
            {
4787
0
                auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
4788
0
                    dsVal->GetName().c_str(), GDAL_OF_VECTOR));
4789
0
                if (poDS)
4790
0
                {
4791
0
                    for (auto &&poLayer : poDS->GetLayers())
4792
0
                    {
4793
0
                        if (currentValue == poLayer->GetDescription())
4794
0
                        {
4795
0
                            ret.clear();
4796
0
                            ret.push_back(poLayer->GetDescription());
4797
0
                            break;
4798
0
                        }
4799
0
                        ret.push_back(poLayer->GetDescription());
4800
0
                    }
4801
0
                }
4802
0
            }
4803
0
            return ret;
4804
0
        });
4805
0
}
4806
4807
/************************************************************************/
4808
/*         GDALAlgorithm::SetAutoCompleteFunctionForFieldName()         */
4809
/************************************************************************/
4810
4811
void GDALAlgorithm::SetAutoCompleteFunctionForFieldName(
4812
    GDALInConstructionAlgorithmArg &fieldArg,
4813
    GDALInConstructionAlgorithmArg &layerNameArg,
4814
    std::vector<GDALArgDatasetValue> &datasetArg)
4815
0
{
4816
4817
0
    fieldArg.SetAutoCompleteFunction(
4818
0
        [&datasetArg, &layerNameArg](const std::string &currentValue)
4819
0
        {
4820
0
            std::set<std::string> ret;
4821
0
            if (!datasetArg.empty())
4822
0
            {
4823
0
                CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
4824
4825
0
                auto getLayerFields = [&ret, &currentValue](OGRLayer *poLayer)
4826
0
                {
4827
0
                    auto poDefn = poLayer->GetLayerDefn();
4828
0
                    const int nFieldCount = poDefn->GetFieldCount();
4829
0
                    for (int iField = 0; iField < nFieldCount; iField++)
4830
0
                    {
4831
0
                        const char *fieldName =
4832
0
                            poDefn->GetFieldDefn(iField)->GetNameRef();
4833
0
                        if (currentValue == fieldName)
4834
0
                        {
4835
0
                            ret.clear();
4836
0
                            ret.insert(fieldName);
4837
0
                            break;
4838
0
                        }
4839
0
                        ret.insert(fieldName);
4840
0
                    }
4841
0
                };
4842
4843
0
                GDALArgDatasetValue &dsVal = datasetArg[0];
4844
4845
0
                if (!dsVal.GetName().empty())
4846
0
                {
4847
0
                    auto poDS = std::unique_ptr<GDALDataset>(
4848
0
                        GDALDataset::Open(dsVal.GetName().c_str(),
4849
0
                                          GDAL_OF_VECTOR | GDAL_OF_READONLY));
4850
0
                    if (poDS)
4851
0
                    {
4852
0
                        const auto &layerName = layerNameArg.Get<std::string>();
4853
0
                        if (layerName.empty())
4854
0
                        {
4855
                            // Loop through all layers
4856
0
                            for (auto &&poLayer : poDS->GetLayers())
4857
0
                            {
4858
0
                                getLayerFields(poLayer);
4859
0
                            }
4860
0
                        }
4861
0
                        else
4862
0
                        {
4863
0
                            const auto poLayer = poDS->GetLayerByName(
4864
0
                                layerNameArg.Get<std::string>().c_str());
4865
0
                            if (poLayer)
4866
0
                            {
4867
0
                                getLayerFields(poLayer);
4868
0
                            }
4869
0
                        }
4870
0
                    }
4871
0
                }
4872
0
            }
4873
0
            std::vector<std::string> retVector(ret.begin(), ret.end());
4874
0
            return retVector;
4875
0
        });
4876
0
}
4877
4878
/************************************************************************/
4879
/*                   GDALAlgorithm::AddFieldNameArg()                   */
4880
/************************************************************************/
4881
4882
GDALInConstructionAlgorithmArg &
4883
GDALAlgorithm::AddFieldNameArg(std::string *pValue, const char *helpMessage)
4884
0
{
4885
0
    return AddArg("field-name", 0, MsgOrDefault(helpMessage, _("Field name")),
4886
0
                  pValue);
4887
0
}
4888
4889
/************************************************************************/
4890
/*               GDALAlgorithm::AddFieldTypeSubtypeArg()                */
4891
/************************************************************************/
4892
4893
GDALInConstructionAlgorithmArg &GDALAlgorithm::AddFieldTypeSubtypeArg(
4894
    OGRFieldType *pTypeValue, OGRFieldSubType *pSubtypeValue,
4895
    std::string *pStrValue, const std::string &argName, const char *helpMessage)
4896
0
{
4897
0
    auto &arg =
4898
0
        AddArg(argName.empty() ? std::string("field-type") : argName, 0,
4899
0
               MsgOrDefault(helpMessage, _("Field type or subtype")), pStrValue)
4900
0
            .SetAutoCompleteFunction(
4901
0
                [](const std::string &currentValue)
4902
0
                {
4903
0
                    std::vector<std::string> oRet;
4904
0
                    for (int i = 1; i <= OGRFieldSubType::OFSTMaxSubType; i++)
4905
0
                    {
4906
0
                        const char *pszSubType =
4907
0
                            OGRFieldDefn::GetFieldSubTypeName(
4908
0
                                static_cast<OGRFieldSubType>(i));
4909
0
                        if (pszSubType != nullptr)
4910
0
                        {
4911
0
                            if (currentValue.empty() ||
4912
0
                                STARTS_WITH(pszSubType, currentValue.c_str()))
4913
0
                            {
4914
0
                                oRet.push_back(pszSubType);
4915
0
                            }
4916
0
                        }
4917
0
                    }
4918
4919
0
                    for (int i = 0; i <= OGRFieldType::OFTMaxType; i++)
4920
0
                    {
4921
                        // Skip deprecated
4922
0
                        if (static_cast<OGRFieldType>(i) ==
4923
0
                                OGRFieldType::OFTWideString ||
4924
0
                            static_cast<OGRFieldType>(i) ==
4925
0
                                OGRFieldType::OFTWideStringList)
4926
0
                            continue;
4927
0
                        const char *pszType = OGRFieldDefn::GetFieldTypeName(
4928
0
                            static_cast<OGRFieldType>(i));
4929
0
                        if (pszType != nullptr)
4930
0
                        {
4931
0
                            if (currentValue.empty() ||
4932
0
                                STARTS_WITH(pszType, currentValue.c_str()))
4933
0
                            {
4934
0
                                oRet.push_back(pszType);
4935
0
                            }
4936
0
                        }
4937
0
                    }
4938
0
                    return oRet;
4939
0
                });
4940
4941
0
    auto validationFunction =
4942
0
        [this, &arg, pTypeValue, pSubtypeValue, pStrValue]()
4943
0
    {
4944
0
        bool isValid{true};
4945
0
        *pTypeValue = OGRFieldDefn::GetFieldTypeByName(pStrValue->c_str());
4946
4947
        // String is returned for unknown types
4948
0
        if (!EQUAL(pStrValue->c_str(), "String") && *pTypeValue == OFTString)
4949
0
        {
4950
0
            isValid = false;
4951
0
        }
4952
4953
0
        *pSubtypeValue =
4954
0
            OGRFieldDefn::GetFieldSubTypeByName(pStrValue->c_str());
4955
4956
0
        if (*pSubtypeValue != OFSTNone)
4957
0
        {
4958
0
            isValid = true;
4959
0
            switch (*pSubtypeValue)
4960
0
            {
4961
0
                case OFSTBoolean:
4962
0
                case OFSTInt16:
4963
0
                {
4964
0
                    *pTypeValue = OFTInteger;
4965
0
                    break;
4966
0
                }
4967
0
                case OFSTFloat32:
4968
0
                {
4969
0
                    *pTypeValue = OFTReal;
4970
0
                    break;
4971
0
                }
4972
0
                default:
4973
0
                {
4974
0
                    *pTypeValue = OFTString;
4975
0
                    break;
4976
0
                }
4977
0
            }
4978
0
        }
4979
4980
0
        if (!isValid)
4981
0
        {
4982
0
            ReportError(CE_Failure, CPLE_AppDefined,
4983
0
                        "Invalid value for argument '%s': '%s'",
4984
0
                        arg.GetName().c_str(), pStrValue->c_str());
4985
0
        }
4986
4987
0
        return isValid;
4988
0
    };
4989
4990
0
    if (!pStrValue->empty())
4991
0
    {
4992
0
        arg.SetDefault(*pStrValue);
4993
0
        validationFunction();
4994
0
    }
4995
4996
0
    arg.AddValidationAction(std::move(validationFunction));
4997
4998
0
    return arg;
4999
0
}
5000
5001
/************************************************************************/
5002
/*                   GDALAlgorithm::ValidateBandArg()                   */
5003
/************************************************************************/
5004
5005
bool GDALAlgorithm::ValidateBandArg() const
5006
0
{
5007
0
    bool ret = true;
5008
0
    const auto bandArg = GetArg(GDAL_ARG_NAME_BAND);
5009
0
    const auto inputDatasetArg = GetArg(GDAL_ARG_NAME_INPUT);
5010
0
    if (bandArg && bandArg->IsExplicitlySet() && inputDatasetArg &&
5011
0
        (inputDatasetArg->GetType() == GAAT_DATASET ||
5012
0
         inputDatasetArg->GetType() == GAAT_DATASET_LIST) &&
5013
0
        (inputDatasetArg->GetDatasetType() & GDAL_OF_RASTER) != 0)
5014
0
    {
5015
0
        const auto CheckBand = [this](const GDALDataset *poDS, int nBand)
5016
0
        {
5017
0
            if (nBand > poDS->GetRasterCount())
5018
0
            {
5019
0
                ReportError(CE_Failure, CPLE_AppDefined,
5020
0
                            "Value of 'band' should be greater or equal than "
5021
0
                            "1 and less or equal than %d.",
5022
0
                            poDS->GetRasterCount());
5023
0
                return false;
5024
0
            }
5025
0
            return true;
5026
0
        };
5027
5028
0
        const auto ValidateForOneDataset =
5029
0
            [&bandArg, &CheckBand](const GDALDataset *poDS)
5030
0
        {
5031
0
            bool l_ret = true;
5032
0
            if (bandArg->GetType() == GAAT_INTEGER)
5033
0
            {
5034
0
                l_ret = CheckBand(poDS, bandArg->Get<int>());
5035
0
            }
5036
0
            else if (bandArg->GetType() == GAAT_INTEGER_LIST)
5037
0
            {
5038
0
                for (int nBand : bandArg->Get<std::vector<int>>())
5039
0
                {
5040
0
                    l_ret = l_ret && CheckBand(poDS, nBand);
5041
0
                }
5042
0
            }
5043
0
            return l_ret;
5044
0
        };
5045
5046
0
        if (inputDatasetArg->GetType() == GAAT_DATASET)
5047
0
        {
5048
0
            auto poDS =
5049
0
                inputDatasetArg->Get<GDALArgDatasetValue>().GetDatasetRef();
5050
0
            if (poDS && !ValidateForOneDataset(poDS))
5051
0
                ret = false;
5052
0
        }
5053
0
        else
5054
0
        {
5055
0
            CPLAssert(inputDatasetArg->GetType() == GAAT_DATASET_LIST);
5056
0
            for (auto &datasetValue :
5057
0
                 inputDatasetArg->Get<std::vector<GDALArgDatasetValue>>())
5058
0
            {
5059
0
                auto poDS = datasetValue.GetDatasetRef();
5060
0
                if (poDS && !ValidateForOneDataset(poDS))
5061
0
                    ret = false;
5062
0
            }
5063
0
        }
5064
0
    }
5065
0
    return ret;
5066
0
}
5067
5068
/************************************************************************/
5069
/*            GDALAlgorithm::RunPreStepPipelineValidations()            */
5070
/************************************************************************/
5071
5072
bool GDALAlgorithm::RunPreStepPipelineValidations() const
5073
0
{
5074
0
    return ValidateBandArg();
5075
0
}
5076
5077
/************************************************************************/
5078
/*                     GDALAlgorithm::AddBandArg()                      */
5079
/************************************************************************/
5080
5081
GDALInConstructionAlgorithmArg &
5082
GDALAlgorithm::AddBandArg(int *pValue, const char *helpMessage)
5083
0
{
5084
0
    AddValidationAction([this]() { return ValidateBandArg(); });
5085
5086
0
    return AddArg(GDAL_ARG_NAME_BAND, 'b',
5087
0
                  MsgOrDefault(helpMessage, _("Input band (1-based index)")),
5088
0
                  pValue)
5089
0
        .AddValidationAction(
5090
0
            [pValue]()
5091
0
            {
5092
0
                if (*pValue <= 0)
5093
0
                {
5094
0
                    CPLError(CE_Failure, CPLE_AppDefined,
5095
0
                             "Value of 'band' should greater or equal to 1.");
5096
0
                    return false;
5097
0
                }
5098
0
                return true;
5099
0
            });
5100
0
}
5101
5102
/************************************************************************/
5103
/*                     GDALAlgorithm::AddBandArg()                      */
5104
/************************************************************************/
5105
5106
GDALInConstructionAlgorithmArg &
5107
GDALAlgorithm::AddBandArg(std::vector<int> *pValue, const char *helpMessage)
5108
0
{
5109
0
    AddValidationAction([this]() { return ValidateBandArg(); });
5110
5111
0
    return AddArg(GDAL_ARG_NAME_BAND, 'b',
5112
0
                  MsgOrDefault(helpMessage, _("Input band(s) (1-based index)")),
5113
0
                  pValue)
5114
0
        .AddValidationAction(
5115
0
            [pValue]()
5116
0
            {
5117
0
                for (int val : *pValue)
5118
0
                {
5119
0
                    if (val <= 0)
5120
0
                    {
5121
0
                        CPLError(CE_Failure, CPLE_AppDefined,
5122
0
                                 "Value of 'band' should greater or equal "
5123
0
                                 "to 1.");
5124
0
                        return false;
5125
0
                    }
5126
0
                }
5127
0
                return true;
5128
0
            });
5129
0
}
5130
5131
/************************************************************************/
5132
/*                      ParseAndValidateKeyValue()                      */
5133
/************************************************************************/
5134
5135
bool GDALAlgorithm::ParseAndValidateKeyValue(GDALAlgorithmArg &arg)
5136
0
{
5137
0
    const auto Validate = [this, &arg](const std::string &val)
5138
0
    {
5139
0
        if (val.find('=') == std::string::npos)
5140
0
        {
5141
0
            ReportError(
5142
0
                CE_Failure, CPLE_AppDefined,
5143
0
                "Invalid value for argument '%s'. <KEY>=<VALUE> expected",
5144
0
                arg.GetName().c_str());
5145
0
            return false;
5146
0
        }
5147
5148
0
        return true;
5149
0
    };
5150
5151
0
    if (arg.GetType() == GAAT_STRING)
5152
0
    {
5153
0
        return Validate(arg.Get<std::string>());
5154
0
    }
5155
0
    else if (arg.GetType() == GAAT_STRING_LIST)
5156
0
    {
5157
0
        std::vector<std::string> &vals = arg.Get<std::vector<std::string>>();
5158
0
        if (vals.size() == 1)
5159
0
        {
5160
            // Try to split A=B,C=D into A=B and C=D if there is no ambiguity
5161
0
            std::vector<std::string> newVals;
5162
0
            std::string curToken;
5163
0
            bool canSplitOnComma = true;
5164
0
            char lastSep = 0;
5165
0
            bool inString = false;
5166
0
            bool equalFoundInLastToken = false;
5167
0
            for (char c : vals[0])
5168
0
            {
5169
0
                if (!inString && c == ',')
5170
0
                {
5171
0
                    if (lastSep != '=' || !equalFoundInLastToken)
5172
0
                    {
5173
0
                        canSplitOnComma = false;
5174
0
                        break;
5175
0
                    }
5176
0
                    lastSep = c;
5177
0
                    newVals.push_back(curToken);
5178
0
                    curToken.clear();
5179
0
                    equalFoundInLastToken = false;
5180
0
                }
5181
0
                else if (!inString && c == '=')
5182
0
                {
5183
0
                    if (lastSep == '=')
5184
0
                    {
5185
0
                        canSplitOnComma = false;
5186
0
                        break;
5187
0
                    }
5188
0
                    equalFoundInLastToken = true;
5189
0
                    lastSep = c;
5190
0
                    curToken += c;
5191
0
                }
5192
0
                else if (c == '"')
5193
0
                {
5194
0
                    inString = !inString;
5195
0
                    curToken += c;
5196
0
                }
5197
0
                else
5198
0
                {
5199
0
                    curToken += c;
5200
0
                }
5201
0
            }
5202
0
            if (canSplitOnComma && !inString && equalFoundInLastToken)
5203
0
            {
5204
0
                if (!curToken.empty())
5205
0
                    newVals.emplace_back(std::move(curToken));
5206
0
                vals = std::move(newVals);
5207
0
            }
5208
0
        }
5209
5210
0
        for (const auto &val : vals)
5211
0
        {
5212
0
            if (!Validate(val))
5213
0
                return false;
5214
0
        }
5215
0
    }
5216
5217
0
    return true;
5218
0
}
5219
5220
/************************************************************************/
5221
/*                           IsGDALGOutput()                            */
5222
/************************************************************************/
5223
5224
bool GDALAlgorithm::IsGDALGOutput() const
5225
0
{
5226
0
    bool isGDALGOutput = false;
5227
0
    const auto outputFormatArg = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
5228
0
    const auto outputArg = GetArg(GDAL_ARG_NAME_OUTPUT);
5229
0
    if (outputArg && outputArg->GetType() == GAAT_DATASET &&
5230
0
        outputArg->IsExplicitlySet())
5231
0
    {
5232
0
        if (outputFormatArg && outputFormatArg->GetType() == GAAT_STRING &&
5233
0
            outputFormatArg->IsExplicitlySet())
5234
0
        {
5235
0
            const auto &val =
5236
0
                outputFormatArg->GDALAlgorithmArg::Get<std::string>();
5237
0
            isGDALGOutput = EQUAL(val.c_str(), "GDALG");
5238
0
        }
5239
0
        else
5240
0
        {
5241
0
            const auto &filename =
5242
0
                outputArg->GDALAlgorithmArg::Get<GDALArgDatasetValue>();
5243
0
            isGDALGOutput =
5244
0
                filename.GetName().size() > strlen(".gdalg.json") &&
5245
0
                EQUAL(filename.GetName().c_str() + filename.GetName().size() -
5246
0
                          strlen(".gdalg.json"),
5247
0
                      ".gdalg.json");
5248
0
        }
5249
0
    }
5250
0
    return isGDALGOutput;
5251
0
}
5252
5253
/************************************************************************/
5254
/*                         ProcessGDALGOutput()                         */
5255
/************************************************************************/
5256
5257
GDALAlgorithm::ProcessGDALGOutputRet GDALAlgorithm::ProcessGDALGOutput()
5258
0
{
5259
0
    if (!SupportsStreamedOutput())
5260
0
        return ProcessGDALGOutputRet::NOT_GDALG;
5261
5262
0
    if (IsGDALGOutput())
5263
0
    {
5264
0
        const auto outputArg = GetArg(GDAL_ARG_NAME_OUTPUT);
5265
0
        const auto &filename =
5266
0
            outputArg->GDALAlgorithmArg::Get<GDALArgDatasetValue>().GetName();
5267
0
        VSIStatBufL sStat;
5268
0
        if (VSIStatL(filename.c_str(), &sStat) == 0)
5269
0
        {
5270
0
            const auto overwriteArg = GetArg(GDAL_ARG_NAME_OVERWRITE);
5271
0
            if (overwriteArg && overwriteArg->GetType() == GAAT_BOOLEAN)
5272
0
            {
5273
0
                if (!overwriteArg->GDALAlgorithmArg::Get<bool>())
5274
0
                {
5275
0
                    CPLError(CE_Failure, CPLE_AppDefined,
5276
0
                             "File '%s' already exists. Specify the "
5277
0
                             "--overwrite option to overwrite it.",
5278
0
                             filename.c_str());
5279
0
                    return ProcessGDALGOutputRet::GDALG_ERROR;
5280
0
                }
5281
0
            }
5282
0
        }
5283
5284
0
        std::string osCommandLine;
5285
5286
0
        for (const auto &path : GDALAlgorithm::m_callPath)
5287
0
        {
5288
0
            if (!osCommandLine.empty())
5289
0
                osCommandLine += ' ';
5290
0
            osCommandLine += path;
5291
0
        }
5292
5293
0
        for (const auto &arg : GetArgs())
5294
0
        {
5295
0
            if (arg->IsExplicitlySet() &&
5296
0
                arg->GetName() != GDAL_ARG_NAME_OUTPUT &&
5297
0
                arg->GetName() != GDAL_ARG_NAME_OUTPUT_FORMAT &&
5298
0
                arg->GetName() != GDAL_ARG_NAME_UPDATE &&
5299
0
                arg->GetName() != GDAL_ARG_NAME_OVERWRITE)
5300
0
            {
5301
0
                osCommandLine += ' ';
5302
0
                std::string strArg;
5303
0
                if (!arg->Serialize(strArg))
5304
0
                {
5305
0
                    CPLError(CE_Failure, CPLE_AppDefined,
5306
0
                             "Cannot serialize argument %s",
5307
0
                             arg->GetName().c_str());
5308
0
                    return ProcessGDALGOutputRet::GDALG_ERROR;
5309
0
                }
5310
0
                osCommandLine += strArg;
5311
0
            }
5312
0
        }
5313
5314
0
        osCommandLine += " --output-format stream --output streamed_dataset";
5315
5316
0
        std::string outStringUnused;
5317
0
        return SaveGDALG(filename, outStringUnused, osCommandLine)
5318
0
                   ? ProcessGDALGOutputRet::GDALG_OK
5319
0
                   : ProcessGDALGOutputRet::GDALG_ERROR;
5320
0
    }
5321
5322
0
    return ProcessGDALGOutputRet::NOT_GDALG;
5323
0
}
5324
5325
/************************************************************************/
5326
/*                      GDALAlgorithm::SaveGDALG()                      */
5327
/************************************************************************/
5328
5329
/* static */ bool GDALAlgorithm::SaveGDALG(const std::string &filename,
5330
                                           std::string &outString,
5331
                                           const std::string &commandLine)
5332
0
{
5333
0
    CPLJSONDocument oDoc;
5334
0
    oDoc.GetRoot().Add("type", "gdal_streamed_alg");
5335
0
    oDoc.GetRoot().Add("command_line", commandLine);
5336
0
    oDoc.GetRoot().Add("gdal_version", GDALVersionInfo("VERSION_NUM"));
5337
5338
0
    if (!filename.empty())
5339
0
        return oDoc.Save(filename);
5340
5341
0
    outString = oDoc.GetRoot().Format(CPLJSONObject::PrettyFormat::Pretty);
5342
0
    return true;
5343
0
}
5344
5345
/************************************************************************/
5346
/*                GDALAlgorithm::AddCreationOptionsArg()                */
5347
/************************************************************************/
5348
5349
GDALInConstructionAlgorithmArg &
5350
GDALAlgorithm::AddCreationOptionsArg(std::vector<std::string> *pValue,
5351
                                     const char *helpMessage)
5352
0
{
5353
0
    auto &arg = AddArg(GDAL_ARG_NAME_CREATION_OPTION, 0,
5354
0
                       MsgOrDefault(helpMessage, _("Creation option")), pValue)
5355
0
                    .AddAlias("co")
5356
0
                    .SetMetaVar("<KEY>=<VALUE>")
5357
0
                    .SetPackedValuesAllowed(false);
5358
0
    arg.AddValidationAction([this, &arg]()
5359
0
                            { return ParseAndValidateKeyValue(arg); });
5360
5361
0
    arg.SetAutoCompleteFunction(
5362
0
        [this](const std::string &currentValue)
5363
0
        {
5364
0
            std::vector<std::string> oRet;
5365
5366
0
            int datasetType =
5367
0
                GDAL_OF_RASTER | GDAL_OF_VECTOR | GDAL_OF_MULTIDIM_RASTER;
5368
0
            auto outputArg = GetArg(GDAL_ARG_NAME_OUTPUT);
5369
0
            if (outputArg && (outputArg->GetType() == GAAT_DATASET ||
5370
0
                              outputArg->GetType() == GAAT_DATASET_LIST))
5371
0
            {
5372
0
                datasetType = outputArg->GetDatasetType();
5373
0
            }
5374
5375
0
            auto outputFormat = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
5376
0
            if (outputFormat && outputFormat->GetType() == GAAT_STRING &&
5377
0
                outputFormat->IsExplicitlySet())
5378
0
            {
5379
0
                auto poDriver = GetGDALDriverManager()->GetDriverByName(
5380
0
                    outputFormat->Get<std::string>().c_str());
5381
0
                if (poDriver)
5382
0
                {
5383
0
                    AddOptionsSuggestions(
5384
0
                        poDriver->GetMetadataItem(GDAL_DMD_CREATIONOPTIONLIST),
5385
0
                        datasetType, currentValue, oRet);
5386
0
                }
5387
0
                return oRet;
5388
0
            }
5389
5390
0
            if (outputArg && outputArg->GetType() == GAAT_DATASET)
5391
0
            {
5392
0
                auto poDM = GetGDALDriverManager();
5393
0
                auto &datasetValue = outputArg->Get<GDALArgDatasetValue>();
5394
0
                const auto &osDSName = datasetValue.GetName();
5395
0
                const std::string osExt = CPLGetExtensionSafe(osDSName.c_str());
5396
0
                if (!osExt.empty())
5397
0
                {
5398
0
                    std::set<std::string> oVisitedExtensions;
5399
0
                    for (int i = 0; i < poDM->GetDriverCount(); ++i)
5400
0
                    {
5401
0
                        auto poDriver = poDM->GetDriver(i);
5402
0
                        if (((datasetType & GDAL_OF_RASTER) != 0 &&
5403
0
                             poDriver->GetMetadataItem(GDAL_DCAP_RASTER)) ||
5404
0
                            ((datasetType & GDAL_OF_VECTOR) != 0 &&
5405
0
                             poDriver->GetMetadataItem(GDAL_DCAP_VECTOR)) ||
5406
0
                            ((datasetType & GDAL_OF_MULTIDIM_RASTER) != 0 &&
5407
0
                             poDriver->GetMetadataItem(
5408
0
                                 GDAL_DCAP_MULTIDIM_RASTER)))
5409
0
                        {
5410
0
                            const char *pszExtensions =
5411
0
                                poDriver->GetMetadataItem(GDAL_DMD_EXTENSIONS);
5412
0
                            if (pszExtensions)
5413
0
                            {
5414
0
                                const CPLStringList aosExts(
5415
0
                                    CSLTokenizeString2(pszExtensions, " ", 0));
5416
0
                                for (const char *pszExt : cpl::Iterate(aosExts))
5417
0
                                {
5418
0
                                    if (EQUAL(pszExt, osExt.c_str()) &&
5419
0
                                        !cpl::contains(oVisitedExtensions,
5420
0
                                                       pszExt))
5421
0
                                    {
5422
0
                                        oVisitedExtensions.insert(pszExt);
5423
0
                                        if (AddOptionsSuggestions(
5424
0
                                                poDriver->GetMetadataItem(
5425
0
                                                    GDAL_DMD_CREATIONOPTIONLIST),
5426
0
                                                datasetType, currentValue,
5427
0
                                                oRet))
5428
0
                                        {
5429
0
                                            return oRet;
5430
0
                                        }
5431
0
                                        break;
5432
0
                                    }
5433
0
                                }
5434
0
                            }
5435
0
                        }
5436
0
                    }
5437
0
                }
5438
0
            }
5439
5440
0
            return oRet;
5441
0
        });
5442
5443
0
    return arg;
5444
0
}
5445
5446
/************************************************************************/
5447
/*             GDALAlgorithm::AddLayerCreationOptionsArg()              */
5448
/************************************************************************/
5449
5450
GDALInConstructionAlgorithmArg &
5451
GDALAlgorithm::AddLayerCreationOptionsArg(std::vector<std::string> *pValue,
5452
                                          const char *helpMessage)
5453
0
{
5454
0
    auto &arg =
5455
0
        AddArg(GDAL_ARG_NAME_LAYER_CREATION_OPTION, 0,
5456
0
               MsgOrDefault(helpMessage, _("Layer creation option")), pValue)
5457
0
            .AddAlias("lco")
5458
0
            .SetMetaVar("<KEY>=<VALUE>")
5459
0
            .SetPackedValuesAllowed(false);
5460
0
    arg.AddValidationAction([this, &arg]()
5461
0
                            { return ParseAndValidateKeyValue(arg); });
5462
5463
0
    arg.SetAutoCompleteFunction(
5464
0
        [this](const std::string &currentValue)
5465
0
        {
5466
0
            std::vector<std::string> oRet;
5467
5468
0
            auto outputFormat = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
5469
0
            if (outputFormat && outputFormat->GetType() == GAAT_STRING &&
5470
0
                outputFormat->IsExplicitlySet())
5471
0
            {
5472
0
                auto poDriver = GetGDALDriverManager()->GetDriverByName(
5473
0
                    outputFormat->Get<std::string>().c_str());
5474
0
                if (poDriver)
5475
0
                {
5476
0
                    AddOptionsSuggestions(poDriver->GetMetadataItem(
5477
0
                                              GDAL_DS_LAYER_CREATIONOPTIONLIST),
5478
0
                                          GDAL_OF_VECTOR, currentValue, oRet);
5479
0
                }
5480
0
                return oRet;
5481
0
            }
5482
5483
0
            auto outputArg = GetArg(GDAL_ARG_NAME_OUTPUT);
5484
0
            if (outputArg && outputArg->GetType() == GAAT_DATASET)
5485
0
            {
5486
0
                auto poDM = GetGDALDriverManager();
5487
0
                auto &datasetValue = outputArg->Get<GDALArgDatasetValue>();
5488
0
                const auto &osDSName = datasetValue.GetName();
5489
0
                const std::string osExt = CPLGetExtensionSafe(osDSName.c_str());
5490
0
                if (!osExt.empty())
5491
0
                {
5492
0
                    std::set<std::string> oVisitedExtensions;
5493
0
                    for (int i = 0; i < poDM->GetDriverCount(); ++i)
5494
0
                    {
5495
0
                        auto poDriver = poDM->GetDriver(i);
5496
0
                        if (poDriver->GetMetadataItem(GDAL_DCAP_VECTOR))
5497
0
                        {
5498
0
                            const char *pszExtensions =
5499
0
                                poDriver->GetMetadataItem(GDAL_DMD_EXTENSIONS);
5500
0
                            if (pszExtensions)
5501
0
                            {
5502
0
                                const CPLStringList aosExts(
5503
0
                                    CSLTokenizeString2(pszExtensions, " ", 0));
5504
0
                                for (const char *pszExt : cpl::Iterate(aosExts))
5505
0
                                {
5506
0
                                    if (EQUAL(pszExt, osExt.c_str()) &&
5507
0
                                        !cpl::contains(oVisitedExtensions,
5508
0
                                                       pszExt))
5509
0
                                    {
5510
0
                                        oVisitedExtensions.insert(pszExt);
5511
0
                                        if (AddOptionsSuggestions(
5512
0
                                                poDriver->GetMetadataItem(
5513
0
                                                    GDAL_DS_LAYER_CREATIONOPTIONLIST),
5514
0
                                                GDAL_OF_VECTOR, currentValue,
5515
0
                                                oRet))
5516
0
                                        {
5517
0
                                            return oRet;
5518
0
                                        }
5519
0
                                        break;
5520
0
                                    }
5521
0
                                }
5522
0
                            }
5523
0
                        }
5524
0
                    }
5525
0
                }
5526
0
            }
5527
5528
0
            return oRet;
5529
0
        });
5530
5531
0
    return arg;
5532
0
}
5533
5534
/************************************************************************/
5535
/*                     GDALAlgorithm::AddBBOXArg()                      */
5536
/************************************************************************/
5537
5538
/** Add bbox=xmin,ymin,xmax,ymax argument. */
5539
GDALInConstructionAlgorithmArg &
5540
GDALAlgorithm::AddBBOXArg(std::vector<double> *pValue, const char *helpMessage)
5541
0
{
5542
0
    auto &arg = AddArg("bbox", 0,
5543
0
                       MsgOrDefault(helpMessage,
5544
0
                                    _("Bounding box as xmin,ymin,xmax,ymax")),
5545
0
                       pValue)
5546
0
                    .SetRepeatedArgAllowed(false)
5547
0
                    .SetMinCount(4)
5548
0
                    .SetMaxCount(4)
5549
0
                    .SetDisplayHintAboutRepetition(false);
5550
0
    arg.AddValidationAction(
5551
0
        [&arg]()
5552
0
        {
5553
0
            const auto &val = arg.Get<std::vector<double>>();
5554
0
            CPLAssert(val.size() == 4);
5555
0
            if (!(val[0] <= val[2]) || !(val[1] <= val[3]))
5556
0
            {
5557
0
                CPLError(CE_Failure, CPLE_AppDefined,
5558
0
                         "Value of 'bbox' should be xmin,ymin,xmax,ymax with "
5559
0
                         "xmin <= xmax and ymin <= ymax");
5560
0
                return false;
5561
0
            }
5562
0
            return true;
5563
0
        });
5564
0
    return arg;
5565
0
}
5566
5567
/************************************************************************/
5568
/*                  GDALAlgorithm::AddActiveLayerArg()                  */
5569
/************************************************************************/
5570
5571
GDALInConstructionAlgorithmArg &
5572
GDALAlgorithm::AddActiveLayerArg(std::string *pValue, const char *helpMessage)
5573
0
{
5574
0
    return AddArg("active-layer", 0,
5575
0
                  MsgOrDefault(helpMessage,
5576
0
                               _("Set active layer (if not specified, all)")),
5577
0
                  pValue);
5578
0
}
5579
5580
/************************************************************************/
5581
/*                  GDALAlgorithm::AddNumThreadsArg()                   */
5582
/************************************************************************/
5583
5584
GDALInConstructionAlgorithmArg &
5585
GDALAlgorithm::AddNumThreadsArg(int *pValue, std::string *pStrValue,
5586
                                const char *helpMessage)
5587
0
{
5588
0
    auto &arg =
5589
0
        AddArg(GDAL_ARG_NAME_NUM_THREADS, 'j',
5590
0
               MsgOrDefault(helpMessage, _("Number of jobs (or ALL_CPUS)")),
5591
0
               pStrValue);
5592
5593
0
    AddArg(GDAL_ARG_NAME_NUM_THREADS_INT_HIDDEN, 0,
5594
0
           _("Number of jobs (read-only, hidden argument)"), pValue)
5595
0
        .SetHidden();
5596
5597
0
    auto lambda = [this, &arg, pValue, pStrValue]
5598
0
    {
5599
0
        bool bOK = false;
5600
0
        const char *pszVal = CPLGetConfigOption("GDAL_NUM_THREADS", nullptr);
5601
0
        const int nLimit = std::clamp(
5602
0
            pszVal && !EQUAL(pszVal, "ALL_CPUS") ? atoi(pszVal) : INT_MAX, 1,
5603
0
            CPLGetNumCPUs());
5604
0
        const int nNumThreads =
5605
0
            GDALGetNumThreads(pStrValue->c_str(), nLimit,
5606
0
                              /* bDefaultToAllCPUs = */ false, nullptr, &bOK);
5607
0
        if (bOK)
5608
0
        {
5609
0
            *pValue = nNumThreads;
5610
0
        }
5611
0
        else
5612
0
        {
5613
0
            ReportError(CE_Failure, CPLE_IllegalArg,
5614
0
                        "Invalid value for '%s' argument",
5615
0
                        arg.GetName().c_str());
5616
0
        }
5617
0
        return bOK;
5618
0
    };
5619
0
    if (!pStrValue->empty())
5620
0
    {
5621
0
        arg.SetDefault(*pStrValue);
5622
0
        lambda();
5623
0
    }
5624
0
    arg.AddValidationAction(std::move(lambda));
5625
0
    return arg;
5626
0
}
5627
5628
/************************************************************************/
5629
/*                 GDALAlgorithm::AddAbsolutePathArg()                  */
5630
/************************************************************************/
5631
5632
GDALInConstructionAlgorithmArg &
5633
GDALAlgorithm::AddAbsolutePathArg(bool *pValue, const char *helpMessage)
5634
0
{
5635
0
    return AddArg(
5636
0
        "absolute-path", 0,
5637
0
        MsgOrDefault(helpMessage, _("Whether the path to the input dataset "
5638
0
                                    "should be stored as an absolute path")),
5639
0
        pValue);
5640
0
}
5641
5642
/************************************************************************/
5643
/*               GDALAlgorithm::AddPixelFunctionNameArg()               */
5644
/************************************************************************/
5645
5646
GDALInConstructionAlgorithmArg &
5647
GDALAlgorithm::AddPixelFunctionNameArg(std::string *pValue,
5648
                                       const char *helpMessage)
5649
0
{
5650
5651
0
    const auto pixelFunctionNames =
5652
0
        VRTDerivedRasterBand::GetPixelFunctionNames();
5653
0
    return AddArg(
5654
0
               "pixel-function", 0,
5655
0
               MsgOrDefault(
5656
0
                   helpMessage,
5657
0
                   _("Specify a pixel function to calculate output value from "
5658
0
                     "overlapping inputs")),
5659
0
               pValue)
5660
0
        .SetChoices(pixelFunctionNames);
5661
0
}
5662
5663
/************************************************************************/
5664
/*               GDALAlgorithm::AddPixelFunctionArgsArg()               */
5665
/************************************************************************/
5666
5667
GDALInConstructionAlgorithmArg &
5668
GDALAlgorithm::AddPixelFunctionArgsArg(std::vector<std::string> *pValue,
5669
                                       const char *helpMessage)
5670
0
{
5671
0
    auto &pixelFunctionArgArg =
5672
0
        AddArg("pixel-function-arg", 0,
5673
0
               MsgOrDefault(
5674
0
                   helpMessage,
5675
0
                   _("Specify argument(s) to pass to the pixel function")),
5676
0
               pValue)
5677
0
            .SetMetaVar("<NAME>=<VALUE>")
5678
0
            .SetRepeatedArgAllowed(true);
5679
0
    pixelFunctionArgArg.AddValidationAction(
5680
0
        [this, &pixelFunctionArgArg]()
5681
0
        { return ParseAndValidateKeyValue(pixelFunctionArgArg); });
5682
5683
0
    pixelFunctionArgArg.SetAutoCompleteFunction(
5684
0
        [this](const std::string &currentValue)
5685
0
        {
5686
0
            std::string pixelFunction;
5687
0
            const auto pixelFunctionArg = GetArg("pixel-function");
5688
0
            if (pixelFunctionArg && pixelFunctionArg->GetType() == GAAT_STRING)
5689
0
            {
5690
0
                pixelFunction = pixelFunctionArg->Get<std::string>();
5691
0
            }
5692
5693
0
            std::vector<std::string> ret;
5694
5695
0
            if (!pixelFunction.empty())
5696
0
            {
5697
0
                const auto *pair = VRTDerivedRasterBand::GetPixelFunction(
5698
0
                    pixelFunction.c_str());
5699
0
                if (!pair)
5700
0
                {
5701
0
                    ret.push_back("**");
5702
                    // Non printable UTF-8 space, to avoid autocompletion to pickup on 'd'
5703
0
                    ret.push_back(std::string("\xC2\xA0"
5704
0
                                              "Invalid pixel function name"));
5705
0
                }
5706
0
                else if (pair->second.find("Argument name=") ==
5707
0
                         std::string::npos)
5708
0
                {
5709
0
                    ret.push_back("**");
5710
                    // Non printable UTF-8 space, to avoid autocompletion to pickup on 'd'
5711
0
                    ret.push_back(
5712
0
                        std::string(
5713
0
                            "\xC2\xA0"
5714
0
                            "No pixel function arguments for pixel function '")
5715
0
                            .append(pixelFunction)
5716
0
                            .append("'"));
5717
0
                }
5718
0
                else
5719
0
                {
5720
0
                    AddOptionsSuggestions(pair->second.c_str(), 0, currentValue,
5721
0
                                          ret);
5722
0
                }
5723
0
            }
5724
5725
0
            return ret;
5726
0
        });
5727
5728
0
    return pixelFunctionArgArg;
5729
0
}
5730
5731
/************************************************************************/
5732
/*                   GDALAlgorithm::AddProgressArg()                    */
5733
/************************************************************************/
5734
5735
void GDALAlgorithm::AddProgressArg()
5736
0
{
5737
0
    AddArg(GDAL_ARG_NAME_QUIET, 'q', _("Quiet mode (no progress bar)"),
5738
0
           &m_quiet)
5739
0
        .SetHiddenForAPI()
5740
0
        .SetCategory(GAAC_COMMON)
5741
0
        .AddAction([this]() { m_progressBarRequested = false; });
5742
5743
0
    AddArg("progress", 0, _("Display progress bar"), &m_progressBarRequested)
5744
0
        .SetHidden();
5745
0
}
5746
5747
/************************************************************************/
5748
/*                         GDALAlgorithm::Run()                         */
5749
/************************************************************************/
5750
5751
bool GDALAlgorithm::Run(GDALProgressFunc pfnProgress, void *pProgressData)
5752
0
{
5753
0
    WarnIfDeprecated();
5754
5755
0
    if (m_selectedSubAlg)
5756
0
    {
5757
0
        if (m_calledFromCommandLine)
5758
0
            m_selectedSubAlg->m_calledFromCommandLine = true;
5759
0
        return m_selectedSubAlg->Run(pfnProgress, pProgressData);
5760
0
    }
5761
5762
0
    if (m_helpRequested || m_helpDocRequested)
5763
0
    {
5764
0
        if (m_calledFromCommandLine)
5765
0
            printf("%s", GetUsageForCLI(false).c_str()); /*ok*/
5766
0
        return true;
5767
0
    }
5768
5769
0
    if (m_JSONUsageRequested)
5770
0
    {
5771
0
        if (m_calledFromCommandLine)
5772
0
            printf("%s", GetUsageAsJSON().c_str()); /*ok*/
5773
0
        return true;
5774
0
    }
5775
5776
0
    if (!ValidateArguments())
5777
0
        return false;
5778
5779
0
    switch (ProcessGDALGOutput())
5780
0
    {
5781
0
        case ProcessGDALGOutputRet::GDALG_ERROR:
5782
0
            return false;
5783
5784
0
        case ProcessGDALGOutputRet::GDALG_OK:
5785
0
            return true;
5786
5787
0
        case ProcessGDALGOutputRet::NOT_GDALG:
5788
0
            break;
5789
0
    }
5790
5791
0
    if (m_executionForStreamOutput)
5792
0
    {
5793
0
        if (!CheckSafeForStreamOutput())
5794
0
        {
5795
0
            return false;
5796
0
        }
5797
0
    }
5798
5799
0
    return RunImpl(pfnProgress, pProgressData);
5800
0
}
5801
5802
/************************************************************************/
5803
/*              GDALAlgorithm::CheckSafeForStreamOutput()               */
5804
/************************************************************************/
5805
5806
bool GDALAlgorithm::CheckSafeForStreamOutput()
5807
0
{
5808
0
    const auto outputFormatArg = GetArg(GDAL_ARG_NAME_OUTPUT_FORMAT);
5809
0
    if (outputFormatArg && outputFormatArg->GetType() == GAAT_STRING)
5810
0
    {
5811
0
        const auto &val = outputFormatArg->GDALAlgorithmArg::Get<std::string>();
5812
0
        if (!EQUAL(val.c_str(), "stream"))
5813
0
        {
5814
            // For security reasons, to avoid that reading a .gdalg.json file
5815
            // writes a file on the file system.
5816
0
            ReportError(
5817
0
                CE_Failure, CPLE_NotSupported,
5818
0
                "in streamed execution, --format stream should be used");
5819
0
            return false;
5820
0
        }
5821
0
    }
5822
0
    return true;
5823
0
}
5824
5825
/************************************************************************/
5826
/*                      GDALAlgorithm::Finalize()                       */
5827
/************************************************************************/
5828
5829
bool GDALAlgorithm::Finalize()
5830
0
{
5831
0
    bool ret = true;
5832
0
    if (m_selectedSubAlg)
5833
0
        ret = m_selectedSubAlg->Finalize();
5834
5835
0
    for (auto &arg : m_args)
5836
0
    {
5837
0
        if (arg->GetType() == GAAT_DATASET)
5838
0
        {
5839
0
            ret = arg->Get<GDALArgDatasetValue>().Close() && ret;
5840
0
        }
5841
0
        else if (arg->GetType() == GAAT_DATASET_LIST)
5842
0
        {
5843
0
            for (auto &ds : arg->Get<std::vector<GDALArgDatasetValue>>())
5844
0
            {
5845
0
                ret = ds.Close() && ret;
5846
0
            }
5847
0
        }
5848
0
    }
5849
0
    return ret;
5850
0
}
5851
5852
/************************************************************************/
5853
/*                  GDALAlgorithm::GetArgNamesForCLI()                  */
5854
/************************************************************************/
5855
5856
std::pair<std::vector<std::pair<GDALAlgorithmArg *, std::string>>, size_t>
5857
GDALAlgorithm::GetArgNamesForCLI() const
5858
0
{
5859
0
    std::vector<std::pair<GDALAlgorithmArg *, std::string>> options;
5860
5861
0
    size_t maxOptLen = 0;
5862
0
    for (const auto &arg : m_args)
5863
0
    {
5864
0
        if (arg->IsHidden() || arg->IsHiddenForCLI())
5865
0
            continue;
5866
0
        std::string opt;
5867
0
        bool addComma = false;
5868
0
        if (!arg->GetShortName().empty())
5869
0
        {
5870
0
            opt += '-';
5871
0
            opt += arg->GetShortName();
5872
0
            addComma = true;
5873
0
        }
5874
0
        for (char alias : arg->GetShortNameAliases())
5875
0
        {
5876
0
            if (addComma)
5877
0
                opt += ", ";
5878
0
            opt += "-";
5879
0
            opt += alias;
5880
0
            addComma = true;
5881
0
        }
5882
0
        for (const std::string &alias : arg->GetAliases())
5883
0
        {
5884
0
            if (addComma)
5885
0
                opt += ", ";
5886
0
            opt += "--";
5887
0
            opt += alias;
5888
0
            addComma = true;
5889
0
        }
5890
0
        if (!arg->GetName().empty())
5891
0
        {
5892
0
            if (addComma)
5893
0
                opt += ", ";
5894
0
            opt += "--";
5895
0
            opt += arg->GetName();
5896
0
        }
5897
0
        const auto &metaVar = arg->GetMetaVar();
5898
0
        if (!metaVar.empty())
5899
0
        {
5900
0
            opt += ' ';
5901
0
            if (metaVar.front() != '<')
5902
0
                opt += '<';
5903
0
            opt += metaVar;
5904
0
            if (metaVar.back() != '>')
5905
0
                opt += '>';
5906
0
        }
5907
0
        maxOptLen = std::max(maxOptLen, opt.size());
5908
0
        options.emplace_back(arg.get(), opt);
5909
0
    }
5910
5911
0
    return std::make_pair(std::move(options), maxOptLen);
5912
0
}
5913
5914
/************************************************************************/
5915
/*                   GDALAlgorithm::GetUsageForCLI()                    */
5916
/************************************************************************/
5917
5918
std::string
5919
GDALAlgorithm::GetUsageForCLI(bool shortUsage,
5920
                              const UsageOptions &usageOptions) const
5921
0
{
5922
0
    if (m_selectedSubAlg)
5923
0
        return m_selectedSubAlg->GetUsageForCLI(shortUsage, usageOptions);
5924
5925
0
    std::string osRet(usageOptions.isPipelineStep ? "*" : "Usage:");
5926
0
    std::string osPath;
5927
0
    for (const std::string &s : m_callPath)
5928
0
    {
5929
0
        if (!osPath.empty())
5930
0
            osPath += ' ';
5931
0
        osPath += s;
5932
0
    }
5933
0
    osRet += ' ';
5934
0
    osRet += osPath;
5935
5936
0
    bool hasNonPositionals = false;
5937
0
    for (const auto &arg : m_args)
5938
0
    {
5939
0
        if (!arg->IsHidden() && !arg->IsHiddenForCLI() && !arg->IsPositional())
5940
0
            hasNonPositionals = true;
5941
0
    }
5942
5943
0
    if (HasSubAlgorithms())
5944
0
    {
5945
0
        if (m_callPath.size() == 1)
5946
0
        {
5947
0
            osRet += " <COMMAND>";
5948
0
            if (hasNonPositionals)
5949
0
                osRet += " [OPTIONS]";
5950
0
            if (usageOptions.isPipelineStep)
5951
0
            {
5952
0
                const size_t nLenFirstLine = osRet.size();
5953
0
                osRet += '\n';
5954
0
                osRet.append(nLenFirstLine, '-');
5955
0
                osRet += '\n';
5956
0
            }
5957
0
            osRet += "\nwhere <COMMAND> is one of:\n";
5958
0
        }
5959
0
        else
5960
0
        {
5961
0
            osRet += " <SUBCOMMAND>";
5962
0
            if (hasNonPositionals)
5963
0
                osRet += " [OPTIONS]";
5964
0
            if (usageOptions.isPipelineStep)
5965
0
            {
5966
0
                const size_t nLenFirstLine = osRet.size();
5967
0
                osRet += '\n';
5968
0
                osRet.append(nLenFirstLine, '-');
5969
0
                osRet += '\n';
5970
0
            }
5971
0
            osRet += "\nwhere <SUBCOMMAND> is one of:\n";
5972
0
        }
5973
0
        size_t maxNameLen = 0;
5974
0
        for (const auto &subAlgName : GetSubAlgorithmNames())
5975
0
        {
5976
0
            maxNameLen = std::max(maxNameLen, subAlgName.size());
5977
0
        }
5978
0
        for (const auto &subAlgName : GetSubAlgorithmNames())
5979
0
        {
5980
0
            auto subAlg = InstantiateSubAlgorithm(subAlgName);
5981
0
            if (subAlg && !subAlg->IsHidden())
5982
0
            {
5983
0
                const std::string &name(subAlg->GetName());
5984
0
                osRet += "  - ";
5985
0
                osRet += name;
5986
0
                osRet += ": ";
5987
0
                osRet.append(maxNameLen - name.size(), ' ');
5988
0
                osRet += subAlg->GetDescription();
5989
0
                if (!subAlg->m_aliases.empty())
5990
0
                {
5991
0
                    bool first = true;
5992
0
                    for (const auto &alias : subAlg->GetAliases())
5993
0
                    {
5994
0
                        if (alias ==
5995
0
                            GDALAlgorithmRegistry::HIDDEN_ALIAS_SEPARATOR)
5996
0
                            break;
5997
0
                        if (first)
5998
0
                            osRet += " (alias: ";
5999
0
                        else
6000
0
                            osRet += ", ";
6001
0
                        osRet += alias;
6002
0
                        first = false;
6003
0
                    }
6004
0
                    if (!first)
6005
0
                    {
6006
0
                        osRet += ')';
6007
0
                    }
6008
0
                }
6009
0
                osRet += '\n';
6010
0
            }
6011
0
        }
6012
6013
0
        if (shortUsage && hasNonPositionals)
6014
0
        {
6015
0
            osRet += "\nTry '";
6016
0
            osRet += osPath;
6017
0
            osRet += " --help' for help.\n";
6018
0
        }
6019
0
    }
6020
0
    else
6021
0
    {
6022
0
        if (!m_args.empty())
6023
0
        {
6024
0
            if (hasNonPositionals)
6025
0
                osRet += " [OPTIONS]";
6026
0
            for (const auto *arg : m_positionalArgs)
6027
0
            {
6028
0
                if ((!arg->IsHidden() && !arg->IsHiddenForCLI()) ||
6029
0
                    (GetName() == "pipeline" && arg->GetName() == "pipeline"))
6030
0
                {
6031
0
                    const bool optional =
6032
0
                        (!arg->IsRequired() && !(GetName() == "pipeline" &&
6033
0
                                                 arg->GetName() == "pipeline"));
6034
0
                    osRet += ' ';
6035
0
                    if (optional)
6036
0
                        osRet += '[';
6037
0
                    const std::string &metavar = arg->GetMetaVar();
6038
0
                    if (!metavar.empty() && metavar[0] == '<')
6039
0
                    {
6040
0
                        osRet += metavar;
6041
0
                    }
6042
0
                    else
6043
0
                    {
6044
0
                        osRet += '<';
6045
0
                        osRet += metavar;
6046
0
                        osRet += '>';
6047
0
                    }
6048
0
                    if (arg->GetType() == GAAT_DATASET_LIST &&
6049
0
                        arg->GetMaxCount() > 1)
6050
0
                    {
6051
0
                        osRet += "...";
6052
0
                    }
6053
0
                    if (optional)
6054
0
                        osRet += ']';
6055
0
                }
6056
0
            }
6057
0
        }
6058
6059
0
        const size_t nLenFirstLine = osRet.size();
6060
0
        osRet += '\n';
6061
0
        if (usageOptions.isPipelineStep)
6062
0
        {
6063
0
            osRet.append(nLenFirstLine, '-');
6064
0
            osRet += '\n';
6065
0
        }
6066
6067
0
        if (shortUsage)
6068
0
        {
6069
0
            osRet += "Try '";
6070
0
            osRet += osPath;
6071
0
            osRet += " --help' for help.\n";
6072
0
            return osRet;
6073
0
        }
6074
6075
0
        osRet += '\n';
6076
0
        osRet += m_description;
6077
0
        osRet += '\n';
6078
0
    }
6079
6080
0
    if (!m_args.empty() && !shortUsage)
6081
0
    {
6082
0
        std::vector<std::pair<GDALAlgorithmArg *, std::string>> options;
6083
0
        size_t maxOptLen;
6084
0
        std::tie(options, maxOptLen) = GetArgNamesForCLI();
6085
0
        if (usageOptions.maxOptLen)
6086
0
            maxOptLen = usageOptions.maxOptLen;
6087
6088
0
        const std::string userProvidedOpt = "--<user-provided-option>=<value>";
6089
0
        if (m_arbitraryLongNameArgsAllowed)
6090
0
            maxOptLen = std::max(maxOptLen, userProvidedOpt.size());
6091
6092
0
        const auto OutputArg =
6093
0
            [this, maxOptLen, &osRet](const GDALAlgorithmArg *arg,
6094
0
                                      const std::string &opt)
6095
0
        {
6096
0
            osRet += "  ";
6097
0
            osRet += opt;
6098
0
            osRet += "  ";
6099
0
            osRet.append(maxOptLen - opt.size(), ' ');
6100
0
            osRet += arg->GetDescription();
6101
6102
0
            const auto &choices = arg->GetChoices();
6103
0
            if (!choices.empty())
6104
0
            {
6105
0
                osRet += ". ";
6106
0
                osRet += arg->GetMetaVar();
6107
0
                osRet += '=';
6108
0
                bool firstChoice = true;
6109
0
                for (const auto &choice : choices)
6110
0
                {
6111
0
                    if (!firstChoice)
6112
0
                        osRet += '|';
6113
0
                    osRet += choice;
6114
0
                    firstChoice = false;
6115
0
                }
6116
0
            }
6117
6118
0
            if (arg->GetType() == GAAT_DATASET ||
6119
0
                arg->GetType() == GAAT_DATASET_LIST)
6120
0
            {
6121
0
                if (arg->GetDatasetInputFlags() == GADV_NAME &&
6122
0
                    arg->GetDatasetOutputFlags() == GADV_OBJECT)
6123
0
                {
6124
0
                    osRet += " (created by algorithm)";
6125
0
                }
6126
0
            }
6127
6128
0
            if (arg->GetType() == GAAT_STRING && arg->HasDefaultValue())
6129
0
            {
6130
0
                osRet += " (default: ";
6131
0
                osRet += arg->GetDefault<std::string>();
6132
0
                osRet += ')';
6133
0
            }
6134
0
            else if (arg->GetType() == GAAT_BOOLEAN && arg->HasDefaultValue())
6135
0
            {
6136
0
                if (arg->GetDefault<bool>())
6137
0
                    osRet += " (default: true)";
6138
0
            }
6139
0
            else if (arg->GetType() == GAAT_INTEGER && arg->HasDefaultValue())
6140
0
            {
6141
0
                osRet += " (default: ";
6142
0
                osRet += CPLSPrintf("%d", arg->GetDefault<int>());
6143
0
                osRet += ')';
6144
0
            }
6145
0
            else if (arg->GetType() == GAAT_REAL && arg->HasDefaultValue())
6146
0
            {
6147
0
                osRet += " (default: ";
6148
0
                osRet += CPLSPrintf("%g", arg->GetDefault<double>());
6149
0
                osRet += ')';
6150
0
            }
6151
0
            else if (arg->GetType() == GAAT_STRING_LIST &&
6152
0
                     arg->HasDefaultValue())
6153
0
            {
6154
0
                const auto &defaultVal =
6155
0
                    arg->GetDefault<std::vector<std::string>>();
6156
0
                if (defaultVal.size() == 1)
6157
0
                {
6158
0
                    osRet += " (default: ";
6159
0
                    osRet += defaultVal[0];
6160
0
                    osRet += ')';
6161
0
                }
6162
0
            }
6163
0
            else if (arg->GetType() == GAAT_INTEGER_LIST &&
6164
0
                     arg->HasDefaultValue())
6165
0
            {
6166
0
                const auto &defaultVal = arg->GetDefault<std::vector<int>>();
6167
0
                if (defaultVal.size() == 1)
6168
0
                {
6169
0
                    osRet += " (default: ";
6170
0
                    osRet += CPLSPrintf("%d", defaultVal[0]);
6171
0
                    osRet += ')';
6172
0
                }
6173
0
            }
6174
0
            else if (arg->GetType() == GAAT_REAL_LIST && arg->HasDefaultValue())
6175
0
            {
6176
0
                const auto &defaultVal = arg->GetDefault<std::vector<double>>();
6177
0
                if (defaultVal.size() == 1)
6178
0
                {
6179
0
                    osRet += " (default: ";
6180
0
                    osRet += CPLSPrintf("%g", defaultVal[0]);
6181
0
                    osRet += ')';
6182
0
                }
6183
0
            }
6184
6185
0
            if (arg->GetDisplayHintAboutRepetition())
6186
0
            {
6187
0
                if (arg->GetMinCount() > 0 &&
6188
0
                    arg->GetMinCount() == arg->GetMaxCount())
6189
0
                {
6190
0
                    if (arg->GetMinCount() != 1)
6191
0
                        osRet += CPLSPrintf(" [%d values]", arg->GetMaxCount());
6192
0
                }
6193
0
                else if (arg->GetMinCount() > 0 &&
6194
0
                         arg->GetMaxCount() < GDALAlgorithmArgDecl::UNBOUNDED)
6195
0
                {
6196
0
                    osRet += CPLSPrintf(" [%d..%d values]", arg->GetMinCount(),
6197
0
                                        arg->GetMaxCount());
6198
0
                }
6199
0
                else if (arg->GetMinCount() > 0)
6200
0
                {
6201
0
                    osRet += CPLSPrintf(" [%d.. values]", arg->GetMinCount());
6202
0
                }
6203
0
                else if (arg->GetMaxCount() > 1)
6204
0
                {
6205
0
                    osRet += " [may be repeated]";
6206
0
                }
6207
0
            }
6208
6209
0
            if (arg->IsRequired())
6210
0
            {
6211
0
                osRet += " [required]";
6212
0
            }
6213
6214
0
            osRet += '\n';
6215
6216
0
            const auto &mutualExclusionGroup = arg->GetMutualExclusionGroup();
6217
0
            if (!mutualExclusionGroup.empty())
6218
0
            {
6219
0
                std::string otherArgs;
6220
0
                for (const auto &otherArg : m_args)
6221
0
                {
6222
0
                    if (otherArg->IsHidden() || otherArg->IsHiddenForCLI() ||
6223
0
                        otherArg.get() == arg)
6224
0
                        continue;
6225
0
                    if (otherArg->GetMutualExclusionGroup() ==
6226
0
                        mutualExclusionGroup)
6227
0
                    {
6228
0
                        if (!otherArgs.empty())
6229
0
                            otherArgs += ", ";
6230
0
                        otherArgs += "--";
6231
0
                        otherArgs += otherArg->GetName();
6232
0
                    }
6233
0
                }
6234
0
                if (!otherArgs.empty())
6235
0
                {
6236
0
                    osRet += "  ";
6237
0
                    osRet += "  ";
6238
0
                    osRet.append(maxOptLen, ' ');
6239
0
                    osRet += "Mutually exclusive with ";
6240
0
                    osRet += otherArgs;
6241
0
                    osRet += '\n';
6242
0
                }
6243
0
            }
6244
0
        };
6245
6246
0
        if (!m_positionalArgs.empty())
6247
0
        {
6248
0
            osRet += "\nPositional arguments:\n";
6249
0
            for (const auto &[arg, opt] : options)
6250
0
            {
6251
0
                if (arg->IsPositional())
6252
0
                    OutputArg(arg, opt);
6253
0
            }
6254
0
        }
6255
6256
0
        if (hasNonPositionals)
6257
0
        {
6258
0
            bool hasCommon = false;
6259
0
            bool hasBase = false;
6260
0
            bool hasAdvanced = false;
6261
0
            bool hasEsoteric = false;
6262
0
            std::vector<std::string> categories;
6263
0
            for (const auto &iter : options)
6264
0
            {
6265
0
                const auto &arg = iter.first;
6266
0
                if (!arg->IsPositional())
6267
0
                {
6268
0
                    const auto &category = arg->GetCategory();
6269
0
                    if (category == GAAC_COMMON)
6270
0
                    {
6271
0
                        hasCommon = true;
6272
0
                    }
6273
0
                    else if (category == GAAC_BASE)
6274
0
                    {
6275
0
                        hasBase = true;
6276
0
                    }
6277
0
                    else if (category == GAAC_ADVANCED)
6278
0
                    {
6279
0
                        hasAdvanced = true;
6280
0
                    }
6281
0
                    else if (category == GAAC_ESOTERIC)
6282
0
                    {
6283
0
                        hasEsoteric = true;
6284
0
                    }
6285
0
                    else if (std::find(categories.begin(), categories.end(),
6286
0
                                       category) == categories.end())
6287
0
                    {
6288
0
                        categories.push_back(category);
6289
0
                    }
6290
0
                }
6291
0
            }
6292
0
            if (hasAdvanced || m_arbitraryLongNameArgsAllowed)
6293
0
                categories.insert(categories.begin(), GAAC_ADVANCED);
6294
0
            if (hasBase)
6295
0
                categories.insert(categories.begin(), GAAC_BASE);
6296
0
            if (hasCommon && !usageOptions.isPipelineStep)
6297
0
                categories.insert(categories.begin(), GAAC_COMMON);
6298
0
            if (hasEsoteric)
6299
0
                categories.push_back(GAAC_ESOTERIC);
6300
6301
0
            for (const auto &category : categories)
6302
0
            {
6303
0
                osRet += "\n";
6304
0
                if (category != GAAC_BASE)
6305
0
                {
6306
0
                    osRet += category;
6307
0
                    osRet += ' ';
6308
0
                }
6309
0
                osRet += "Options:\n";
6310
0
                for (const auto &[arg, opt] : options)
6311
0
                {
6312
0
                    if (!arg->IsPositional() && arg->GetCategory() == category)
6313
0
                        OutputArg(arg, opt);
6314
0
                }
6315
0
                if (m_arbitraryLongNameArgsAllowed && category == GAAC_ADVANCED)
6316
0
                {
6317
0
                    osRet += "  ";
6318
0
                    osRet += userProvidedOpt;
6319
0
                    osRet += "  ";
6320
0
                    if (userProvidedOpt.size() < maxOptLen)
6321
0
                        osRet.append(maxOptLen - userProvidedOpt.size(), ' ');
6322
0
                    osRet += "Argument provided by user";
6323
0
                    osRet += '\n';
6324
0
                }
6325
0
            }
6326
0
        }
6327
0
    }
6328
6329
0
    if (!m_longDescription.empty())
6330
0
    {
6331
0
        osRet += '\n';
6332
0
        osRet += m_longDescription;
6333
0
        osRet += '\n';
6334
0
    }
6335
6336
0
    if (!m_helpDocRequested && !usageOptions.isPipelineMain)
6337
0
    {
6338
0
        if (!m_helpURL.empty())
6339
0
        {
6340
0
            osRet += "\nFor more details, consult ";
6341
0
            osRet += GetHelpFullURL();
6342
0
            osRet += '\n';
6343
0
        }
6344
0
        osRet += GetUsageForCLIEnd();
6345
0
    }
6346
6347
0
    return osRet;
6348
0
}
6349
6350
/************************************************************************/
6351
/*                  GDALAlgorithm::GetUsageForCLIEnd()                  */
6352
/************************************************************************/
6353
6354
//! @cond Doxygen_Suppress
6355
std::string GDALAlgorithm::GetUsageForCLIEnd() const
6356
0
{
6357
0
    std::string osRet;
6358
6359
0
    if (!m_callPath.empty() && m_callPath[0] == "gdal")
6360
0
    {
6361
0
        osRet += "\nWARNING: the gdal command is provisionally provided as an "
6362
0
                 "alternative interface to GDAL and OGR command line "
6363
0
                 "utilities.\nThe project reserves the right to modify, "
6364
0
                 "rename, reorganize, and change the behavior of the utility\n"
6365
0
                 "until it is officially frozen in a future feature release of "
6366
0
                 "GDAL.\n";
6367
0
    }
6368
0
    return osRet;
6369
0
}
6370
6371
//! @endcond
6372
6373
/************************************************************************/
6374
/*                   GDALAlgorithm::GetUsageAsJSON()                    */
6375
/************************************************************************/
6376
6377
std::string GDALAlgorithm::GetUsageAsJSON() const
6378
0
{
6379
0
    CPLJSONDocument oDoc;
6380
0
    auto oRoot = oDoc.GetRoot();
6381
6382
0
    if (m_displayInJSONUsage)
6383
0
    {
6384
0
        oRoot.Add("name", m_name);
6385
0
        CPLJSONArray jFullPath;
6386
0
        for (const std::string &s : m_callPath)
6387
0
        {
6388
0
            jFullPath.Add(s);
6389
0
        }
6390
0
        oRoot.Add("full_path", jFullPath);
6391
0
    }
6392
6393
0
    oRoot.Add("description", m_description);
6394
0
    if (!m_helpURL.empty())
6395
0
    {
6396
0
        oRoot.Add("short_url", m_helpURL);
6397
0
        oRoot.Add("url", GetHelpFullURL());
6398
0
    }
6399
6400
0
    CPLJSONArray jSubAlgorithms;
6401
0
    for (const auto &subAlgName : GetSubAlgorithmNames())
6402
0
    {
6403
0
        auto subAlg = InstantiateSubAlgorithm(subAlgName);
6404
0
        if (subAlg && subAlg->m_displayInJSONUsage && !subAlg->IsHidden())
6405
0
        {
6406
0
            CPLJSONDocument oSubDoc;
6407
0
            CPL_IGNORE_RET_VAL(oSubDoc.LoadMemory(subAlg->GetUsageAsJSON()));
6408
0
            jSubAlgorithms.Add(oSubDoc.GetRoot());
6409
0
        }
6410
0
    }
6411
0
    oRoot.Add("sub_algorithms", jSubAlgorithms);
6412
6413
0
    if (m_arbitraryLongNameArgsAllowed)
6414
0
    {
6415
0
        oRoot.Add("user_provided_arguments_allowed", true);
6416
0
    }
6417
6418
0
    const auto ProcessArg = [](const GDALAlgorithmArg *arg)
6419
0
    {
6420
0
        CPLJSONObject jArg;
6421
0
        jArg.Add("name", arg->GetName());
6422
0
        jArg.Add("type", GDALAlgorithmArgTypeName(arg->GetType()));
6423
0
        jArg.Add("description", arg->GetDescription());
6424
6425
0
        const auto &metaVar = arg->GetMetaVar();
6426
0
        if (!metaVar.empty() && metaVar != CPLString(arg->GetName()).toupper())
6427
0
        {
6428
0
            if (metaVar.front() == '<' && metaVar.back() == '>' &&
6429
0
                metaVar.substr(1, metaVar.size() - 2).find('>') ==
6430
0
                    std::string::npos)
6431
0
                jArg.Add("metavar", metaVar.substr(1, metaVar.size() - 2));
6432
0
            else
6433
0
                jArg.Add("metavar", metaVar);
6434
0
        }
6435
6436
0
        const auto &choices = arg->GetChoices();
6437
0
        if (!choices.empty())
6438
0
        {
6439
0
            CPLJSONArray jChoices;
6440
0
            for (const auto &choice : choices)
6441
0
                jChoices.Add(choice);
6442
0
            jArg.Add("choices", jChoices);
6443
0
        }
6444
0
        if (arg->HasDefaultValue())
6445
0
        {
6446
0
            switch (arg->GetType())
6447
0
            {
6448
0
                case GAAT_BOOLEAN:
6449
0
                    jArg.Add("default", arg->GetDefault<bool>());
6450
0
                    break;
6451
0
                case GAAT_STRING:
6452
0
                    jArg.Add("default", arg->GetDefault<std::string>());
6453
0
                    break;
6454
0
                case GAAT_INTEGER:
6455
0
                    jArg.Add("default", arg->GetDefault<int>());
6456
0
                    break;
6457
0
                case GAAT_REAL:
6458
0
                    jArg.Add("default", arg->GetDefault<double>());
6459
0
                    break;
6460
0
                case GAAT_STRING_LIST:
6461
0
                {
6462
0
                    const auto &val =
6463
0
                        arg->GetDefault<std::vector<std::string>>();
6464
0
                    if (val.size() == 1)
6465
0
                    {
6466
0
                        jArg.Add("default", val[0]);
6467
0
                    }
6468
0
                    else
6469
0
                    {
6470
0
                        CPLJSONArray jArr;
6471
0
                        for (const auto &s : val)
6472
0
                        {
6473
0
                            jArr.Add(s);
6474
0
                        }
6475
0
                        jArg.Add("default", jArr);
6476
0
                    }
6477
0
                    break;
6478
0
                }
6479
0
                case GAAT_INTEGER_LIST:
6480
0
                {
6481
0
                    const auto &val = arg->GetDefault<std::vector<int>>();
6482
0
                    if (val.size() == 1)
6483
0
                    {
6484
0
                        jArg.Add("default", val[0]);
6485
0
                    }
6486
0
                    else
6487
0
                    {
6488
0
                        CPLJSONArray jArr;
6489
0
                        for (int i : val)
6490
0
                        {
6491
0
                            jArr.Add(i);
6492
0
                        }
6493
0
                        jArg.Add("default", jArr);
6494
0
                    }
6495
0
                    break;
6496
0
                }
6497
0
                case GAAT_REAL_LIST:
6498
0
                {
6499
0
                    const auto &val = arg->GetDefault<std::vector<double>>();
6500
0
                    if (val.size() == 1)
6501
0
                    {
6502
0
                        jArg.Add("default", val[0]);
6503
0
                    }
6504
0
                    else
6505
0
                    {
6506
0
                        CPLJSONArray jArr;
6507
0
                        for (double d : val)
6508
0
                        {
6509
0
                            jArr.Add(d);
6510
0
                        }
6511
0
                        jArg.Add("default", jArr);
6512
0
                    }
6513
0
                    break;
6514
0
                }
6515
0
                case GAAT_DATASET:
6516
0
                case GAAT_DATASET_LIST:
6517
0
                    CPLError(CE_Warning, CPLE_AppDefined,
6518
0
                             "Unhandled default value for arg %s",
6519
0
                             arg->GetName().c_str());
6520
0
                    break;
6521
0
            }
6522
0
        }
6523
6524
0
        const auto [minVal, minValIsIncluded] = arg->GetMinValue();
6525
0
        if (!std::isnan(minVal))
6526
0
        {
6527
0
            if (arg->GetType() == GAAT_INTEGER ||
6528
0
                arg->GetType() == GAAT_INTEGER_LIST)
6529
0
                jArg.Add("min_value", static_cast<int>(minVal));
6530
0
            else
6531
0
                jArg.Add("min_value", minVal);
6532
0
            jArg.Add("min_value_is_included", minValIsIncluded);
6533
0
        }
6534
6535
0
        const auto [maxVal, maxValIsIncluded] = arg->GetMaxValue();
6536
0
        if (!std::isnan(maxVal))
6537
0
        {
6538
0
            if (arg->GetType() == GAAT_INTEGER ||
6539
0
                arg->GetType() == GAAT_INTEGER_LIST)
6540
0
                jArg.Add("max_value", static_cast<int>(maxVal));
6541
0
            else
6542
0
                jArg.Add("max_value", maxVal);
6543
0
            jArg.Add("max_value_is_included", maxValIsIncluded);
6544
0
        }
6545
6546
0
        jArg.Add("required", arg->IsRequired());
6547
0
        if (GDALAlgorithmArgTypeIsList(arg->GetType()))
6548
0
        {
6549
0
            jArg.Add("packed_values_allowed", arg->GetPackedValuesAllowed());
6550
0
            jArg.Add("repeated_arg_allowed", arg->GetRepeatedArgAllowed());
6551
0
            jArg.Add("min_count", arg->GetMinCount());
6552
0
            jArg.Add("max_count", arg->GetMaxCount());
6553
0
        }
6554
0
        jArg.Add("category", arg->GetCategory());
6555
6556
0
        if (arg->GetType() == GAAT_DATASET ||
6557
0
            arg->GetType() == GAAT_DATASET_LIST)
6558
0
        {
6559
0
            {
6560
0
                CPLJSONArray jAr;
6561
0
                if (arg->GetDatasetType() & GDAL_OF_RASTER)
6562
0
                    jAr.Add("raster");
6563
0
                if (arg->GetDatasetType() & GDAL_OF_VECTOR)
6564
0
                    jAr.Add("vector");
6565
0
                if (arg->GetDatasetType() & GDAL_OF_MULTIDIM_RASTER)
6566
0
                    jAr.Add("multidim_raster");
6567
0
                jArg.Add("dataset_type", jAr);
6568
0
            }
6569
6570
0
            const auto GetFlags = [](int flags)
6571
0
            {
6572
0
                CPLJSONArray jAr;
6573
0
                if (flags & GADV_NAME)
6574
0
                    jAr.Add("name");
6575
0
                if (flags & GADV_OBJECT)
6576
0
                    jAr.Add("dataset");
6577
0
                return jAr;
6578
0
            };
6579
6580
0
            if (arg->IsInput())
6581
0
            {
6582
0
                jArg.Add("input_flags", GetFlags(arg->GetDatasetInputFlags()));
6583
0
            }
6584
0
            if (arg->IsOutput())
6585
0
            {
6586
0
                jArg.Add("output_flags",
6587
0
                         GetFlags(arg->GetDatasetOutputFlags()));
6588
0
            }
6589
0
        }
6590
6591
0
        const auto &mutualExclusionGroup = arg->GetMutualExclusionGroup();
6592
0
        if (!mutualExclusionGroup.empty())
6593
0
        {
6594
0
            jArg.Add("mutual_exclusion_group", mutualExclusionGroup);
6595
0
        }
6596
6597
0
        const auto &metadata = arg->GetMetadata();
6598
0
        if (!metadata.empty())
6599
0
        {
6600
0
            CPLJSONObject jMetadata;
6601
0
            for (const auto &[key, values] : metadata)
6602
0
            {
6603
0
                CPLJSONArray jValue;
6604
0
                for (const auto &value : values)
6605
0
                    jValue.Add(value);
6606
0
                jMetadata.Add(key, jValue);
6607
0
            }
6608
0
            jArg.Add("metadata", jMetadata);
6609
0
        }
6610
6611
0
        return jArg;
6612
0
    };
6613
6614
0
    {
6615
0
        CPLJSONArray jArgs;
6616
0
        for (const auto &arg : m_args)
6617
0
        {
6618
0
            if (!arg->IsHiddenForAPI() && arg->IsInput() && !arg->IsOutput())
6619
0
                jArgs.Add(ProcessArg(arg.get()));
6620
0
        }
6621
0
        oRoot.Add("input_arguments", jArgs);
6622
0
    }
6623
6624
0
    {
6625
0
        CPLJSONArray jArgs;
6626
0
        for (const auto &arg : m_args)
6627
0
        {
6628
0
            if (!arg->IsHiddenForAPI() && !arg->IsInput() && arg->IsOutput())
6629
0
                jArgs.Add(ProcessArg(arg.get()));
6630
0
        }
6631
0
        oRoot.Add("output_arguments", jArgs);
6632
0
    }
6633
6634
0
    {
6635
0
        CPLJSONArray jArgs;
6636
0
        for (const auto &arg : m_args)
6637
0
        {
6638
0
            if (!arg->IsHiddenForAPI() && arg->IsInput() && arg->IsOutput())
6639
0
                jArgs.Add(ProcessArg(arg.get()));
6640
0
        }
6641
0
        oRoot.Add("input_output_arguments", jArgs);
6642
0
    }
6643
6644
0
    if (m_supportsStreamedOutput)
6645
0
    {
6646
0
        oRoot.Add("supports_streamed_output", true);
6647
0
    }
6648
6649
0
    return oDoc.SaveAsString();
6650
0
}
6651
6652
/************************************************************************/
6653
/*                   GDALAlgorithm::GetAutoComplete()                   */
6654
/************************************************************************/
6655
6656
std::vector<std::string>
6657
GDALAlgorithm::GetAutoComplete(std::vector<std::string> &args,
6658
                               bool lastWordIsComplete, bool showAllOptions)
6659
0
{
6660
0
    std::vector<std::string> ret;
6661
6662
    // Get inner-most algorithm
6663
0
    std::unique_ptr<GDALAlgorithm> curAlgHolder;
6664
0
    GDALAlgorithm *curAlg = this;
6665
0
    while (!args.empty() && !args.front().empty() && args.front()[0] != '-')
6666
0
    {
6667
0
        auto subAlg = curAlg->InstantiateSubAlgorithm(
6668
0
            args.front(), /* suggestionAllowed = */ false);
6669
0
        if (!subAlg)
6670
0
            break;
6671
0
        if (args.size() == 1 && !lastWordIsComplete)
6672
0
        {
6673
0
            int nCount = 0;
6674
0
            for (const auto &subAlgName : curAlg->GetSubAlgorithmNames())
6675
0
            {
6676
0
                if (STARTS_WITH(subAlgName.c_str(), args.front().c_str()))
6677
0
                    nCount++;
6678
0
            }
6679
0
            if (nCount >= 2)
6680
0
            {
6681
0
                for (const std::string &subAlgName :
6682
0
                     curAlg->GetSubAlgorithmNames())
6683
0
                {
6684
0
                    subAlg = curAlg->InstantiateSubAlgorithm(subAlgName);
6685
0
                    if (subAlg && !subAlg->IsHidden())
6686
0
                        ret.push_back(subAlg->GetName());
6687
0
                }
6688
0
                return ret;
6689
0
            }
6690
0
        }
6691
0
        showAllOptions = false;
6692
0
        args.erase(args.begin());
6693
0
        curAlgHolder = std::move(subAlg);
6694
0
        curAlg = curAlgHolder.get();
6695
0
    }
6696
0
    if (curAlg != this)
6697
0
    {
6698
0
        curAlg->m_calledFromCommandLine = m_calledFromCommandLine;
6699
0
        return curAlg->GetAutoComplete(args, lastWordIsComplete,
6700
0
                                       /* showAllOptions = */ false);
6701
0
    }
6702
6703
0
    std::string option;
6704
0
    std::string value;
6705
0
    ExtractLastOptionAndValue(args, option, value);
6706
6707
0
    if (option.empty() && !args.empty() && !args.back().empty() &&
6708
0
        args.back()[0] == '-')
6709
0
    {
6710
0
        const auto &lastArg = args.back();
6711
        // List available options
6712
0
        for (const auto &arg : GetArgs())
6713
0
        {
6714
0
            if (arg->IsHidden() || arg->IsHiddenForCLI() ||
6715
0
                (!showAllOptions &&
6716
0
                 (arg->GetName() == "help" || arg->GetName() == "config" ||
6717
0
                  arg->GetName() == "version" ||
6718
0
                  arg->GetName() == "json-usage")))
6719
0
            {
6720
0
                continue;
6721
0
            }
6722
0
            if (!arg->GetShortName().empty())
6723
0
            {
6724
0
                std::string str = std::string("-").append(arg->GetShortName());
6725
0
                if (lastArg == str)
6726
0
                    ret.push_back(std::move(str));
6727
0
            }
6728
0
            if (lastArg != "-" && lastArg != "--")
6729
0
            {
6730
0
                for (const std::string &alias : arg->GetAliases())
6731
0
                {
6732
0
                    std::string str = std::string("--").append(alias);
6733
0
                    if (cpl::starts_with(str, lastArg))
6734
0
                        ret.push_back(std::move(str));
6735
0
                }
6736
0
            }
6737
0
            if (!arg->GetName().empty())
6738
0
            {
6739
0
                std::string str = std::string("--").append(arg->GetName());
6740
0
                if (cpl::starts_with(str, lastArg))
6741
0
                    ret.push_back(std::move(str));
6742
0
            }
6743
0
        }
6744
0
        std::sort(ret.begin(), ret.end());
6745
0
    }
6746
0
    else if (!option.empty())
6747
0
    {
6748
        // List possible choices for current option
6749
0
        auto arg = GetArg(option);
6750
0
        if (arg && arg->GetType() != GAAT_BOOLEAN)
6751
0
        {
6752
0
            ret = arg->GetChoices();
6753
0
            if (ret.empty())
6754
0
            {
6755
0
                {
6756
0
                    CPLErrorStateBackuper oErrorQuieter(CPLQuietErrorHandler);
6757
0
                    SetParseForAutoCompletion();
6758
0
                    CPL_IGNORE_RET_VAL(ParseCommandLineArguments(args));
6759
0
                }
6760
0
                ret = arg->GetAutoCompleteChoices(value);
6761
0
            }
6762
0
            else
6763
0
            {
6764
0
                std::sort(ret.begin(), ret.end());
6765
0
            }
6766
0
            if (!ret.empty() && ret.back() == value)
6767
0
            {
6768
0
                ret.clear();
6769
0
            }
6770
0
            else if (ret.empty())
6771
0
            {
6772
0
                ret.push_back("**");
6773
                // Non printable UTF-8 space, to avoid autocompletion to pickup on 'd'
6774
0
                ret.push_back(std::string("\xC2\xA0"
6775
0
                                          "description: ")
6776
0
                                  .append(arg->GetDescription()));
6777
0
            }
6778
0
        }
6779
0
    }
6780
0
    else
6781
0
    {
6782
        // List possible sub-algorithms
6783
0
        for (const std::string &subAlgName : GetSubAlgorithmNames())
6784
0
        {
6785
0
            auto subAlg = InstantiateSubAlgorithm(subAlgName);
6786
0
            if (subAlg && !subAlg->IsHidden())
6787
0
                ret.push_back(subAlg->GetName());
6788
0
        }
6789
0
        if (!ret.empty())
6790
0
        {
6791
0
            std::sort(ret.begin(), ret.end());
6792
0
        }
6793
6794
        // Try filenames
6795
0
        if (ret.empty() && !args.empty())
6796
0
        {
6797
0
            {
6798
0
                CPLErrorStateBackuper oErrorQuieter(CPLQuietErrorHandler);
6799
0
                SetParseForAutoCompletion();
6800
0
                CPL_IGNORE_RET_VAL(ParseCommandLineArguments(args));
6801
0
            }
6802
6803
0
            const std::string &lastArg = args.back();
6804
0
            GDALAlgorithmArg *arg = nullptr;
6805
0
            for (const char *name : {GDAL_ARG_NAME_INPUT, "dataset", "filename",
6806
0
                                     "like", "source", "destination"})
6807
0
            {
6808
0
                if (!arg)
6809
0
                {
6810
0
                    auto newArg = GetArg(name);
6811
0
                    if (newArg)
6812
0
                    {
6813
0
                        if (!newArg->IsExplicitlySet())
6814
0
                        {
6815
0
                            arg = newArg;
6816
0
                        }
6817
0
                        else if (newArg->GetType() == GAAT_STRING ||
6818
0
                                 newArg->GetType() == GAAT_STRING_LIST ||
6819
0
                                 newArg->GetType() == GAAT_DATASET ||
6820
0
                                 newArg->GetType() == GAAT_DATASET_LIST)
6821
0
                        {
6822
0
                            VSIStatBufL sStat;
6823
0
                            if ((!lastArg.empty() && lastArg.back() == '/') ||
6824
0
                                VSIStatL(lastArg.c_str(), &sStat) != 0)
6825
0
                            {
6826
0
                                arg = newArg;
6827
0
                            }
6828
0
                        }
6829
0
                    }
6830
0
                }
6831
0
            }
6832
0
            if (arg)
6833
0
            {
6834
0
                ret = arg->GetAutoCompleteChoices(lastArg);
6835
0
            }
6836
0
        }
6837
0
    }
6838
6839
0
    return ret;
6840
0
}
6841
6842
/************************************************************************/
6843
/*                   GDALAlgorithm::GetFieldIndices()                   */
6844
/************************************************************************/
6845
6846
bool GDALAlgorithm::GetFieldIndices(const std::vector<std::string> &names,
6847
                                    OGRLayerH hLayer, std::vector<int> &indices)
6848
0
{
6849
0
    VALIDATE_POINTER1(hLayer, __func__, false);
6850
6851
0
    const OGRLayer &layer = *OGRLayer::FromHandle(hLayer);
6852
6853
0
    if (names.size() == 1 && names[0] == "ALL")
6854
0
    {
6855
0
        const int nSrcFieldCount = layer.GetLayerDefn()->GetFieldCount();
6856
0
        for (int i = 0; i < nSrcFieldCount; ++i)
6857
0
        {
6858
0
            indices.push_back(i);
6859
0
        }
6860
0
    }
6861
0
    else if (!names.empty() && !(names.size() == 1 && names[0] == "NONE"))
6862
0
    {
6863
0
        std::set<int> fieldsAdded;
6864
0
        for (const std::string &osFieldName : names)
6865
0
        {
6866
6867
0
            const int nIdx =
6868
0
                layer.GetLayerDefn()->GetFieldIndex(osFieldName.c_str());
6869
6870
0
            if (nIdx < 0)
6871
0
            {
6872
0
                CPLError(CE_Failure, CPLE_AppDefined,
6873
0
                         "Field '%s' does not exist in layer '%s'",
6874
0
                         osFieldName.c_str(), layer.GetName());
6875
0
                return false;
6876
0
            }
6877
6878
0
            if (fieldsAdded.insert(nIdx).second)
6879
0
            {
6880
0
                indices.push_back(nIdx);
6881
0
            }
6882
0
        }
6883
0
    }
6884
6885
0
    return true;
6886
0
}
6887
6888
/************************************************************************/
6889
/*              GDALAlgorithm::ExtractLastOptionAndValue()              */
6890
/************************************************************************/
6891
6892
void GDALAlgorithm::ExtractLastOptionAndValue(std::vector<std::string> &args,
6893
                                              std::string &option,
6894
                                              std::string &value) const
6895
0
{
6896
0
    if (!args.empty() && !args.back().empty() && args.back()[0] == '-')
6897
0
    {
6898
0
        const auto nPosEqual = args.back().find('=');
6899
0
        if (nPosEqual == std::string::npos)
6900
0
        {
6901
            // Deal with "gdal ... --option"
6902
0
            if (GetArg(args.back()))
6903
0
            {
6904
0
                option = args.back();
6905
0
                args.pop_back();
6906
0
            }
6907
0
        }
6908
0
        else
6909
0
        {
6910
            // Deal with "gdal ... --option=<value>"
6911
0
            if (GetArg(args.back().substr(0, nPosEqual)))
6912
0
            {
6913
0
                option = args.back().substr(0, nPosEqual);
6914
0
                value = args.back().substr(nPosEqual + 1);
6915
0
                args.pop_back();
6916
0
            }
6917
0
        }
6918
0
    }
6919
0
    else if (args.size() >= 2 && !args[args.size() - 2].empty() &&
6920
0
             args[args.size() - 2][0] == '-')
6921
0
    {
6922
        // Deal with "gdal ... --option <value>"
6923
0
        auto arg = GetArg(args[args.size() - 2]);
6924
0
        if (arg && arg->GetType() != GAAT_BOOLEAN)
6925
0
        {
6926
0
            option = args[args.size() - 2];
6927
0
            value = args.back();
6928
0
            args.pop_back();
6929
0
        }
6930
0
    }
6931
6932
0
    const auto IsKeyValueOption = [](const std::string &osStr)
6933
0
    {
6934
0
        return osStr == "--co" || osStr == "--creation-option" ||
6935
0
               osStr == "--lco" || osStr == "--layer-creation-option" ||
6936
0
               osStr == "--oo" || osStr == "--open-option";
6937
0
    };
6938
6939
0
    if (IsKeyValueOption(option))
6940
0
    {
6941
0
        const auto nPosEqual = value.find('=');
6942
0
        if (nPosEqual != std::string::npos)
6943
0
        {
6944
0
            value.resize(nPosEqual);
6945
0
        }
6946
0
    }
6947
0
}
6948
6949
//! @cond Doxygen_Suppress
6950
6951
/************************************************************************/
6952
/*                  GDALContainerAlgorithm::RunImpl()                   */
6953
/************************************************************************/
6954
6955
bool GDALContainerAlgorithm::RunImpl(GDALProgressFunc, void *)
6956
0
{
6957
0
    return false;
6958
0
}
6959
6960
//! @endcond
6961
6962
/************************************************************************/
6963
/*                        GDALAlgorithmRelease()                        */
6964
/************************************************************************/
6965
6966
/** Release a handle to an algorithm.
6967
 *
6968
 * @since 3.11
6969
 */
6970
void GDALAlgorithmRelease(GDALAlgorithmH hAlg)
6971
0
{
6972
0
    delete hAlg;
6973
0
}
6974
6975
/************************************************************************/
6976
/*                        GDALAlgorithmGetName()                        */
6977
/************************************************************************/
6978
6979
/** Return the algorithm name.
6980
 *
6981
 * @param hAlg Handle to an algorithm. Must NOT be null.
6982
 * @return algorithm name whose lifetime is bound to hAlg and which must not
6983
 * be freed.
6984
 * @since 3.11
6985
 */
6986
const char *GDALAlgorithmGetName(GDALAlgorithmH hAlg)
6987
0
{
6988
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
6989
0
    return hAlg->ptr->GetName().c_str();
6990
0
}
6991
6992
/************************************************************************/
6993
/*                    GDALAlgorithmGetDescription()                     */
6994
/************************************************************************/
6995
6996
/** Return the algorithm (short) description.
6997
 *
6998
 * @param hAlg Handle to an algorithm. Must NOT be null.
6999
 * @return algorithm description whose lifetime is bound to hAlg and which must
7000
 * not be freed.
7001
 * @since 3.11
7002
 */
7003
const char *GDALAlgorithmGetDescription(GDALAlgorithmH hAlg)
7004
0
{
7005
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7006
0
    return hAlg->ptr->GetDescription().c_str();
7007
0
}
7008
7009
/************************************************************************/
7010
/*                  GDALAlgorithmGetLongDescription()                   */
7011
/************************************************************************/
7012
7013
/** Return the algorithm (longer) description.
7014
 *
7015
 * @param hAlg Handle to an algorithm. Must NOT be null.
7016
 * @return algorithm description whose lifetime is bound to hAlg and which must
7017
 * not be freed.
7018
 * @since 3.11
7019
 */
7020
const char *GDALAlgorithmGetLongDescription(GDALAlgorithmH hAlg)
7021
0
{
7022
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7023
0
    return hAlg->ptr->GetLongDescription().c_str();
7024
0
}
7025
7026
/************************************************************************/
7027
/*                    GDALAlgorithmGetHelpFullURL()                     */
7028
/************************************************************************/
7029
7030
/** Return the algorithm full URL.
7031
 *
7032
 * @param hAlg Handle to an algorithm. Must NOT be null.
7033
 * @return algorithm URL whose lifetime is bound to hAlg and which must
7034
 * not be freed.
7035
 * @since 3.11
7036
 */
7037
const char *GDALAlgorithmGetHelpFullURL(GDALAlgorithmH hAlg)
7038
0
{
7039
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7040
0
    return hAlg->ptr->GetHelpFullURL().c_str();
7041
0
}
7042
7043
/************************************************************************/
7044
/*                   GDALAlgorithmHasSubAlgorithms()                    */
7045
/************************************************************************/
7046
7047
/** Return whether the algorithm has sub-algorithms.
7048
 *
7049
 * @param hAlg Handle to an algorithm. Must NOT be null.
7050
 * @since 3.11
7051
 */
7052
bool GDALAlgorithmHasSubAlgorithms(GDALAlgorithmH hAlg)
7053
0
{
7054
0
    VALIDATE_POINTER1(hAlg, __func__, false);
7055
0
    return hAlg->ptr->HasSubAlgorithms();
7056
0
}
7057
7058
/************************************************************************/
7059
/*                 GDALAlgorithmGetSubAlgorithmNames()                  */
7060
/************************************************************************/
7061
7062
/** Get the names of registered algorithms.
7063
 *
7064
 * @param hAlg Handle to an algorithm. Must NOT be null.
7065
 * @return a NULL terminated list of names, which must be destroyed with
7066
 * CSLDestroy()
7067
 * @since 3.11
7068
 */
7069
char **GDALAlgorithmGetSubAlgorithmNames(GDALAlgorithmH hAlg)
7070
0
{
7071
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7072
0
    return CPLStringList(hAlg->ptr->GetSubAlgorithmNames()).StealList();
7073
0
}
7074
7075
/************************************************************************/
7076
/*                GDALAlgorithmInstantiateSubAlgorithm()                */
7077
/************************************************************************/
7078
7079
/** Instantiate an algorithm by its name (or its alias).
7080
 *
7081
 * @param hAlg Handle to an algorithm. Must NOT be null.
7082
 * @param pszSubAlgName Algorithm name. Must NOT be null.
7083
 * @return an handle to the algorithm (to be freed with GDALAlgorithmRelease),
7084
 * or NULL if the algorithm does not exist or another error occurred.
7085
 * @since 3.11
7086
 */
7087
GDALAlgorithmH GDALAlgorithmInstantiateSubAlgorithm(GDALAlgorithmH hAlg,
7088
                                                    const char *pszSubAlgName)
7089
0
{
7090
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7091
0
    VALIDATE_POINTER1(pszSubAlgName, __func__, nullptr);
7092
0
    auto subAlg = hAlg->ptr->InstantiateSubAlgorithm(pszSubAlgName);
7093
0
    return subAlg
7094
0
               ? std::make_unique<GDALAlgorithmHS>(std::move(subAlg)).release()
7095
0
               : nullptr;
7096
0
}
7097
7098
/************************************************************************/
7099
/*               GDALAlgorithmParseCommandLineArguments()               */
7100
/************************************************************************/
7101
7102
/** Parse a command line argument, which does not include the algorithm
7103
 * name, to set the value of corresponding arguments.
7104
 *
7105
 * @param hAlg Handle to an algorithm. Must NOT be null.
7106
 * @param papszArgs NULL-terminated list of arguments, not including the algorithm name.
7107
 * @return true if successful, false otherwise
7108
 * @since 3.11
7109
 */
7110
7111
bool GDALAlgorithmParseCommandLineArguments(GDALAlgorithmH hAlg,
7112
                                            CSLConstList papszArgs)
7113
0
{
7114
0
    VALIDATE_POINTER1(hAlg, __func__, false);
7115
0
    return hAlg->ptr->ParseCommandLineArguments(CPLStringList(papszArgs));
7116
0
}
7117
7118
/************************************************************************/
7119
/*                  GDALAlgorithmGetActualAlgorithm()                   */
7120
/************************************************************************/
7121
7122
/** Return the actual algorithm that is going to be invoked, when the
7123
 * current algorithm has sub-algorithms.
7124
 *
7125
 * Only valid after GDALAlgorithmParseCommandLineArguments() has been called.
7126
 *
7127
 * Note that the lifetime of the returned algorithm does not exceed the one of
7128
 * the hAlg instance that owns it.
7129
 *
7130
 * @param hAlg Handle to an algorithm. Must NOT be null.
7131
 * @return an handle to the algorithm (to be freed with GDALAlgorithmRelease).
7132
 * @since 3.11
7133
 */
7134
GDALAlgorithmH GDALAlgorithmGetActualAlgorithm(GDALAlgorithmH hAlg)
7135
0
{
7136
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7137
0
    return GDALAlgorithmHS::FromRef(hAlg->ptr->GetActualAlgorithm()).release();
7138
0
}
7139
7140
/************************************************************************/
7141
/*                          GDALAlgorithmRun()                          */
7142
/************************************************************************/
7143
7144
/** Execute the algorithm, starting with ValidateArguments() and then
7145
 * calling RunImpl().
7146
 *
7147
 * @param hAlg Handle to an algorithm. Must NOT be null.
7148
 * @param pfnProgress Progress callback. May be null.
7149
 * @param pProgressData Progress callback user data. May be null.
7150
 * @return true if successful, false otherwise
7151
 * @since 3.11
7152
 */
7153
7154
bool GDALAlgorithmRun(GDALAlgorithmH hAlg, GDALProgressFunc pfnProgress,
7155
                      void *pProgressData)
7156
0
{
7157
0
    VALIDATE_POINTER1(hAlg, __func__, false);
7158
0
    return hAlg->ptr->Run(pfnProgress, pProgressData);
7159
0
}
7160
7161
/************************************************************************/
7162
/*                       GDALAlgorithmFinalize()                        */
7163
/************************************************************************/
7164
7165
/** Complete any pending actions, and return the final status.
7166
 * This is typically useful for algorithm that generate an output dataset.
7167
 *
7168
 * Note that this function does *NOT* release memory associated with the
7169
 * algorithm. GDALAlgorithmRelease() must still be called afterwards.
7170
 *
7171
 * @param hAlg Handle to an algorithm. Must NOT be null.
7172
 * @return true if successful, false otherwise
7173
 * @since 3.11
7174
 */
7175
7176
bool GDALAlgorithmFinalize(GDALAlgorithmH hAlg)
7177
0
{
7178
0
    VALIDATE_POINTER1(hAlg, __func__, false);
7179
0
    return hAlg->ptr->Finalize();
7180
0
}
7181
7182
/************************************************************************/
7183
/*                    GDALAlgorithmGetUsageAsJSON()                     */
7184
/************************************************************************/
7185
7186
/** Return the usage of the algorithm as a JSON-serialized string.
7187
 *
7188
 * This can be used to dynamically generate interfaces to algorithms.
7189
 *
7190
 * @param hAlg Handle to an algorithm. Must NOT be null.
7191
 * @return a string that must be freed with CPLFree()
7192
 * @since 3.11
7193
 */
7194
char *GDALAlgorithmGetUsageAsJSON(GDALAlgorithmH hAlg)
7195
0
{
7196
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7197
0
    return CPLStrdup(hAlg->ptr->GetUsageAsJSON().c_str());
7198
0
}
7199
7200
/************************************************************************/
7201
/*                      GDALAlgorithmGetArgNames()                      */
7202
/************************************************************************/
7203
7204
/** Return the list of available argument names.
7205
 *
7206
 * @param hAlg Handle to an algorithm. Must NOT be null.
7207
 * @return a NULL terminated list of names, which must be destroyed with
7208
 * CSLDestroy()
7209
 * @since 3.11
7210
 */
7211
char **GDALAlgorithmGetArgNames(GDALAlgorithmH hAlg)
7212
0
{
7213
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7214
0
    CPLStringList list;
7215
0
    for (const auto &arg : hAlg->ptr->GetArgs())
7216
0
        list.AddString(arg->GetName().c_str());
7217
0
    return list.StealList();
7218
0
}
7219
7220
/************************************************************************/
7221
/*                        GDALAlgorithmGetArg()                         */
7222
/************************************************************************/
7223
7224
/** Return an argument from its name.
7225
 *
7226
 * The lifetime of the returned object does not exceed the one of hAlg.
7227
 *
7228
 * @param hAlg Handle to an algorithm. Must NOT be null.
7229
 * @param pszArgName Argument name. Must NOT be null.
7230
 * @return an argument that must be released with GDALAlgorithmArgRelease(),
7231
 * or nullptr in case of error
7232
 * @since 3.11
7233
 */
7234
GDALAlgorithmArgH GDALAlgorithmGetArg(GDALAlgorithmH hAlg,
7235
                                      const char *pszArgName)
7236
0
{
7237
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7238
0
    VALIDATE_POINTER1(pszArgName, __func__, nullptr);
7239
0
    auto arg = hAlg->ptr->GetArg(pszArgName, /* suggestionAllowed = */ true,
7240
0
                                 /* isConst = */ true);
7241
0
    if (!arg)
7242
0
        return nullptr;
7243
0
    return std::make_unique<GDALAlgorithmArgHS>(arg).release();
7244
0
}
7245
7246
/************************************************************************/
7247
/*                    GDALAlgorithmGetArgNonConst()                     */
7248
/************************************************************************/
7249
7250
/** Return an argument from its name, possibly allowing creation of user-provided
7251
 * argument if the algorithm allow it.
7252
 *
7253
 * The lifetime of the returned object does not exceed the one of hAlg.
7254
 *
7255
 * @param hAlg Handle to an algorithm. Must NOT be null.
7256
 * @param pszArgName Argument name. Must NOT be null.
7257
 * @return an argument that must be released with GDALAlgorithmArgRelease(),
7258
 * or nullptr in case of error
7259
 * @since 3.12
7260
 */
7261
GDALAlgorithmArgH GDALAlgorithmGetArgNonConst(GDALAlgorithmH hAlg,
7262
                                              const char *pszArgName)
7263
0
{
7264
0
    VALIDATE_POINTER1(hAlg, __func__, nullptr);
7265
0
    VALIDATE_POINTER1(pszArgName, __func__, nullptr);
7266
0
    auto arg = hAlg->ptr->GetArg(pszArgName, /* suggestionAllowed = */ true,
7267
0
                                 /* isConst = */ false);
7268
0
    if (!arg)
7269
0
        return nullptr;
7270
0
    return std::make_unique<GDALAlgorithmArgHS>(arg).release();
7271
0
}
7272
7273
/************************************************************************/
7274
/*                      GDALAlgorithmArgRelease()                       */
7275
/************************************************************************/
7276
7277
/** Release a handle to an argument.
7278
 *
7279
 * @since 3.11
7280
 */
7281
void GDALAlgorithmArgRelease(GDALAlgorithmArgH hArg)
7282
0
{
7283
0
    delete hArg;
7284
0
}
7285
7286
/************************************************************************/
7287
/*                      GDALAlgorithmArgGetName()                       */
7288
/************************************************************************/
7289
7290
/** Return the name of an argument.
7291
 *
7292
 * @param hArg Handle to an argument. Must NOT be null.
7293
 * @return argument name whose lifetime is bound to hArg and which must not
7294
 * be freed.
7295
 * @since 3.11
7296
 */
7297
const char *GDALAlgorithmArgGetName(GDALAlgorithmArgH hArg)
7298
0
{
7299
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
7300
0
    return hArg->ptr->GetName().c_str();
7301
0
}
7302
7303
/************************************************************************/
7304
/*                      GDALAlgorithmArgGetType()                       */
7305
/************************************************************************/
7306
7307
/** Get the type of an argument
7308
 *
7309
 * @param hArg Handle to an argument. Must NOT be null.
7310
 * @since 3.11
7311
 */
7312
GDALAlgorithmArgType GDALAlgorithmArgGetType(GDALAlgorithmArgH hArg)
7313
0
{
7314
0
    VALIDATE_POINTER1(hArg, __func__, GAAT_STRING);
7315
0
    return hArg->ptr->GetType();
7316
0
}
7317
7318
/************************************************************************/
7319
/*                   GDALAlgorithmArgGetDescription()                   */
7320
/************************************************************************/
7321
7322
/** Return the description of an argument.
7323
 *
7324
 * @param hArg Handle to an argument. Must NOT be null.
7325
 * @return argument description whose lifetime is bound to hArg and which must not
7326
 * be freed.
7327
 * @since 3.11
7328
 */
7329
const char *GDALAlgorithmArgGetDescription(GDALAlgorithmArgH hArg)
7330
0
{
7331
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
7332
0
    return hArg->ptr->GetDescription().c_str();
7333
0
}
7334
7335
/************************************************************************/
7336
/*                    GDALAlgorithmArgGetShortName()                    */
7337
/************************************************************************/
7338
7339
/** Return the short name, or empty string if there is none
7340
 *
7341
 * @param hArg Handle to an argument. Must NOT be null.
7342
 * @return short name whose lifetime is bound to hArg and which must not
7343
 * be freed.
7344
 * @since 3.11
7345
 */
7346
const char *GDALAlgorithmArgGetShortName(GDALAlgorithmArgH hArg)
7347
0
{
7348
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
7349
0
    return hArg->ptr->GetShortName().c_str();
7350
0
}
7351
7352
/************************************************************************/
7353
/*                     GDALAlgorithmArgGetAliases()                     */
7354
/************************************************************************/
7355
7356
/** Return the aliases (potentially none)
7357
 *
7358
 * @param hArg Handle to an argument. Must NOT be null.
7359
 * @return a NULL terminated list of names, which must be destroyed with
7360
 * CSLDestroy()
7361
7362
 * @since 3.11
7363
 */
7364
char **GDALAlgorithmArgGetAliases(GDALAlgorithmArgH hArg)
7365
0
{
7366
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
7367
0
    return CPLStringList(hArg->ptr->GetAliases()).StealList();
7368
0
}
7369
7370
/************************************************************************/
7371
/*                     GDALAlgorithmArgGetMetaVar()                     */
7372
/************************************************************************/
7373
7374
/** Return the "meta-var" hint.
7375
 *
7376
 * By default, the meta-var value is the long name of the argument in
7377
 * upper case.
7378
 *
7379
 * @param hArg Handle to an argument. Must NOT be null.
7380
 * @return meta-var hint whose lifetime is bound to hArg and which must not
7381
 * be freed.
7382
 * @since 3.11
7383
 */
7384
const char *GDALAlgorithmArgGetMetaVar(GDALAlgorithmArgH hArg)
7385
0
{
7386
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
7387
0
    return hArg->ptr->GetMetaVar().c_str();
7388
0
}
7389
7390
/************************************************************************/
7391
/*                    GDALAlgorithmArgGetCategory()                     */
7392
/************************************************************************/
7393
7394
/** Return the argument category
7395
 *
7396
 * GAAC_COMMON, GAAC_BASE, GAAC_ADVANCED, GAAC_ESOTERIC or a custom category.
7397
 *
7398
 * @param hArg Handle to an argument. Must NOT be null.
7399
 * @return category whose lifetime is bound to hArg and which must not
7400
 * be freed.
7401
 * @since 3.11
7402
 */
7403
const char *GDALAlgorithmArgGetCategory(GDALAlgorithmArgH hArg)
7404
0
{
7405
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
7406
0
    return hArg->ptr->GetCategory().c_str();
7407
0
}
7408
7409
/************************************************************************/
7410
/*                    GDALAlgorithmArgIsPositional()                    */
7411
/************************************************************************/
7412
7413
/** Return if the argument is a positional one.
7414
 *
7415
 * @param hArg Handle to an argument. Must NOT be null.
7416
 * @since 3.11
7417
 */
7418
bool GDALAlgorithmArgIsPositional(GDALAlgorithmArgH hArg)
7419
0
{
7420
0
    VALIDATE_POINTER1(hArg, __func__, false);
7421
0
    return hArg->ptr->IsPositional();
7422
0
}
7423
7424
/************************************************************************/
7425
/*                     GDALAlgorithmArgIsRequired()                     */
7426
/************************************************************************/
7427
7428
/** Return whether the argument is required. Defaults to false.
7429
 *
7430
 * @param hArg Handle to an argument. Must NOT be null.
7431
 * @since 3.11
7432
 */
7433
bool GDALAlgorithmArgIsRequired(GDALAlgorithmArgH hArg)
7434
0
{
7435
0
    VALIDATE_POINTER1(hArg, __func__, false);
7436
0
    return hArg->ptr->IsRequired();
7437
0
}
7438
7439
/************************************************************************/
7440
/*                    GDALAlgorithmArgGetMinCount()                     */
7441
/************************************************************************/
7442
7443
/** Return the minimum number of values for the argument.
7444
 *
7445
 * Defaults to 0.
7446
 * Only applies to list type of arguments.
7447
 *
7448
 * @param hArg Handle to an argument. Must NOT be null.
7449
 * @since 3.11
7450
 */
7451
int GDALAlgorithmArgGetMinCount(GDALAlgorithmArgH hArg)
7452
0
{
7453
0
    VALIDATE_POINTER1(hArg, __func__, 0);
7454
0
    return hArg->ptr->GetMinCount();
7455
0
}
7456
7457
/************************************************************************/
7458
/*                    GDALAlgorithmArgGetMaxCount()                     */
7459
/************************************************************************/
7460
7461
/** Return the maximum number of values for the argument.
7462
 *
7463
 * Defaults to 1 for scalar types, and INT_MAX for list types.
7464
 * Only applies to list type of arguments.
7465
 *
7466
 * @param hArg Handle to an argument. Must NOT be null.
7467
 * @since 3.11
7468
 */
7469
int GDALAlgorithmArgGetMaxCount(GDALAlgorithmArgH hArg)
7470
0
{
7471
0
    VALIDATE_POINTER1(hArg, __func__, 0);
7472
0
    return hArg->ptr->GetMaxCount();
7473
0
}
7474
7475
/************************************************************************/
7476
/*               GDALAlgorithmArgGetPackedValuesAllowed()               */
7477
/************************************************************************/
7478
7479
/** Return whether, for list type of arguments, several values, space
7480
 * separated, may be specified. That is "--foo=bar,baz".
7481
 * The default is true.
7482
 *
7483
 * @param hArg Handle to an argument. Must NOT be null.
7484
 * @since 3.11
7485
 */
7486
bool GDALAlgorithmArgGetPackedValuesAllowed(GDALAlgorithmArgH hArg)
7487
0
{
7488
0
    VALIDATE_POINTER1(hArg, __func__, false);
7489
0
    return hArg->ptr->GetPackedValuesAllowed();
7490
0
}
7491
7492
/************************************************************************/
7493
/*               GDALAlgorithmArgGetRepeatedArgAllowed()                */
7494
/************************************************************************/
7495
7496
/** Return whether, for list type of arguments, the argument may be
7497
 * repeated. That is "--foo=bar --foo=baz".
7498
 * The default is true.
7499
 *
7500
 * @param hArg Handle to an argument. Must NOT be null.
7501
 * @since 3.11
7502
 */
7503
bool GDALAlgorithmArgGetRepeatedArgAllowed(GDALAlgorithmArgH hArg)
7504
0
{
7505
0
    VALIDATE_POINTER1(hArg, __func__, false);
7506
0
    return hArg->ptr->GetRepeatedArgAllowed();
7507
0
}
7508
7509
/************************************************************************/
7510
/*                     GDALAlgorithmArgGetChoices()                     */
7511
/************************************************************************/
7512
7513
/** Return the allowed values (as strings) for the argument.
7514
 *
7515
 * Only honored for GAAT_STRING and GAAT_STRING_LIST types.
7516
 *
7517
 * @param hArg Handle to an argument. Must NOT be null.
7518
 * @return a NULL terminated list of names, which must be destroyed with
7519
 * CSLDestroy()
7520
7521
 * @since 3.11
7522
 */
7523
char **GDALAlgorithmArgGetChoices(GDALAlgorithmArgH hArg)
7524
0
{
7525
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
7526
0
    return CPLStringList(hArg->ptr->GetChoices()).StealList();
7527
0
}
7528
7529
/************************************************************************/
7530
/*                  GDALAlgorithmArgGetMetadataItem()                   */
7531
/************************************************************************/
7532
7533
/** Return the values of the metadata item of an argument.
7534
 *
7535
 * @param hArg Handle to an argument. Must NOT be null.
7536
 * @param pszItem Name of the item. Must NOT be null.
7537
 * @return a NULL terminated list of values, which must be destroyed with
7538
 * CSLDestroy()
7539
7540
 * @since 3.11
7541
 */
7542
char **GDALAlgorithmArgGetMetadataItem(GDALAlgorithmArgH hArg,
7543
                                       const char *pszItem)
7544
0
{
7545
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
7546
0
    VALIDATE_POINTER1(pszItem, __func__, nullptr);
7547
0
    const auto pVecOfStrings = hArg->ptr->GetMetadataItem(pszItem);
7548
0
    return pVecOfStrings ? CPLStringList(*pVecOfStrings).StealList() : nullptr;
7549
0
}
7550
7551
/************************************************************************/
7552
/*                  GDALAlgorithmArgIsExplicitlySet()                   */
7553
/************************************************************************/
7554
7555
/** Return whether the argument value has been explicitly set with Set()
7556
 *
7557
 * @param hArg Handle to an argument. Must NOT be null.
7558
 * @since 3.11
7559
 */
7560
bool GDALAlgorithmArgIsExplicitlySet(GDALAlgorithmArgH hArg)
7561
0
{
7562
0
    VALIDATE_POINTER1(hArg, __func__, false);
7563
0
    return hArg->ptr->IsExplicitlySet();
7564
0
}
7565
7566
/************************************************************************/
7567
/*                  GDALAlgorithmArgHasDefaultValue()                   */
7568
/************************************************************************/
7569
7570
/** Return if the argument has a declared default value.
7571
 *
7572
 * @param hArg Handle to an argument. Must NOT be null.
7573
 * @since 3.11
7574
 */
7575
bool GDALAlgorithmArgHasDefaultValue(GDALAlgorithmArgH hArg)
7576
0
{
7577
0
    VALIDATE_POINTER1(hArg, __func__, false);
7578
0
    return hArg->ptr->HasDefaultValue();
7579
0
}
7580
7581
/************************************************************************/
7582
/*                GDALAlgorithmArgGetDefaultAsBoolean()                 */
7583
/************************************************************************/
7584
7585
/** Return the argument default value as a integer.
7586
 *
7587
 * Must only be called on arguments whose type is GAAT_BOOLEAN
7588
 *
7589
 * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
7590
 * argument has a default value.
7591
 *
7592
 * @param hArg Handle to an argument. Must NOT be null.
7593
 * @since 3.12
7594
 */
7595
bool GDALAlgorithmArgGetDefaultAsBoolean(GDALAlgorithmArgH hArg)
7596
0
{
7597
0
    VALIDATE_POINTER1(hArg, __func__, false);
7598
0
    if (hArg->ptr->GetType() != GAAT_BOOLEAN)
7599
0
    {
7600
0
        CPLError(CE_Failure, CPLE_AppDefined,
7601
0
                 "%s must only be called on arguments of type GAAT_BOOLEAN",
7602
0
                 __func__);
7603
0
        return false;
7604
0
    }
7605
0
    return hArg->ptr->GetDefault<bool>();
7606
0
}
7607
7608
/************************************************************************/
7609
/*                 GDALAlgorithmArgGetDefaultAsString()                 */
7610
/************************************************************************/
7611
7612
/** Return the argument default value as a string.
7613
 *
7614
 * Must only be called on arguments whose type is GAAT_STRING.
7615
 *
7616
 * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
7617
 * argument has a default value.
7618
 *
7619
 * @param hArg Handle to an argument. Must NOT be null.
7620
 * @return string whose lifetime is bound to hArg and which must not
7621
 * be freed.
7622
 * @since 3.11
7623
 */
7624
const char *GDALAlgorithmArgGetDefaultAsString(GDALAlgorithmArgH hArg)
7625
0
{
7626
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
7627
0
    if (hArg->ptr->GetType() != GAAT_STRING)
7628
0
    {
7629
0
        CPLError(CE_Failure, CPLE_AppDefined,
7630
0
                 "%s must only be called on arguments of type GAAT_STRING",
7631
0
                 __func__);
7632
0
        return nullptr;
7633
0
    }
7634
0
    return hArg->ptr->GetDefault<std::string>().c_str();
7635
0
}
7636
7637
/************************************************************************/
7638
/*                GDALAlgorithmArgGetDefaultAsInteger()                 */
7639
/************************************************************************/
7640
7641
/** Return the argument default value as a integer.
7642
 *
7643
 * Must only be called on arguments whose type is GAAT_INTEGER
7644
 *
7645
 * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
7646
 * argument has a default value.
7647
 *
7648
 * @param hArg Handle to an argument. Must NOT be null.
7649
 * @since 3.12
7650
 */
7651
int GDALAlgorithmArgGetDefaultAsInteger(GDALAlgorithmArgH hArg)
7652
0
{
7653
0
    VALIDATE_POINTER1(hArg, __func__, 0);
7654
0
    if (hArg->ptr->GetType() != GAAT_INTEGER)
7655
0
    {
7656
0
        CPLError(CE_Failure, CPLE_AppDefined,
7657
0
                 "%s must only be called on arguments of type GAAT_INTEGER",
7658
0
                 __func__);
7659
0
        return 0;
7660
0
    }
7661
0
    return hArg->ptr->GetDefault<int>();
7662
0
}
7663
7664
/************************************************************************/
7665
/*                 GDALAlgorithmArgGetDefaultAsDouble()                 */
7666
/************************************************************************/
7667
7668
/** Return the argument default value as a double.
7669
 *
7670
 * Must only be called on arguments whose type is GAAT_REAL
7671
 *
7672
 * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
7673
 * argument has a default value.
7674
 *
7675
 * @param hArg Handle to an argument. Must NOT be null.
7676
 * @since 3.12
7677
 */
7678
double GDALAlgorithmArgGetDefaultAsDouble(GDALAlgorithmArgH hArg)
7679
0
{
7680
0
    VALIDATE_POINTER1(hArg, __func__, 0);
7681
0
    if (hArg->ptr->GetType() != GAAT_REAL)
7682
0
    {
7683
0
        CPLError(CE_Failure, CPLE_AppDefined,
7684
0
                 "%s must only be called on arguments of type GAAT_REAL",
7685
0
                 __func__);
7686
0
        return 0;
7687
0
    }
7688
0
    return hArg->ptr->GetDefault<double>();
7689
0
}
7690
7691
/************************************************************************/
7692
/*               GDALAlgorithmArgGetDefaultAsStringList()               */
7693
/************************************************************************/
7694
7695
/** Return the argument default value as a string list.
7696
 *
7697
 * Must only be called on arguments whose type is GAAT_STRING_LIST.
7698
 *
7699
 * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
7700
 * argument has a default value.
7701
 *
7702
 * @param hArg Handle to an argument. Must NOT be null.
7703
 * @return a NULL terminated list of names, which must be destroyed with
7704
 * CSLDestroy()
7705
7706
 * @since 3.12
7707
 */
7708
char **GDALAlgorithmArgGetDefaultAsStringList(GDALAlgorithmArgH hArg)
7709
0
{
7710
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
7711
0
    if (hArg->ptr->GetType() != GAAT_STRING_LIST)
7712
0
    {
7713
0
        CPLError(CE_Failure, CPLE_AppDefined,
7714
0
                 "%s must only be called on arguments of type GAAT_STRING_LIST",
7715
0
                 __func__);
7716
0
        return nullptr;
7717
0
    }
7718
0
    return CPLStringList(hArg->ptr->GetDefault<std::vector<std::string>>())
7719
0
        .StealList();
7720
0
}
7721
7722
/************************************************************************/
7723
/*              GDALAlgorithmArgGetDefaultAsIntegerList()               */
7724
/************************************************************************/
7725
7726
/** Return the argument default value as a integer list.
7727
 *
7728
 * Must only be called on arguments whose type is GAAT_INTEGER_LIST.
7729
 *
7730
 * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
7731
 * argument has a default value.
7732
 *
7733
 * @param hArg Handle to an argument. Must NOT be null.
7734
 * @param[out] pnCount Pointer to the number of values in the list. Must NOT be null.
7735
 * @since 3.12
7736
 */
7737
const int *GDALAlgorithmArgGetDefaultAsIntegerList(GDALAlgorithmArgH hArg,
7738
                                                   size_t *pnCount)
7739
0
{
7740
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
7741
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
7742
0
    if (hArg->ptr->GetType() != GAAT_INTEGER_LIST)
7743
0
    {
7744
0
        CPLError(
7745
0
            CE_Failure, CPLE_AppDefined,
7746
0
            "%s must only be called on arguments of type GAAT_INTEGER_LIST",
7747
0
            __func__);
7748
0
        *pnCount = 0;
7749
0
        return nullptr;
7750
0
    }
7751
0
    const auto &val = hArg->ptr->GetDefault<std::vector<int>>();
7752
0
    *pnCount = val.size();
7753
0
    return val.data();
7754
0
}
7755
7756
/************************************************************************/
7757
/*               GDALAlgorithmArgGetDefaultAsDoubleList()               */
7758
/************************************************************************/
7759
7760
/** Return the argument default value as a real list.
7761
 *
7762
 * Must only be called on arguments whose type is GAAT_REAL_LIST.
7763
 *
7764
 * GDALAlgorithmArgHasDefaultValue() must be called to determine if the
7765
 * argument has a default value.
7766
 *
7767
 * @param hArg Handle to an argument. Must NOT be null.
7768
 * @param[out] pnCount Pointer to the number of values in the list. Must NOT be null.
7769
 * @since 3.12
7770
 */
7771
const double *GDALAlgorithmArgGetDefaultAsDoubleList(GDALAlgorithmArgH hArg,
7772
                                                     size_t *pnCount)
7773
0
{
7774
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
7775
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
7776
0
    if (hArg->ptr->GetType() != GAAT_REAL_LIST)
7777
0
    {
7778
0
        CPLError(CE_Failure, CPLE_AppDefined,
7779
0
                 "%s must only be called on arguments of type GAAT_REAL_LIST",
7780
0
                 __func__);
7781
0
        *pnCount = 0;
7782
0
        return nullptr;
7783
0
    }
7784
0
    const auto &val = hArg->ptr->GetDefault<std::vector<double>>();
7785
0
    *pnCount = val.size();
7786
0
    return val.data();
7787
0
}
7788
7789
/************************************************************************/
7790
/*                      GDALAlgorithmArgIsHidden()                      */
7791
/************************************************************************/
7792
7793
/** Return whether the argument is hidden (for GDAL internal use)
7794
 *
7795
 * This is an alias for GDALAlgorithmArgIsHiddenForCLI() &&
7796
 * GDALAlgorithmArgIsHiddenForAPI().
7797
 *
7798
 * @param hArg Handle to an argument. Must NOT be null.
7799
 * @since 3.12
7800
 */
7801
bool GDALAlgorithmArgIsHidden(GDALAlgorithmArgH hArg)
7802
0
{
7803
0
    VALIDATE_POINTER1(hArg, __func__, false);
7804
0
    return hArg->ptr->IsHidden();
7805
0
}
7806
7807
/************************************************************************/
7808
/*                   GDALAlgorithmArgIsHiddenForCLI()                   */
7809
/************************************************************************/
7810
7811
/** Return whether the argument must not be mentioned in CLI usage.
7812
 *
7813
 * For example, "output-value" for "gdal raster info", which is only
7814
 * meant when the algorithm is used from a non-CLI context.
7815
 *
7816
 * @param hArg Handle to an argument. Must NOT be null.
7817
 * @since 3.11
7818
 */
7819
bool GDALAlgorithmArgIsHiddenForCLI(GDALAlgorithmArgH hArg)
7820
0
{
7821
0
    VALIDATE_POINTER1(hArg, __func__, false);
7822
0
    return hArg->ptr->IsHiddenForCLI();
7823
0
}
7824
7825
/************************************************************************/
7826
/*                   GDALAlgorithmArgIsHiddenForAPI()                   */
7827
/************************************************************************/
7828
7829
/** Return whether the argument must not be mentioned in the context of an
7830
 * API use.
7831
 * Said otherwise, if it is only for CLI usage.
7832
 *
7833
 * For example "--help"
7834
 *
7835
 * @param hArg Handle to an argument. Must NOT be null.
7836
 * @since 3.12
7837
 */
7838
bool GDALAlgorithmArgIsHiddenForAPI(GDALAlgorithmArgH hArg)
7839
0
{
7840
0
    VALIDATE_POINTER1(hArg, __func__, false);
7841
0
    return hArg->ptr->IsHiddenForAPI();
7842
0
}
7843
7844
/************************************************************************/
7845
/*                    GDALAlgorithmArgIsOnlyForCLI()                    */
7846
/************************************************************************/
7847
7848
/** Return whether the argument must not be mentioned in the context of an
7849
 * API use.
7850
 * Said otherwise, if it is only for CLI usage.
7851
 *
7852
 * For example "--help"
7853
 *
7854
 * @param hArg Handle to an argument. Must NOT be null.
7855
 * @since 3.11
7856
 * @deprecated Use GDALAlgorithmArgIsHiddenForAPI() instead.
7857
 */
7858
bool GDALAlgorithmArgIsOnlyForCLI(GDALAlgorithmArgH hArg)
7859
0
{
7860
0
    VALIDATE_POINTER1(hArg, __func__, false);
7861
0
    return hArg->ptr->IsHiddenForAPI();
7862
0
}
7863
7864
/************************************************************************/
7865
/*                      GDALAlgorithmArgIsInput()                       */
7866
/************************************************************************/
7867
7868
/** Indicate whether the value of the argument is read-only during the
7869
 * execution of the algorithm.
7870
 *
7871
 * Default is true.
7872
 *
7873
 * @param hArg Handle to an argument. Must NOT be null.
7874
 * @since 3.11
7875
 */
7876
bool GDALAlgorithmArgIsInput(GDALAlgorithmArgH hArg)
7877
0
{
7878
0
    VALIDATE_POINTER1(hArg, __func__, false);
7879
0
    return hArg->ptr->IsInput();
7880
0
}
7881
7882
/************************************************************************/
7883
/*                      GDALAlgorithmArgIsOutput()                      */
7884
/************************************************************************/
7885
7886
/** Return whether (at least part of) the value of the argument is set
7887
 * during the execution of the algorithm.
7888
 *
7889
 * For example, "output-value" for "gdal raster info"
7890
 * Default is false.
7891
 * An argument may return both IsInput() and IsOutput() as true.
7892
 * For example the "gdal raster convert" algorithm consumes the dataset
7893
 * name of its "output" argument, and sets the dataset object during its
7894
 * execution.
7895
 *
7896
 * @param hArg Handle to an argument. Must NOT be null.
7897
 * @since 3.11
7898
 */
7899
bool GDALAlgorithmArgIsOutput(GDALAlgorithmArgH hArg)
7900
0
{
7901
0
    VALIDATE_POINTER1(hArg, __func__, false);
7902
0
    return hArg->ptr->IsOutput();
7903
0
}
7904
7905
/************************************************************************/
7906
/*                   GDALAlgorithmArgGetDatasetType()                   */
7907
/************************************************************************/
7908
7909
/** Get which type of dataset is allowed / generated.
7910
 *
7911
 * Binary-or combination of GDAL_OF_RASTER, GDAL_OF_VECTOR and
7912
 * GDAL_OF_MULTIDIM_RASTER.
7913
 * Only applies to arguments of type GAAT_DATASET or GAAT_DATASET_LIST.
7914
 *
7915
 * @param hArg Handle to an argument. Must NOT be null.
7916
 * @since 3.11
7917
 */
7918
GDALArgDatasetType GDALAlgorithmArgGetDatasetType(GDALAlgorithmArgH hArg)
7919
0
{
7920
0
    VALIDATE_POINTER1(hArg, __func__, 0);
7921
0
    return hArg->ptr->GetDatasetType();
7922
0
}
7923
7924
/************************************************************************/
7925
/*                GDALAlgorithmArgGetDatasetInputFlags()                */
7926
/************************************************************************/
7927
7928
/** Indicates which components among name and dataset are accepted as
7929
 * input, when this argument serves as an input.
7930
 *
7931
 * If the GADV_NAME bit is set, it indicates a dataset name is accepted as
7932
 * input.
7933
 * If the GADV_OBJECT bit is set, it indicates a dataset object is
7934
 * accepted as input.
7935
 * If both bits are set, the algorithm can accept either a name or a dataset
7936
 * object.
7937
 * Only applies to arguments of type GAAT_DATASET or GAAT_DATASET_LIST.
7938
 *
7939
 * @param hArg Handle to an argument. Must NOT be null.
7940
 * @return string whose lifetime is bound to hAlg and which must not
7941
 * be freed.
7942
 * @since 3.11
7943
 */
7944
int GDALAlgorithmArgGetDatasetInputFlags(GDALAlgorithmArgH hArg)
7945
0
{
7946
0
    VALIDATE_POINTER1(hArg, __func__, 0);
7947
0
    return hArg->ptr->GetDatasetInputFlags();
7948
0
}
7949
7950
/************************************************************************/
7951
/*               GDALAlgorithmArgGetDatasetOutputFlags()                */
7952
/************************************************************************/
7953
7954
/** Indicates which components among name and dataset are modified,
7955
 * when this argument serves as an output.
7956
 *
7957
 * If the GADV_NAME bit is set, it indicates a dataset name is generated as
7958
 * output (that is the algorithm will generate the name. Rarely used).
7959
 * If the GADV_OBJECT bit is set, it indicates a dataset object is
7960
 * generated as output, and available for use after the algorithm has
7961
 * completed.
7962
 * Only applies to arguments of type GAAT_DATASET or GAAT_DATASET_LIST.
7963
 *
7964
 * @param hArg Handle to an argument. Must NOT be null.
7965
 * @return string whose lifetime is bound to hAlg and which must not
7966
 * be freed.
7967
 * @since 3.11
7968
 */
7969
int GDALAlgorithmArgGetDatasetOutputFlags(GDALAlgorithmArgH hArg)
7970
0
{
7971
0
    VALIDATE_POINTER1(hArg, __func__, 0);
7972
0
    return hArg->ptr->GetDatasetOutputFlags();
7973
0
}
7974
7975
/************************************************************************/
7976
/*              GDALAlgorithmArgGetMutualExclusionGroup()               */
7977
/************************************************************************/
7978
7979
/** Return the name of the mutual exclusion group to which this argument
7980
 * belongs to.
7981
 *
7982
 * Or empty string if it does not belong to any exclusion group.
7983
 *
7984
 * @param hArg Handle to an argument. Must NOT be null.
7985
 * @return string whose lifetime is bound to hArg and which must not
7986
 * be freed.
7987
 * @since 3.11
7988
 */
7989
const char *GDALAlgorithmArgGetMutualExclusionGroup(GDALAlgorithmArgH hArg)
7990
0
{
7991
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
7992
0
    return hArg->ptr->GetMutualExclusionGroup().c_str();
7993
0
}
7994
7995
/************************************************************************/
7996
/*                    GDALAlgorithmArgGetAsBoolean()                    */
7997
/************************************************************************/
7998
7999
/** Return the argument value as a boolean.
8000
 *
8001
 * Must only be called on arguments whose type is GAAT_BOOLEAN.
8002
 *
8003
 * @param hArg Handle to an argument. Must NOT be null.
8004
 * @since 3.11
8005
 */
8006
bool GDALAlgorithmArgGetAsBoolean(GDALAlgorithmArgH hArg)
8007
0
{
8008
0
    VALIDATE_POINTER1(hArg, __func__, false);
8009
0
    if (hArg->ptr->GetType() != GAAT_BOOLEAN)
8010
0
    {
8011
0
        CPLError(CE_Failure, CPLE_AppDefined,
8012
0
                 "%s must only be called on arguments of type GAAT_BOOLEAN",
8013
0
                 __func__);
8014
0
        return false;
8015
0
    }
8016
0
    return hArg->ptr->Get<bool>();
8017
0
}
8018
8019
/************************************************************************/
8020
/*                    GDALAlgorithmArgGetAsString()                     */
8021
/************************************************************************/
8022
8023
/** Return the argument value as a string.
8024
 *
8025
 * Must only be called on arguments whose type is GAAT_STRING.
8026
 *
8027
 * @param hArg Handle to an argument. Must NOT be null.
8028
 * @return string whose lifetime is bound to hArg and which must not
8029
 * be freed.
8030
 * @since 3.11
8031
 */
8032
const char *GDALAlgorithmArgGetAsString(GDALAlgorithmArgH hArg)
8033
0
{
8034
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8035
0
    if (hArg->ptr->GetType() != GAAT_STRING)
8036
0
    {
8037
0
        CPLError(CE_Failure, CPLE_AppDefined,
8038
0
                 "%s must only be called on arguments of type GAAT_STRING",
8039
0
                 __func__);
8040
0
        return nullptr;
8041
0
    }
8042
0
    return hArg->ptr->Get<std::string>().c_str();
8043
0
}
8044
8045
/************************************************************************/
8046
/*                 GDALAlgorithmArgGetAsDatasetValue()                  */
8047
/************************************************************************/
8048
8049
/** Return the argument value as a GDALArgDatasetValueH.
8050
 *
8051
 * Must only be called on arguments whose type is GAAT_DATASET
8052
 *
8053
 * @param hArg Handle to an argument. Must NOT be null.
8054
 * @return handle to a GDALArgDatasetValue that must be released with
8055
 * GDALArgDatasetValueRelease(). The lifetime of that handle does not exceed
8056
 * the one of hArg.
8057
 * @since 3.11
8058
 */
8059
GDALArgDatasetValueH GDALAlgorithmArgGetAsDatasetValue(GDALAlgorithmArgH hArg)
8060
0
{
8061
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8062
0
    if (hArg->ptr->GetType() != GAAT_DATASET)
8063
0
    {
8064
0
        CPLError(CE_Failure, CPLE_AppDefined,
8065
0
                 "%s must only be called on arguments of type GAAT_DATASET",
8066
0
                 __func__);
8067
0
        return nullptr;
8068
0
    }
8069
0
    return std::make_unique<GDALArgDatasetValueHS>(
8070
0
               &(hArg->ptr->Get<GDALArgDatasetValue>()))
8071
0
        .release();
8072
0
}
8073
8074
/************************************************************************/
8075
/*                    GDALAlgorithmArgGetAsInteger()                    */
8076
/************************************************************************/
8077
8078
/** Return the argument value as a integer.
8079
 *
8080
 * Must only be called on arguments whose type is GAAT_INTEGER
8081
 *
8082
 * @param hArg Handle to an argument. Must NOT be null.
8083
 * @since 3.11
8084
 */
8085
int GDALAlgorithmArgGetAsInteger(GDALAlgorithmArgH hArg)
8086
0
{
8087
0
    VALIDATE_POINTER1(hArg, __func__, 0);
8088
0
    if (hArg->ptr->GetType() != GAAT_INTEGER)
8089
0
    {
8090
0
        CPLError(CE_Failure, CPLE_AppDefined,
8091
0
                 "%s must only be called on arguments of type GAAT_INTEGER",
8092
0
                 __func__);
8093
0
        return 0;
8094
0
    }
8095
0
    return hArg->ptr->Get<int>();
8096
0
}
8097
8098
/************************************************************************/
8099
/*                    GDALAlgorithmArgGetAsDouble()                     */
8100
/************************************************************************/
8101
8102
/** Return the argument value as a double.
8103
 *
8104
 * Must only be called on arguments whose type is GAAT_REAL
8105
 *
8106
 * @param hArg Handle to an argument. Must NOT be null.
8107
 * @since 3.11
8108
 */
8109
double GDALAlgorithmArgGetAsDouble(GDALAlgorithmArgH hArg)
8110
0
{
8111
0
    VALIDATE_POINTER1(hArg, __func__, 0);
8112
0
    if (hArg->ptr->GetType() != GAAT_REAL)
8113
0
    {
8114
0
        CPLError(CE_Failure, CPLE_AppDefined,
8115
0
                 "%s must only be called on arguments of type GAAT_REAL",
8116
0
                 __func__);
8117
0
        return 0;
8118
0
    }
8119
0
    return hArg->ptr->Get<double>();
8120
0
}
8121
8122
/************************************************************************/
8123
/*                  GDALAlgorithmArgGetAsStringList()                   */
8124
/************************************************************************/
8125
8126
/** Return the argument value as a string list.
8127
 *
8128
 * Must only be called on arguments whose type is GAAT_STRING_LIST.
8129
 *
8130
 * @param hArg Handle to an argument. Must NOT be null.
8131
 * @return a NULL terminated list of names, which must be destroyed with
8132
 * CSLDestroy()
8133
8134
 * @since 3.11
8135
 */
8136
char **GDALAlgorithmArgGetAsStringList(GDALAlgorithmArgH hArg)
8137
0
{
8138
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8139
0
    if (hArg->ptr->GetType() != GAAT_STRING_LIST)
8140
0
    {
8141
0
        CPLError(CE_Failure, CPLE_AppDefined,
8142
0
                 "%s must only be called on arguments of type GAAT_STRING_LIST",
8143
0
                 __func__);
8144
0
        return nullptr;
8145
0
    }
8146
0
    return CPLStringList(hArg->ptr->Get<std::vector<std::string>>())
8147
0
        .StealList();
8148
0
}
8149
8150
/************************************************************************/
8151
/*                  GDALAlgorithmArgGetAsIntegerList()                  */
8152
/************************************************************************/
8153
8154
/** Return the argument value as a integer list.
8155
 *
8156
 * Must only be called on arguments whose type is GAAT_INTEGER_LIST.
8157
 *
8158
 * @param hArg Handle to an argument. Must NOT be null.
8159
 * @param[out] pnCount Pointer to the number of values in the list. Must NOT be null.
8160
 * @since 3.11
8161
 */
8162
const int *GDALAlgorithmArgGetAsIntegerList(GDALAlgorithmArgH hArg,
8163
                                            size_t *pnCount)
8164
0
{
8165
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8166
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
8167
0
    if (hArg->ptr->GetType() != GAAT_INTEGER_LIST)
8168
0
    {
8169
0
        CPLError(
8170
0
            CE_Failure, CPLE_AppDefined,
8171
0
            "%s must only be called on arguments of type GAAT_INTEGER_LIST",
8172
0
            __func__);
8173
0
        *pnCount = 0;
8174
0
        return nullptr;
8175
0
    }
8176
0
    const auto &val = hArg->ptr->Get<std::vector<int>>();
8177
0
    *pnCount = val.size();
8178
0
    return val.data();
8179
0
}
8180
8181
/************************************************************************/
8182
/*                  GDALAlgorithmArgGetAsDoubleList()                   */
8183
/************************************************************************/
8184
8185
/** Return the argument value as a real list.
8186
 *
8187
 * Must only be called on arguments whose type is GAAT_REAL_LIST.
8188
 *
8189
 * @param hArg Handle to an argument. Must NOT be null.
8190
 * @param[out] pnCount Pointer to the number of values in the list. Must NOT be null.
8191
 * @since 3.11
8192
 */
8193
const double *GDALAlgorithmArgGetAsDoubleList(GDALAlgorithmArgH hArg,
8194
                                              size_t *pnCount)
8195
0
{
8196
0
    VALIDATE_POINTER1(hArg, __func__, nullptr);
8197
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
8198
0
    if (hArg->ptr->GetType() != GAAT_REAL_LIST)
8199
0
    {
8200
0
        CPLError(CE_Failure, CPLE_AppDefined,
8201
0
                 "%s must only be called on arguments of type GAAT_REAL_LIST",
8202
0
                 __func__);
8203
0
        *pnCount = 0;
8204
0
        return nullptr;
8205
0
    }
8206
0
    const auto &val = hArg->ptr->Get<std::vector<double>>();
8207
0
    *pnCount = val.size();
8208
0
    return val.data();
8209
0
}
8210
8211
/************************************************************************/
8212
/*                    GDALAlgorithmArgSetAsBoolean()                    */
8213
/************************************************************************/
8214
8215
/** Set the value for a GAAT_BOOLEAN argument.
8216
 *
8217
 * It cannot be called several times for a given argument.
8218
 * Validation checks and other actions are run.
8219
 *
8220
 * @param hArg Handle to an argument. Must NOT be null.
8221
 * @param value value.
8222
 * @return true if success.
8223
 * @since 3.11
8224
 */
8225
8226
bool GDALAlgorithmArgSetAsBoolean(GDALAlgorithmArgH hArg, bool value)
8227
0
{
8228
0
    VALIDATE_POINTER1(hArg, __func__, false);
8229
0
    return hArg->ptr->Set(value);
8230
0
}
8231
8232
/************************************************************************/
8233
/*                    GDALAlgorithmArgSetAsString()                     */
8234
/************************************************************************/
8235
8236
/** Set the value for a GAAT_STRING argument.
8237
 *
8238
 * It cannot be called several times for a given argument.
8239
 * Validation checks and other actions are run.
8240
 *
8241
 * @param hArg Handle to an argument. Must NOT be null.
8242
 * @param value value (may be null)
8243
 * @return true if success.
8244
 * @since 3.11
8245
 */
8246
8247
bool GDALAlgorithmArgSetAsString(GDALAlgorithmArgH hArg, const char *value)
8248
0
{
8249
0
    VALIDATE_POINTER1(hArg, __func__, false);
8250
0
    return hArg->ptr->Set(value ? value : "");
8251
0
}
8252
8253
/************************************************************************/
8254
/*                    GDALAlgorithmArgSetAsInteger()                    */
8255
/************************************************************************/
8256
8257
/** Set the value for a GAAT_INTEGER (or GAAT_REAL) argument.
8258
 *
8259
 * It cannot be called several times for a given argument.
8260
 * Validation checks and other actions are run.
8261
 *
8262
 * @param hArg Handle to an argument. Must NOT be null.
8263
 * @param value value.
8264
 * @return true if success.
8265
 * @since 3.11
8266
 */
8267
8268
bool GDALAlgorithmArgSetAsInteger(GDALAlgorithmArgH hArg, int value)
8269
0
{
8270
0
    VALIDATE_POINTER1(hArg, __func__, false);
8271
0
    return hArg->ptr->Set(value);
8272
0
}
8273
8274
/************************************************************************/
8275
/*                    GDALAlgorithmArgSetAsDouble()                     */
8276
/************************************************************************/
8277
8278
/** Set the value for a GAAT_REAL argument.
8279
 *
8280
 * It cannot be called several times for a given argument.
8281
 * Validation checks and other actions are run.
8282
 *
8283
 * @param hArg Handle to an argument. Must NOT be null.
8284
 * @param value value.
8285
 * @return true if success.
8286
 * @since 3.11
8287
 */
8288
8289
bool GDALAlgorithmArgSetAsDouble(GDALAlgorithmArgH hArg, double value)
8290
0
{
8291
0
    VALIDATE_POINTER1(hArg, __func__, false);
8292
0
    return hArg->ptr->Set(value);
8293
0
}
8294
8295
/************************************************************************/
8296
/*                 GDALAlgorithmArgSetAsDatasetValue()                  */
8297
/************************************************************************/
8298
8299
/** Set the value for a GAAT_DATASET argument.
8300
 *
8301
 * It cannot be called several times for a given argument.
8302
 * Validation checks and other actions are run.
8303
 *
8304
 * @param hArg Handle to an argument. Must NOT be null.
8305
 * @param value Handle to a GDALArgDatasetValue. Must NOT be null.
8306
 * @return true if success.
8307
 * @since 3.11
8308
 */
8309
bool GDALAlgorithmArgSetAsDatasetValue(GDALAlgorithmArgH hArg,
8310
                                       GDALArgDatasetValueH value)
8311
0
{
8312
0
    VALIDATE_POINTER1(hArg, __func__, false);
8313
0
    VALIDATE_POINTER1(value, __func__, false);
8314
0
    return hArg->ptr->SetFrom(*(value->ptr));
8315
0
}
8316
8317
/************************************************************************/
8318
/*                     GDALAlgorithmArgSetDataset()                     */
8319
/************************************************************************/
8320
8321
/** Set dataset object, increasing its reference counter.
8322
 *
8323
 * @param hArg Handle to an argument. Must NOT be null.
8324
 * @param hDS Dataset object. May be null.
8325
 * @return true if success.
8326
 * @since 3.11
8327
 */
8328
8329
bool GDALAlgorithmArgSetDataset(GDALAlgorithmArgH hArg, GDALDatasetH hDS)
8330
0
{
8331
0
    VALIDATE_POINTER1(hArg, __func__, false);
8332
0
    return hArg->ptr->Set(GDALDataset::FromHandle(hDS));
8333
0
}
8334
8335
/************************************************************************/
8336
/*                  GDALAlgorithmArgSetAsStringList()                   */
8337
/************************************************************************/
8338
8339
/** Set the value for a GAAT_STRING_LIST argument.
8340
 *
8341
 * It cannot be called several times for a given argument.
8342
 * Validation checks and other actions are run.
8343
 *
8344
 * @param hArg Handle to an argument. Must NOT be null.
8345
 * @param value value as a NULL terminated list (may be null)
8346
 * @return true if success.
8347
 * @since 3.11
8348
 */
8349
8350
bool GDALAlgorithmArgSetAsStringList(GDALAlgorithmArgH hArg, CSLConstList value)
8351
0
{
8352
0
    VALIDATE_POINTER1(hArg, __func__, false);
8353
0
    return hArg->ptr->Set(
8354
0
        static_cast<std::vector<std::string>>(CPLStringList(value)));
8355
0
}
8356
8357
/************************************************************************/
8358
/*                  GDALAlgorithmArgSetAsIntegerList()                  */
8359
/************************************************************************/
8360
8361
/** Set the value for a GAAT_INTEGER_LIST argument.
8362
 *
8363
 * It cannot be called several times for a given argument.
8364
 * Validation checks and other actions are run.
8365
 *
8366
 * @param hArg Handle to an argument. Must NOT be null.
8367
 * @param nCount Number of values in pnValues.
8368
 * @param pnValues Pointer to an array of integer values of size nCount.
8369
 * @return true if success.
8370
 * @since 3.11
8371
 */
8372
bool GDALAlgorithmArgSetAsIntegerList(GDALAlgorithmArgH hArg, size_t nCount,
8373
                                      const int *pnValues)
8374
0
{
8375
0
    VALIDATE_POINTER1(hArg, __func__, false);
8376
0
    return hArg->ptr->Set(std::vector<int>(pnValues, pnValues + nCount));
8377
0
}
8378
8379
/************************************************************************/
8380
/*                  GDALAlgorithmArgSetAsDoubleList()                   */
8381
/************************************************************************/
8382
8383
/** Set the value for a GAAT_REAL_LIST argument.
8384
 *
8385
 * It cannot be called several times for a given argument.
8386
 * Validation checks and other actions are run.
8387
 *
8388
 * @param hArg Handle to an argument. Must NOT be null.
8389
 * @param nCount Number of values in pnValues.
8390
 * @param pnValues Pointer to an array of double values of size nCount.
8391
 * @return true if success.
8392
 * @since 3.11
8393
 */
8394
bool GDALAlgorithmArgSetAsDoubleList(GDALAlgorithmArgH hArg, size_t nCount,
8395
                                     const double *pnValues)
8396
0
{
8397
0
    VALIDATE_POINTER1(hArg, __func__, false);
8398
0
    return hArg->ptr->Set(std::vector<double>(pnValues, pnValues + nCount));
8399
0
}
8400
8401
/************************************************************************/
8402
/*                    GDALAlgorithmArgSetDatasets()                     */
8403
/************************************************************************/
8404
8405
/** Set dataset objects to a GAAT_DATASET_LIST argument, increasing their reference counter.
8406
 *
8407
 * @param hArg Handle to an argument. Must NOT be null.
8408
 * @param nCount Number of values in pnValues.
8409
 * @param pahDS Pointer to an array of dataset of size nCount.
8410
 * @return true if success.
8411
 * @since 3.11
8412
 */
8413
8414
bool GDALAlgorithmArgSetDatasets(GDALAlgorithmArgH hArg, size_t nCount,
8415
                                 GDALDatasetH *pahDS)
8416
0
{
8417
0
    VALIDATE_POINTER1(hArg, __func__, false);
8418
0
    std::vector<GDALArgDatasetValue> values;
8419
0
    for (size_t i = 0; i < nCount; ++i)
8420
0
    {
8421
0
        values.emplace_back(GDALDataset::FromHandle(pahDS[i]));
8422
0
    }
8423
0
    return hArg->ptr->Set(std::move(values));
8424
0
}
8425
8426
/************************************************************************/
8427
/*                  GDALAlgorithmArgSetDatasetNames()                   */
8428
/************************************************************************/
8429
8430
/** Set dataset names to a GAAT_DATASET_LIST argument.
8431
 *
8432
 * @param hArg Handle to an argument. Must NOT be null.
8433
 * @param names Dataset names as a NULL terminated list (may be null)
8434
 * @return true if success.
8435
 * @since 3.11
8436
 */
8437
8438
bool GDALAlgorithmArgSetDatasetNames(GDALAlgorithmArgH hArg, CSLConstList names)
8439
0
{
8440
0
    VALIDATE_POINTER1(hArg, __func__, false);
8441
0
    std::vector<GDALArgDatasetValue> values;
8442
0
    for (size_t i = 0; names[i]; ++i)
8443
0
    {
8444
0
        values.emplace_back(names[i]);
8445
0
    }
8446
0
    return hArg->ptr->Set(std::move(values));
8447
0
}
8448
8449
/************************************************************************/
8450
/*                     GDALArgDatasetValueCreate()                      */
8451
/************************************************************************/
8452
8453
/** Instantiate an empty GDALArgDatasetValue
8454
 *
8455
 * @return new handle to free with GDALArgDatasetValueRelease()
8456
 * @since 3.11
8457
 */
8458
GDALArgDatasetValueH GDALArgDatasetValueCreate()
8459
0
{
8460
0
    return std::make_unique<GDALArgDatasetValueHS>().release();
8461
0
}
8462
8463
/************************************************************************/
8464
/*                     GDALArgDatasetValueRelease()                     */
8465
/************************************************************************/
8466
8467
/** Release a handle to a GDALArgDatasetValue
8468
 *
8469
 * @since 3.11
8470
 */
8471
void GDALArgDatasetValueRelease(GDALArgDatasetValueH hValue)
8472
0
{
8473
0
    delete hValue;
8474
0
}
8475
8476
/************************************************************************/
8477
/*                     GDALArgDatasetValueGetName()                     */
8478
/************************************************************************/
8479
8480
/** Return the name component of the GDALArgDatasetValue
8481
 *
8482
 * @param hValue Handle to a GDALArgDatasetValue. Must NOT be null.
8483
 * @return string whose lifetime is bound to hAlg and which must not
8484
 * be freed.
8485
 * @since 3.11
8486
 */
8487
const char *GDALArgDatasetValueGetName(GDALArgDatasetValueH hValue)
8488
0
{
8489
0
    VALIDATE_POINTER1(hValue, __func__, nullptr);
8490
0
    return hValue->ptr->GetName().c_str();
8491
0
}
8492
8493
/************************************************************************/
8494
/*                  GDALArgDatasetValueGetDatasetRef()                  */
8495
/************************************************************************/
8496
8497
/** Return the dataset component of the GDALArgDatasetValue.
8498
 *
8499
 * This does not modify the reference counter, hence the lifetime of the
8500
 * returned object is not guaranteed to exceed the one of hValue.
8501
 *
8502
 * @param hValue Handle to a GDALArgDatasetValue. Must NOT be null.
8503
 * @since 3.11
8504
 */
8505
GDALDatasetH GDALArgDatasetValueGetDatasetRef(GDALArgDatasetValueH hValue)
8506
0
{
8507
0
    VALIDATE_POINTER1(hValue, __func__, nullptr);
8508
0
    return GDALDataset::ToHandle(hValue->ptr->GetDatasetRef());
8509
0
}
8510
8511
/************************************************************************/
8512
/*           GDALArgDatasetValueGetDatasetIncreaseRefCount()            */
8513
/************************************************************************/
8514
8515
/** Return the dataset component of the GDALArgDatasetValue, and increase its
8516
 * reference count if not null. Once done with the dataset, the caller should
8517
 * call GDALReleaseDataset().
8518
 *
8519
 * @param hValue Handle to a GDALArgDatasetValue. Must NOT be null.
8520
 * @since 3.11
8521
 */
8522
GDALDatasetH
8523
GDALArgDatasetValueGetDatasetIncreaseRefCount(GDALArgDatasetValueH hValue)
8524
0
{
8525
0
    VALIDATE_POINTER1(hValue, __func__, nullptr);
8526
0
    return GDALDataset::ToHandle(hValue->ptr->GetDatasetIncreaseRefCount());
8527
0
}
8528
8529
/************************************************************************/
8530
/*                     GDALArgDatasetValueSetName()                     */
8531
/************************************************************************/
8532
8533
/** Set dataset name
8534
 *
8535
 * @param hValue Handle to a GDALArgDatasetValue. Must NOT be null.
8536
 * @param pszName Dataset name. May be null.
8537
 * @since 3.11
8538
 */
8539
8540
void GDALArgDatasetValueSetName(GDALArgDatasetValueH hValue,
8541
                                const char *pszName)
8542
0
{
8543
0
    VALIDATE_POINTER0(hValue, __func__);
8544
0
    hValue->ptr->Set(pszName ? pszName : "");
8545
0
}
8546
8547
/************************************************************************/
8548
/*                   GDALArgDatasetValueSetDataset()                    */
8549
/************************************************************************/
8550
8551
/** Set dataset object, increasing its reference counter.
8552
 *
8553
 * @param hValue Handle to a GDALArgDatasetValue. Must NOT be null.
8554
 * @param hDS Dataset object. May be null.
8555
 * @since 3.11
8556
 */
8557
8558
void GDALArgDatasetValueSetDataset(GDALArgDatasetValueH hValue,
8559
                                   GDALDatasetH hDS)
8560
0
{
8561
0
    VALIDATE_POINTER0(hValue, __func__);
8562
0
    hValue->ptr->Set(GDALDataset::FromHandle(hDS));
8563
0
}