Coverage Report

Created: 2025-06-13 06:29

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