File: cpl_path.cpp

package info (click to toggle)
gdal 3.6.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 89,664 kB
  • sloc: cpp: 1,136,033; ansic: 197,355; python: 35,910; java: 5,511; xml: 4,011; sh: 3,950; cs: 2,443; yacc: 1,047; makefile: 288
file content (1217 lines) | stat: -rw-r--r-- 43,238 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
/**********************************************************************
 *
 * Project:  CPL - Common Portability Library
 * Purpose:  Portable filename/path parsing, and forming ala "Glob API".
 * Author:   Frank Warmerdam, warmerdam@pobox.com
 *
 **********************************************************************
 * Copyright (c) 1999, Frank Warmerdam
 * Copyright (c) 2008-2012, Even Rouault <even dot rouault at spatialys.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 ****************************************************************************/

#include "cpl_port.h"
#include "cpl_conv.h"

#include <cctype>
#include <climits>
#include <cstddef>
#include <cstdio>
#include <cstring>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif

#include <algorithm>
#include <string>

#include "cpl_atomic_ops.h"
#include "cpl_config.h"
#include "cpl_error.h"
#include "cpl_multiproc.h"
#include "cpl_string.h"
#include "cpl_vsi.h"

// Should be size of larged possible filename.
constexpr int CPL_PATH_BUF_SIZE = 2048;
constexpr int CPL_PATH_BUF_COUNT = 10;

#if defined(WIN32)
constexpr char SEP_STRING[] = "\\";
#else
constexpr char SEP_STRING[] = "/";
#endif

static const char *CPLStaticBufferTooSmall(char *pszStaticResult)
{
    CPLError(CE_Failure, CPLE_AppDefined, "Destination buffer too small");
    if (pszStaticResult == nullptr)
        return "";
    strcpy(pszStaticResult, "");
    return pszStaticResult;
}

/************************************************************************/
/*                         CPLGetStaticResult()                         */
/************************************************************************/

static char *CPLGetStaticResult()

{
    int bMemoryError = FALSE;
    char *pachBufRingInfo =
        static_cast<char *>(CPLGetTLSEx(CTLS_PATHBUF, &bMemoryError));
    if (bMemoryError)
        return nullptr;
    if (pachBufRingInfo == nullptr)
    {
        pachBufRingInfo = static_cast<char *>(VSI_CALLOC_VERBOSE(
            1, sizeof(int) + CPL_PATH_BUF_SIZE * CPL_PATH_BUF_COUNT));
        if (pachBufRingInfo == nullptr)
            return nullptr;
        CPLSetTLS(CTLS_PATHBUF, pachBufRingInfo, TRUE);
    }

    /* -------------------------------------------------------------------- */
    /*      Work out which string in the "ring" we want to use this         */
    /*      time.                                                           */
    /* -------------------------------------------------------------------- */
    int *pnBufIndex = reinterpret_cast<int *>(pachBufRingInfo);
    const size_t nOffset =
        sizeof(int) + static_cast<size_t>(*pnBufIndex * CPL_PATH_BUF_SIZE);
    char *pachBuffer = pachBufRingInfo + nOffset;

    *pnBufIndex = (*pnBufIndex + 1) % CPL_PATH_BUF_COUNT;

    return pachBuffer;
}

/************************************************************************/
/*                        CPLFindFilenameStart()                        */
/************************************************************************/

static int CPLFindFilenameStart(const char *pszFilename)

{
    size_t iFileStart = strlen(pszFilename);

    for (; iFileStart > 0 && pszFilename[iFileStart - 1] != '/' &&
           pszFilename[iFileStart - 1] != '\\';
         iFileStart--)
    {
    }

    return static_cast<int>(iFileStart);
}

/************************************************************************/
/*                             CPLGetPath()                             */
/************************************************************************/

/**
 * Extract directory path portion of filename.
 *
 * Returns a string containing the directory path portion of the passed
 * filename.  If there is no path in the passed filename an empty string
 * will be returned (not NULL).
 *
 * <pre>
 * CPLGetPath( "abc/def.xyz" ) == "abc"
 * CPLGetPath( "/abc/def/" ) == "/abc/def"
 * CPLGetPath( "/" ) == "/"
 * CPLGetPath( "/abc/def" ) == "/abc"
 * CPLGetPath( "abc" ) == ""
 * </pre>
 *
 * @param pszFilename the filename potentially including a path.
 *
 *  @return Path in an internal string which must not be freed.  The string
 * may be destroyed by the next CPL filename handling call.  The returned
 * will generally not contain a trailing path separator.
 */

const char *CPLGetPath(const char *pszFilename)

{
    const int iFileStart = CPLFindFilenameStart(pszFilename);
    char *pszStaticResult = CPLGetStaticResult();

    if (pszStaticResult == nullptr || iFileStart >= CPL_PATH_BUF_SIZE)
        return CPLStaticBufferTooSmall(pszStaticResult);

    CPLAssert(!(pszFilename >= pszStaticResult &&
                pszFilename < pszStaticResult + CPL_PATH_BUF_SIZE));

    if (iFileStart == 0)
    {
        strcpy(pszStaticResult, "");
        return pszStaticResult;
    }

    CPLStrlcpy(pszStaticResult, pszFilename,
               static_cast<size_t>(iFileStart) + 1);

    if (iFileStart > 1 && (pszStaticResult[iFileStart - 1] == '/' ||
                           pszStaticResult[iFileStart - 1] == '\\'))
        pszStaticResult[iFileStart - 1] = '\0';

    return pszStaticResult;
}

/************************************************************************/
/*                             CPLGetDirname()                          */
/************************************************************************/

/**
 * Extract directory path portion of filename.
 *
 * Returns a string containing the directory path portion of the passed
 * filename.  If there is no path in the passed filename the dot will be
 * returned.  It is the only difference from CPLGetPath().
 *
 * <pre>
 * CPLGetDirname( "abc/def.xyz" ) == "abc"
 * CPLGetDirname( "/abc/def/" ) == "/abc/def"
 * CPLGetDirname( "/" ) == "/"
 * CPLGetDirname( "/abc/def" ) == "/abc"
 * CPLGetDirname( "abc" ) == "."
 * </pre>
 *
 * @param pszFilename the filename potentially including a path.
 *
 * @return Path in an internal string which must not be freed.  The string
 * may be destroyed by the next CPL filename handling call.  The returned
 * will generally not contain a trailing path separator.
 */

const char *CPLGetDirname(const char *pszFilename)

{
    const int iFileStart = CPLFindFilenameStart(pszFilename);
    char *pszStaticResult = CPLGetStaticResult();

    if (pszStaticResult == nullptr || iFileStart >= CPL_PATH_BUF_SIZE)
        return CPLStaticBufferTooSmall(pszStaticResult);

    CPLAssert(!(pszFilename >= pszStaticResult &&
                pszFilename < pszStaticResult + CPL_PATH_BUF_SIZE));

    if (iFileStart == 0)
    {
        strcpy(pszStaticResult, ".");
        return pszStaticResult;
    }

    CPLStrlcpy(pszStaticResult, pszFilename,
               static_cast<size_t>(iFileStart) + 1);

    if (iFileStart > 1 && (pszStaticResult[iFileStart - 1] == '/' ||
                           pszStaticResult[iFileStart - 1] == '\\'))
        pszStaticResult[iFileStart - 1] = '\0';

    return pszStaticResult;
}

/************************************************************************/
/*                           CPLGetFilename()                           */
/************************************************************************/

/**
 * Extract non-directory portion of filename.
 *
 * Returns a string containing the bare filename portion of the passed
 * filename.  If there is no filename (passed value ends in trailing directory
 * separator) an empty string is returned.
 *
 * <pre>
 * CPLGetFilename( "abc/def.xyz" ) == "def.xyz"
 * CPLGetFilename( "/abc/def/" ) == ""
 * CPLGetFilename( "abc/def" ) == "def"
 * </pre>
 *
 * @param pszFullFilename the full filename potentially including a path.
 *
 * @return just the non-directory portion of the path (points back into
 * original string).
 */

const char *CPLGetFilename(const char *pszFullFilename)

{
    const int iFileStart = CPLFindFilenameStart(pszFullFilename);

    return pszFullFilename + iFileStart;
}

/************************************************************************/
/*                           CPLGetBasename()                           */
/************************************************************************/

/**
 * Extract basename (non-directory, non-extension) portion of filename.
 *
 * Returns a string containing the file basename portion of the passed
 * name.  If there is no basename (passed value ends in trailing directory
 * separator, or filename starts with a dot) an empty string is returned.
 *
 * <pre>
 * CPLGetBasename( "abc/def.xyz" ) == "def"
 * CPLGetBasename( "abc/def" ) == "def"
 * CPLGetBasename( "abc/def/" ) == ""
 * </pre>
 *
 * @param pszFullFilename the full filename potentially including a path.
 *
 * @return just the non-directory, non-extension portion of the path in
 * an internal string which must not be freed.  The string
 * may be destroyed by the next CPL filename handling call.
 */

const char *CPLGetBasename(const char *pszFullFilename)

{
    const size_t iFileStart =
        static_cast<size_t>(CPLFindFilenameStart(pszFullFilename));
    char *pszStaticResult = CPLGetStaticResult();
    if (pszStaticResult == nullptr)
        return CPLStaticBufferTooSmall(pszStaticResult);

    CPLAssert(!(pszFullFilename >= pszStaticResult &&
                pszFullFilename < pszStaticResult + CPL_PATH_BUF_SIZE));

    size_t iExtStart = strlen(pszFullFilename);
    for (; iExtStart > iFileStart && pszFullFilename[iExtStart] != '.';
         iExtStart--)
    {
    }

    if (iExtStart == iFileStart)
        iExtStart = strlen(pszFullFilename);

    const size_t nLength = iExtStart - iFileStart;

    if (nLength >= static_cast<size_t>(CPL_PATH_BUF_SIZE))
        return CPLStaticBufferTooSmall(pszStaticResult);

    CPLStrlcpy(pszStaticResult, pszFullFilename + iFileStart, nLength + 1);

    return pszStaticResult;
}

/************************************************************************/
/*                           CPLGetExtension()                          */
/************************************************************************/

/**
 * Extract filename extension from full filename.
 *
 * Returns a string containing the extension portion of the passed
 * name.  If there is no extension (the filename has no dot) an empty string
 * is returned.  The returned extension will not include the period.
 *
 * <pre>
 * CPLGetExtension( "abc/def.xyz" ) == "xyz"
 * CPLGetExtension( "abc/def" ) == ""
 * </pre>
 *
 * @param pszFullFilename the full filename potentially including a path.
 *
 * @return just the extension portion of the path in
 * an internal string which must not be freed.  The string
 * may be destroyed by the next CPL filename handling call.
 */

const char *CPLGetExtension(const char *pszFullFilename)

{
    if (pszFullFilename[0] == '\0')
        return "";

    size_t iFileStart =
        static_cast<size_t>(CPLFindFilenameStart(pszFullFilename));
    char *pszStaticResult = CPLGetStaticResult();
    if (pszStaticResult == nullptr)
        return CPLStaticBufferTooSmall(pszStaticResult);

    CPLAssert(!(pszFullFilename >= pszStaticResult &&
                pszFullFilename < pszStaticResult + CPL_PATH_BUF_SIZE));

    size_t iExtStart = strlen(pszFullFilename);
    for (; iExtStart > iFileStart && pszFullFilename[iExtStart] != '.';
         iExtStart--)
    {
    }

    if (iExtStart == iFileStart)
        iExtStart = strlen(pszFullFilename) - 1;

    // If the extension is too long, it is very much likely not an extension,
    // but another component of the path
    const size_t knMaxExtensionSize = 10;
    if (strlen(pszFullFilename + iExtStart + 1) > knMaxExtensionSize)
        return "";

    if (CPLStrlcpy(pszStaticResult, pszFullFilename + iExtStart + 1,
                   CPL_PATH_BUF_SIZE) >= static_cast<size_t>(CPL_PATH_BUF_SIZE))
        return CPLStaticBufferTooSmall(pszStaticResult);

    return pszStaticResult;
}

/************************************************************************/
/*                         CPLGetCurrentDir()                           */
/************************************************************************/

/**
 * Get the current working directory name.
 *
 * @return a pointer to buffer, containing current working directory path
 * or NULL in case of error.  User is responsible to free that buffer
 * after usage with CPLFree() function.
 * If HAVE_GETCWD macro is not defined, the function returns NULL.
 **/

#ifdef _WIN32
char *CPLGetCurrentDir()
{
    const size_t nPathMax = _MAX_PATH;
    wchar_t *pwszDirPath =
        static_cast<wchar_t *>(VSI_MALLOC_VERBOSE(nPathMax * sizeof(wchar_t)));
    char *pszRet = nullptr;
    if (pwszDirPath != nullptr && _wgetcwd(pwszDirPath, nPathMax) != nullptr)
    {
        pszRet = CPLRecodeFromWChar(pwszDirPath, CPL_ENC_UCS2, CPL_ENC_UTF8);
    }
    CPLFree(pwszDirPath);
    return pszRet;
}
#elif defined(HAVE_GETCWD)
char *CPLGetCurrentDir()
{
#if PATH_MAX
    const size_t nPathMax = PATH_MAX;
#else
    const size_t nPathMax = 8192;
#endif

    char *pszDirPath = static_cast<char *>(VSI_MALLOC_VERBOSE(nPathMax));
    if (!pszDirPath)
        return nullptr;

    return getcwd(pszDirPath, nPathMax);
}
#else   // !HAVE_GETCWD
char *CPLGetCurrentDir()
{
    return nullptr;
}
#endif  // HAVE_GETCWD

/************************************************************************/
/*                         CPLResetExtension()                          */
/************************************************************************/

/**
 * Replace the extension with the provided one.
 *
 * @param pszPath the input path, this string is not altered.
 * @param pszExt the new extension to apply to the given path.
 *
 * @return an altered filename with the new extension.    Do not
 * modify or free the returned string.  The string may be destroyed by the
 * next CPL call.
 */

const char *CPLResetExtension(const char *pszPath, const char *pszExt)

{
    char *pszStaticResult = CPLGetStaticResult();
    if (pszStaticResult == nullptr)
        return CPLStaticBufferTooSmall(pszStaticResult);

    CPLAssert(!(pszPath >= pszStaticResult &&
                pszPath < pszStaticResult + CPL_PATH_BUF_SIZE));

    /* -------------------------------------------------------------------- */
    /*      First, try and strip off any existing extension.                */
    /* -------------------------------------------------------------------- */
    if (CPLStrlcpy(pszStaticResult, pszPath, CPL_PATH_BUF_SIZE) >=
        static_cast<size_t>(CPL_PATH_BUF_SIZE))
        return CPLStaticBufferTooSmall(pszStaticResult);

    if (*pszStaticResult)
    {
        for (size_t i = strlen(pszStaticResult) - 1; i > 0; i--)
        {
            if (pszStaticResult[i] == '.')
            {
                pszStaticResult[i] = '\0';
                break;
            }

            if (pszStaticResult[i] == '/' || pszStaticResult[i] == '\\' ||
                pszStaticResult[i] == ':')
                break;
        }
    }

    /* -------------------------------------------------------------------- */
    /*      Append the new extension.                                       */
    /* -------------------------------------------------------------------- */
    if (CPLStrlcat(pszStaticResult, ".", CPL_PATH_BUF_SIZE) >=
            static_cast<size_t>(CPL_PATH_BUF_SIZE) ||
        CPLStrlcat(pszStaticResult, pszExt, CPL_PATH_BUF_SIZE) >=
            static_cast<size_t>(CPL_PATH_BUF_SIZE))
    {
        return CPLStaticBufferTooSmall(pszStaticResult);
    }

    return pszStaticResult;
}

/************************************************************************/
/*                       RequiresUnixPathSeparator()                    */
/************************************************************************/

#if defined(WIN32)
static bool RequiresUnixPathSeparator(const char *pszPath)
{
    return strcmp(pszPath, "/vsimem") == 0 || STARTS_WITH(pszPath, "http://") ||
           STARTS_WITH(pszPath, "https://") ||
           STARTS_WITH(pszPath, "/vsimem/") ||
           STARTS_WITH(pszPath, "/vsicurl/") ||
           STARTS_WITH(pszPath, "/vsicurl_streaming/") ||
           STARTS_WITH(pszPath, "/vsis3/") ||
           STARTS_WITH(pszPath, "/vsis3_streaming/") ||
           STARTS_WITH(pszPath, "/vsigs/") ||
           STARTS_WITH(pszPath, "/vsigs_streaming/") ||
           STARTS_WITH(pszPath, "/vsiaz/") ||
           STARTS_WITH(pszPath, "/vsiaz_streaming/") ||
           STARTS_WITH(pszPath, "/vsiadls/") ||
           STARTS_WITH(pszPath, "/vsioss/") ||
           STARTS_WITH(pszPath, "/vsioss_streaming/") ||
           STARTS_WITH(pszPath, "/vsiswift/") ||
           STARTS_WITH(pszPath, "/vsiswift_streaming/") ||
           STARTS_WITH(pszPath, "/vsizip/");
}
#endif

/************************************************************************/
/*                          CPLFormFilename()                           */
/************************************************************************/

/**
 * Build a full file path from a passed path, file basename and extension.
 *
 * The path, and extension are optional.  The basename may in fact contain
 * an extension if desired.
 *
 * <pre>
 * CPLFormFilename("abc/xyz", "def", ".dat" ) == "abc/xyz/def.dat"
 * CPLFormFilename(NULL,"def", NULL ) == "def"
 * CPLFormFilename(NULL, "abc/def.dat", NULL ) == "abc/def.dat"
 * CPLFormFilename("/abc/xyz/", "def.dat", NULL ) == "/abc/xyz/def.dat"
 * </pre>
 *
 * @param pszPath directory path to the directory containing the file.  This
 * may be relative or absolute, and may have a trailing path separator or
 * not.  May be NULL.
 *
 * @param pszBasename file basename.  May optionally have path and/or
 * extension.  Must *NOT* be NULL.
 *
 * @param pszExtension file extension, optionally including the period.  May
 * be NULL.
 *
 * @return a fully formed filename in an internal static string.  Do not
 * modify or free the returned string.  The string may be destroyed by the
 * next CPL call.
 */

const char *CPLFormFilename(const char *pszPath, const char *pszBasename,
                            const char *pszExtension)

{
    char *pszStaticResult = CPLGetStaticResult();
    if (pszStaticResult == nullptr)
        return CPLStaticBufferTooSmall(pszStaticResult);

    CPLAssert(!(pszPath >= pszStaticResult &&
                pszPath < pszStaticResult + CPL_PATH_BUF_SIZE));
    CPLAssert(!(pszBasename >= pszStaticResult &&
                pszBasename < pszStaticResult + CPL_PATH_BUF_SIZE));

    if (pszBasename[0] == '.' &&
        (pszBasename[1] == '/' || pszBasename[1] == '\\'))
        pszBasename += 2;

    const char *pszAddedPathSep = "";
    const char *pszAddedExtSep = "";

    if (pszPath == nullptr)
        pszPath = "";
    size_t nLenPath = strlen(pszPath);
    if (!CPLIsFilenameRelative(pszPath) && strcmp(pszBasename, "..") == 0)
    {
        // /a/b + .. --> /a
        if (pszPath[nLenPath - 1] == '\\' || pszPath[nLenPath - 1] == '/')
            nLenPath--;
        size_t nLenPathOri = nLenPath;
        while (nLenPath > 0 && pszPath[nLenPath - 1] != '\\' &&
               pszPath[nLenPath - 1] != '/')
        {
            nLenPath--;
        }
        if (nLenPath == 1 && pszPath[0] == '/')
        {
            pszBasename = "";
        }
        else if ((nLenPath > 1 && pszPath[0] == '/') ||
                 (nLenPath > 2 && pszPath[1] == ':') ||
                 (nLenPath > 6 && strncmp(pszPath, "\\\\$\\", 4) == 0))
        {
            nLenPath--;
            pszBasename = "";
        }
        else
        {
            nLenPath = nLenPathOri;
            pszAddedPathSep = SEP_STRING;
        }
    }
    else if (nLenPath > 0 && pszPath[nLenPath - 1] != '/' &&
             pszPath[nLenPath - 1] != '\\')
    {
#if defined(WIN32)
        // FIXME? Would be better to ask the filesystems what it
        // prefers as directory separator?
        if (RequiresUnixPathSeparator(pszPath))
            pszAddedPathSep = "/";
        else
#endif
        {
            pszAddedPathSep = SEP_STRING;
        }
    }

    if (pszExtension == nullptr)
        pszExtension = "";
    else if (pszExtension[0] != '.' && strlen(pszExtension) > 0)
        pszAddedExtSep = ".";

    if (CPLStrlcpy(
            pszStaticResult, pszPath,
            std::min(nLenPath + 1, static_cast<size_t>(CPL_PATH_BUF_SIZE))) >=
            static_cast<size_t>(CPL_PATH_BUF_SIZE) ||
        CPLStrlcat(pszStaticResult, pszAddedPathSep, CPL_PATH_BUF_SIZE) >=
            static_cast<size_t>(CPL_PATH_BUF_SIZE) ||
        CPLStrlcat(pszStaticResult, pszBasename, CPL_PATH_BUF_SIZE) >=
            static_cast<size_t>(CPL_PATH_BUF_SIZE) ||
        CPLStrlcat(pszStaticResult, pszAddedExtSep, CPL_PATH_BUF_SIZE) >=
            static_cast<size_t>(CPL_PATH_BUF_SIZE) ||
        CPLStrlcat(pszStaticResult, pszExtension, CPL_PATH_BUF_SIZE) >=
            static_cast<size_t>(CPL_PATH_BUF_SIZE))
    {
        return CPLStaticBufferTooSmall(pszStaticResult);
    }

    return pszStaticResult;
}

/************************************************************************/
/*                          CPLFormCIFilename()                         */
/************************************************************************/

/**
 * Case insensitive file searching, returning full path.
 *
 * This function tries to return the path to a file regardless of
 * whether the file exactly matches the basename, and extension case, or
 * is all upper case, or all lower case.  The path is treated as case
 * sensitive.  This function is equivalent to CPLFormFilename() on
 * case insensitive file systems (like Windows).
 *
 * @param pszPath directory path to the directory containing the file.  This
 * may be relative or absolute, and may have a trailing path separator or
 * not.  May be NULL.
 *
 * @param pszBasename file basename.  May optionally have path and/or
 * extension.  May not be NULL.
 *
 * @param pszExtension file extension, optionally including the period.  May
 * be NULL.
 *
 * @return a fully formed filename in an internal static string.  Do not
 * modify or free the returned string.  The string may be destroyed by the
 * next CPL call.
 */

const char *CPLFormCIFilename(const char *pszPath, const char *pszBasename,
                              const char *pszExtension)

{
    // On case insensitive filesystems, just default to CPLFormFilename().
    if (!VSIIsCaseSensitiveFS(pszPath))
        return CPLFormFilename(pszPath, pszBasename, pszExtension);

    const char *pszAddedExtSep = "";
    size_t nLen = strlen(pszBasename) + 2;

    if (pszExtension != nullptr)
        nLen += strlen(pszExtension);

    char *pszFilename = static_cast<char *>(VSI_MALLOC_VERBOSE(nLen));
    if (pszFilename == nullptr)
        return "";

    if (pszExtension == nullptr)
        pszExtension = "";
    else if (pszExtension[0] != '.' && strlen(pszExtension) > 0)
        pszAddedExtSep = ".";

    snprintf(pszFilename, nLen, "%s%s%s", pszBasename, pszAddedExtSep,
             pszExtension);

    const char *pszFullPath = CPLFormFilename(pszPath, pszFilename, nullptr);
    VSIStatBufL sStatBuf;
    int nStatRet = VSIStatExL(pszFullPath, &sStatBuf, VSI_STAT_EXISTS_FLAG);
    if (nStatRet != 0)
    {
        for (size_t i = 0; pszFilename[i] != '\0'; i++)
        {
            if (islower(pszFilename[i]))
                pszFilename[i] = static_cast<char>(toupper(pszFilename[i]));
        }

        pszFullPath = CPLFormFilename(pszPath, pszFilename, nullptr);
        nStatRet = VSIStatExL(pszFullPath, &sStatBuf, VSI_STAT_EXISTS_FLAG);
    }

    if (nStatRet != 0)
    {
        for (size_t i = 0; pszFilename[i] != '\0'; i++)
        {
            if (isupper(pszFilename[i]))
                pszFilename[i] = static_cast<char>(tolower(pszFilename[i]));
        }

        pszFullPath = CPLFormFilename(pszPath, pszFilename, nullptr);
        nStatRet = VSIStatExL(pszFullPath, &sStatBuf, VSI_STAT_EXISTS_FLAG);
    }

    if (nStatRet != 0)
        pszFullPath = CPLFormFilename(pszPath, pszBasename, pszExtension);

    CPLFree(pszFilename);

    return pszFullPath;
}

/************************************************************************/
/*                     CPLProjectRelativeFilename()                     */
/************************************************************************/

/**
 * Find a file relative to a project file.
 *
 * Given the path to a "project" directory, and a path to a secondary file
 * referenced from that project, build a path to the secondary file
 * that the current application can use.  If the secondary path is already
 * absolute, rather than relative, then it will be returned unaltered.
 *
 * Examples:
 * <pre>
 * CPLProjectRelativeFilename("abc/def", "tmp/abc.gif") == "abc/def/tmp/abc.gif"
 * CPLProjectRelativeFilename("abc/def", "/tmp/abc.gif") == "/tmp/abc.gif"
 * CPLProjectRelativeFilename("/xy", "abc.gif") == "/xy/abc.gif"
 * CPLProjectRelativeFilename("/abc/def", "../abc.gif") == "/abc/def/../abc.gif"
 * CPLProjectRelativeFilename("C:\WIN", "abc.gif") == "C:\WIN\abc.gif"
 * </pre>
 *
 * @param pszProjectDir the directory relative to which the secondary files
 * path should be interpreted.
 * @param pszSecondaryFilename the filename (potentially with path) that
 * is to be interpreted relative to the project directory.
 *
 * @return a composed path to the secondary file.  The returned string is
 * internal and should not be altered, freed, or depending on past the next
 * CPL call.
 */

const char *CPLProjectRelativeFilename(const char *pszProjectDir,
                                       const char *pszSecondaryFilename)

{
    char *pszStaticResult = CPLGetStaticResult();
    if (pszStaticResult == nullptr)
        return CPLStaticBufferTooSmall(pszStaticResult);

    CPLAssert(!(pszProjectDir >= pszStaticResult &&
                pszProjectDir < pszStaticResult + CPL_PATH_BUF_SIZE));
    CPLAssert(!(pszSecondaryFilename >= pszStaticResult &&
                pszSecondaryFilename < pszStaticResult + CPL_PATH_BUF_SIZE));

    if (!CPLIsFilenameRelative(pszSecondaryFilename))
        return pszSecondaryFilename;

    if (pszProjectDir == nullptr || strlen(pszProjectDir) == 0)
        return pszSecondaryFilename;

    if (CPLStrlcpy(pszStaticResult, pszProjectDir, CPL_PATH_BUF_SIZE) >=
        static_cast<size_t>(CPL_PATH_BUF_SIZE))
        return CPLStaticBufferTooSmall(pszStaticResult);

    if (pszProjectDir[strlen(pszProjectDir) - 1] != '/' &&
        pszProjectDir[strlen(pszProjectDir) - 1] != '\\')
    {
        // FIXME: Better to ask the filesystems what it
        // prefers as directory separator?
        const char *pszAddedPathSep = nullptr;
#if defined(WIN32)
        if (RequiresUnixPathSeparator(pszStaticResult))
            pszAddedPathSep = "/";
        else
#endif
        {
            pszAddedPathSep = SEP_STRING;
        }
        if (CPLStrlcat(pszStaticResult, pszAddedPathSep, CPL_PATH_BUF_SIZE) >=
            static_cast<size_t>(CPL_PATH_BUF_SIZE))
            return CPLStaticBufferTooSmall(pszStaticResult);
    }

    if (CPLStrlcat(pszStaticResult, pszSecondaryFilename, CPL_PATH_BUF_SIZE) >=
        static_cast<size_t>(CPL_PATH_BUF_SIZE))
        return CPLStaticBufferTooSmall(pszStaticResult);

    return pszStaticResult;
}

/************************************************************************/
/*                       CPLIsFilenameRelative()                        */
/************************************************************************/

/**
 * Is filename relative or absolute?
 *
 * The test is filesystem convention agnostic.  That is it will test for
 * Unix style and windows style path conventions regardless of the actual
 * system in use.
 *
 * @param pszFilename the filename with path to test.
 *
 * @return TRUE if the filename is relative or FALSE if it is absolute.
 */

int CPLIsFilenameRelative(const char *pszFilename)

{
    if ((pszFilename[0] != '\0' &&
         (STARTS_WITH(pszFilename + 1, ":\\") ||
          STARTS_WITH(pszFilename + 1, ":/") ||
          strstr(pszFilename + 1, "://")  // http://, ftp:// etc....
          )) ||
        STARTS_WITH(pszFilename, "\\\\?\\")  // Windows extended Length Path.
        || pszFilename[0] == '\\' || pszFilename[0] == '/')
        return FALSE;

    return TRUE;
}

/************************************************************************/
/*                       CPLExtractRelativePath()                       */
/************************************************************************/

/**
 * Get relative path from directory to target file.
 *
 * Computes a relative path for pszTarget relative to pszBaseDir.
 * Currently this only works if they share a common base path.  The returned
 * path is normally into the pszTarget string.  It should only be considered
 * valid as long as pszTarget is valid or till the next call to
 * this function, whichever comes first.
 *
 * @param pszBaseDir the name of the directory relative to which the path
 * should be computed.  pszBaseDir may be NULL in which case the original
 * target is returned without relativizing.
 *
 * @param pszTarget the filename to be changed to be relative to pszBaseDir.
 *
 * @param pbGotRelative Pointer to location in which a flag is placed
 * indicating that the returned path is relative to the basename (TRUE) or
 * not (FALSE).  This pointer may be NULL if flag is not desired.
 *
 * @return an adjusted path or the original if it could not be made relative
 * to the pszBaseFile's path.
 **/

const char *CPLExtractRelativePath(const char *pszBaseDir,
                                   const char *pszTarget, int *pbGotRelative)

{
    /* -------------------------------------------------------------------- */
    /*      If we don't have a basedir, then we can't relativize the path.  */
    /* -------------------------------------------------------------------- */
    if (pszBaseDir == nullptr)
    {
        if (pbGotRelative != nullptr)
            *pbGotRelative = FALSE;

        return pszTarget;
    }

    const size_t nBasePathLen = strlen(pszBaseDir);

    /* -------------------------------------------------------------------- */
    /*      One simple case is when the base dir is '.' and the target      */
    /*      filename is relative.                                           */
    /* -------------------------------------------------------------------- */
    if ((nBasePathLen == 0 || EQUAL(pszBaseDir, ".")) &&
        CPLIsFilenameRelative(pszTarget))
    {
        if (pbGotRelative != nullptr)
            *pbGotRelative = TRUE;

        return pszTarget;
    }

    /* -------------------------------------------------------------------- */
    /*      By this point, if we don't have a base path, we can't have a    */
    /*      meaningful common prefix.                                       */
    /* -------------------------------------------------------------------- */
    if (nBasePathLen == 0)
    {
        if (pbGotRelative != nullptr)
            *pbGotRelative = FALSE;

        return pszTarget;
    }

    /* -------------------------------------------------------------------- */
    /*      If we don't have a common path prefix, then we can't get a      */
    /*      relative path.                                                  */
    /* -------------------------------------------------------------------- */
    if (!EQUALN(pszBaseDir, pszTarget, nBasePathLen) ||
        (pszTarget[nBasePathLen] != '\\' && pszTarget[nBasePathLen] != '/'))
    {
        if (pbGotRelative != nullptr)
            *pbGotRelative = FALSE;

        return pszTarget;
    }

    /* -------------------------------------------------------------------- */
    /*      We have a relative path.  Strip it off to get a string to       */
    /*      return.                                                         */
    /* -------------------------------------------------------------------- */
    if (pbGotRelative != nullptr)
        *pbGotRelative = TRUE;

    return pszTarget + nBasePathLen + 1;
}

/************************************************************************/
/*                            CPLCleanTrailingSlash()                   */
/************************************************************************/

/**
 * Remove trailing forward/backward slash from the path for UNIX/Windows resp.
 *
 * Returns a string containing the portion of the passed path string with
 * trailing slash removed. If there is no path in the passed filename
 * an empty string will be returned (not NULL).
 *
 * <pre>
 * CPLCleanTrailingSlash( "abc/def/" ) == "abc/def"
 * CPLCleanTrailingSlash( "abc/def" ) == "abc/def"
 * CPLCleanTrailingSlash( "c:\\abc\\def\\" ) == "c:\\abc\\def"
 * CPLCleanTrailingSlash( "c:\\abc\\def" ) == "c:\\abc\\def"
 * CPLCleanTrailingSlash( "abc" ) == "abc"
 * </pre>
 *
 * @param pszPath the path to be cleaned up
 *
 * @return Path in an internal string which must not be freed.  The string
 * may be destroyed by the next CPL filename handling call.
 */

const char *CPLCleanTrailingSlash(const char *pszPath)

{
    char *pszStaticResult = CPLGetStaticResult();
    if (pszStaticResult == nullptr)
        return CPLStaticBufferTooSmall(pszStaticResult);
    CPLAssert(!(pszPath >= pszStaticResult &&
                pszPath < pszStaticResult + CPL_PATH_BUF_SIZE));

    const size_t iPathLength = strlen(pszPath);
    if (iPathLength >= static_cast<size_t>(CPL_PATH_BUF_SIZE))
        return CPLStaticBufferTooSmall(pszStaticResult);

    CPLStrlcpy(pszStaticResult, pszPath, iPathLength + 1);

    if (iPathLength > 0 && (pszStaticResult[iPathLength - 1] == '\\' ||
                            pszStaticResult[iPathLength - 1] == '/'))
        pszStaticResult[iPathLength - 1] = '\0';

    return pszStaticResult;
}

/************************************************************************/
/*                       CPLCorrespondingPaths()                        */
/************************************************************************/

/**
 * Identify corresponding paths.
 *
 * Given a prototype old and new filename this function will attempt
 * to determine corresponding names for a set of other old filenames that
 * will rename them in a similar manner.  This correspondence assumes there
 * are two possibly kinds of renaming going on.  A change of path, and a
 * change of filename stem.
 *
 * If a consistent renaming cannot be established for all the files this
 * function will return indicating an error.
 *
 * The returned file list becomes owned by the caller and should be destroyed
 * with CSLDestroy().
 *
 * @param pszOldFilename path to old prototype file.
 * @param pszNewFilename path to new prototype file.
 * @param papszFileList list of other files associated with pszOldFilename to
 * rename similarly.
 *
 * @return a list of files corresponding to papszFileList but renamed to
 * correspond to pszNewFilename.
 */

char **CPLCorrespondingPaths(const char *pszOldFilename,
                             const char *pszNewFilename, char **papszFileList)

{
    if (CSLCount(papszFileList) == 0)
        return nullptr;

    /* -------------------------------------------------------------------- */
    /*      There is a special case for a one item list which exactly       */
    /*      matches the old name, to rename to the new name.                */
    /* -------------------------------------------------------------------- */
    if (CSLCount(papszFileList) == 1 &&
        strcmp(pszOldFilename, papszFileList[0]) == 0)
    {
        return CSLAddString(nullptr, pszNewFilename);
    }

    const CPLString osOldPath = CPLGetPath(pszOldFilename);
    const CPLString osOldBasename = CPLGetBasename(pszOldFilename);
    const CPLString osNewBasename = CPLGetBasename(pszNewFilename);

    /* -------------------------------------------------------------------- */
    /*      If the basename is changing, verify that all source files       */
    /*      have the same starting basename.                                */
    /* -------------------------------------------------------------------- */
    if (osOldBasename != osNewBasename)
    {
        for (int i = 0; papszFileList[i] != nullptr; i++)
        {
            if (osOldBasename == CPLGetBasename(papszFileList[i]))
                continue;

            const CPLString osFilePath = CPLGetPath(papszFileList[i]);
            const CPLString osFileName = CPLGetFilename(papszFileList[i]);

            if (!EQUALN(osFileName, osOldBasename, osOldBasename.size()) ||
                !EQUAL(osFilePath, osOldPath) ||
                osFileName[osOldBasename.size()] != '.')
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Unable to rename fileset due irregular basenames.");
                return nullptr;
            }
        }
    }

    /* -------------------------------------------------------------------- */
    /*      If the filename portions differs, ensure they only differ in    */
    /*      basename.                                                       */
    /* -------------------------------------------------------------------- */
    if (osOldBasename != osNewBasename)
    {
        const CPLString osOldExtra =
            CPLGetFilename(pszOldFilename) + osOldBasename.size();
        const CPLString osNewExtra =
            CPLGetFilename(pszNewFilename) + osNewBasename.size();

        if (osOldExtra != osNewExtra)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Unable to rename fileset due to irregular filename "
                     "correspondence.");
            return nullptr;
        }
    }

    /* -------------------------------------------------------------------- */
    /*      Generate the new filenames.                                     */
    /* -------------------------------------------------------------------- */
    char **papszNewList = nullptr;
    const CPLString osNewPath = CPLGetPath(pszNewFilename);

    for (int i = 0; papszFileList[i] != nullptr; i++)
    {
        const CPLString osOldFilename = CPLGetFilename(papszFileList[i]);

        const CPLString osNewFilename =
            osOldBasename == osNewBasename
                ? CPLFormFilename(osNewPath, osOldFilename, nullptr)
                : CPLFormFilename(osNewPath, osNewBasename,
                                  osOldFilename.c_str() + osOldBasename.size());

        papszNewList = CSLAddString(papszNewList, osNewFilename);
    }

    return papszNewList;
}

/************************************************************************/
/*                      CPLGenerateTempFilename()                       */
/************************************************************************/

/**
 * Generate temporary file name.
 *
 * Returns a filename that may be used for a temporary file.  The location
 * of the file tries to follow operating system semantics but may be
 * forced via the CPL_TMPDIR configuration option.
 *
 * @param pszStem if non-NULL this will be part of the filename.
 *
 * @return a filename which is valid till the next CPL call in this thread.
 */

const char *CPLGenerateTempFilename(const char *pszStem)

{
    const char *pszDir = CPLGetConfigOption("CPL_TMPDIR", nullptr);

    if (pszDir == nullptr)
        pszDir = CPLGetConfigOption("TMPDIR", nullptr);

    if (pszDir == nullptr)
        pszDir = CPLGetConfigOption("TEMP", nullptr);

    if (pszDir == nullptr)
        pszDir = ".";

    if (pszStem == nullptr)
        pszStem = "";

    static int nTempFileCounter = 0;
    CPLString osFilename;
    osFilename.Printf("%s_%d_%d", pszStem, CPLGetCurrentProcessID(),
                      CPLAtomicInc(&nTempFileCounter));

    return CPLFormFilename(pszDir, osFilename, nullptr);
}

/************************************************************************/
/*                         CPLExpandTilde()                             */
/************************************************************************/

/**
 * Expands ~/ at start of filename.
 *
 * Assumes that the HOME configuration option is defined.
 *
 * @param pszFilename filename potentially starting with ~/
 *
 * @return an expanded filename.
 *
 * @since GDAL 2.2
 */

const char *CPLExpandTilde(const char *pszFilename)

{
    if (!STARTS_WITH_CI(pszFilename, "~/"))
        return pszFilename;

    const char *pszHome = CPLGetConfigOption("HOME", nullptr);
    if (pszHome == nullptr)
        return pszFilename;

    return CPLFormFilename(pszHome, pszFilename + 2, nullptr);
}

/************************************************************************/
/*                         CPLGetHomeDir()                              */
/************************************************************************/

/**
 * Return the path to the home directory
 *
 * That is the value of the USERPROFILE environment variable on Windows,
 * or HOME on other platforms.
 *
 * @return the home directory, or NULL.
 *
 * @since GDAL 2.3
 */

const char *CPLGetHomeDir()

{
#ifdef WIN32
    return CPLGetConfigOption("USERPROFILE", nullptr);
#else
    return CPLGetConfigOption("HOME", nullptr);
#endif
}

/************************************************************************/
/*                        CPLLaunderForFilename()                       */
/************************************************************************/

/**
 * Launder a string to be compatible of a filename.
 *
 * @param pszName The input string to launder.
 * @param pszOutputPath The directory where the file would be created.
 *                      Unused for now. May be NULL.
 * @return the laundered name.
 *
 * @since GDAL 3.1
 */

const char *CPLLaunderForFilename(const char *pszName,
                                  CPL_UNUSED const char *pszOutputPath)
{
    std::string osRet(pszName);
    for (char &ch : osRet)
    {
        // https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file
        if (ch == '<' || ch == '>' || ch == ':' || ch == '"' || ch == '/' ||
            ch == '\\' || ch == '?' || ch == '*')
        {
            ch = '_';
        }
    }
    return CPLSPrintf("%s", osRet.c_str());
}