Coverage Report

Created: 2025-12-31 06:48

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