gnatcoll_25.0.0_d7d84483/core/src/os/gnatcoll-os-fsutil.adb

   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
------------------------------------------------------------------------------
--                              G N A T C O L L                             --
--                                                                          --
--                       Copyright (C) 2023, AdaCore                        --
--                                                                          --
-- This library is free software;  you can redistribute it and/or modify it --
-- under terms of the  GNU General Public License  as published by the Free --
-- Software  Foundation;  either version 3,  or (at your  option) any later --
-- version. This library is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY;  without even the impied warranty of MERCHAN- --
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE.                            --
--                                                                          --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception,   --
-- version 3.1, as published by the Free Software Foundation.               --
--                                                                          --
-- You should have received a copy of the GNU General Public License and    --
-- a copy of the GCC Runtime Library Exception along with this program;     --
-- see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see    --
-- <http://www.gnu.org/licenses/>.                                          --
--                                                                          --
------------------------------------------------------------------------------

with Ada.Exceptions; use Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with Ada.Text_IO;
with GNATCOLL.OS.Stat;      use GNATCOLL.OS.Stat;
with GNATCOLL.OS.Constants;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with GNAT.OS_Lib;
with GNATCOLL.Strings_Impl;
with Ada.Characters.Handling;
with GNATCOLL.OS.Dir;
with Ada.Calendar;
with Ada.Assertions;

package body GNATCOLL.OS.FSUtil is

   type String_Access is access String;
   procedure Free is new Ada.Unchecked_Deallocation (String, String_Access);

   Sync_Trees_Exception : exception;

   function Copy_File_Content
     (Src : UTF8.UTF_8_String; Dst : UTF8.UTF_8_String) return Boolean;
   --  Copy file content. Return True on success.
   --  Raises a CONSTRAINT_ERROR exception if the source file
   --  length can not be contained in a SInt_64.

   procedure Sync_Trees_Internal
     (Src          : UTF8.UTF_8_String;
      Dst          : UTF8.UTF_8_String;
      Mode         : Sync_Trees_Mode;
      Symlink_Mode : Sync_Trees_Symlink_Mode := SKIP_SYMLINKS);
   --  Internal sync function doing all the work.
   --  This is not done directly in Sync_Trees so exceptions can be handled.

   procedure Set_SHA1_Initial_State (S : in out GNAT.SHA1.Context);
   --  Initialize a SHA1 context.

   procedure Set_SHA256_Initial_State (S : in out GNAT.SHA256.Context);
   --  Initialize a SHA256 context.

   -------------
   -- Process --
   -------------

   function Process
      (Path        : UTF8.UTF_8_String;
       Buffer_Size : Positive := FS.Default_Buffer_Size)
      return Result_Type
   is
      FD      : FS.File_Descriptor;
      Context : State_Type;
      N       : Integer;
      Buffer  : String_Access;

      use all type FS.File_Descriptor;
   begin
      Set_Initial_State (Context);
      FD := FS.Open (Path => Path, Advise_Sequential => True);

      if FD = FS.Invalid_FD then
         raise OS_Error with "Failed to open " & String (Path);
      end if;

      Buffer := new String (1 .. Buffer_Size);

      begin
         loop
            N := FS.Read (FD, Buffer.all);
            exit when N = 0;
            Update (Context, Buffer (1 .. N));
         end loop;
      exception
         when others =>
            FS.Close (FD);
            Free (Buffer);
            raise;
      end;

      FS.Close (FD);
      Free (Buffer);
      return Result (Context);
   end Process;

   -------------------
   -- Internal_SHA1 --
   -------------------

   function Internal_SHA1 is new Process
      (GNAT.SHA1.Context,
       SHA1_Digest,
       Set_SHA1_Initial_State, GNAT.SHA1.Update, GNAT.SHA1.Digest);

   ---------------------
   -- Internal_SHA256 --
   ---------------------

   function Internal_SHA256 is new Process
      (GNAT.SHA256.Context,
       SHA256_Digest,
       Set_SHA256_Initial_State, GNAT.SHA256.Update, GNAT.SHA256.Digest);

   ----------
   -- SHA1 --
   ----------
   function SHA1
      (Path        : UTF8.UTF_8_String;
       Buffer_Size : Positive := FS.Default_Buffer_Size)
      return SHA1_Digest renames Internal_SHA1;

   ------------
   -- SHA256 --
   ------------

   function SHA256
      (Path        : UTF8.UTF_8_String;
       Buffer_Size : Positive := FS.Default_Buffer_Size)
      return SHA256_Digest renames Internal_SHA256;

   -----------------
   -- Remove_File --
   -----------------

   function Remove_File (Path : UTF8.UTF_8_String) return Boolean is separate;

   ------------------
   -- Copy_Content --
   ------------------

   function Copy_File_Content
     (Src : UTF8.UTF_8_String; Dst : UTF8.UTF_8_String)
      return Boolean is separate;

   ---------------
   -- Copy_File --
   ---------------

   function Copy_File
     (Src                  : UTF8.UTF_8_String; Dst : UTF8.UTF_8_String;
      Preserve_Timestamps  : Boolean := False;
      Preserve_Permissions : Boolean := False) return Boolean
   is
      Src_File_Attr : File_Attributes;

   begin
      Src_File_Attr := GNATCOLL.OS.Stat.Stat (Src);
      if not Exists (Src_File_Attr) or else not Is_File (Src_File_Attr) then
         --  File does not exist, or is not a regular file.
         return False;
      end if;

      if not Copy_File_Content (Src, Dst) then
         return False;
      end if;

      if Preserve_Permissions then
         if not Copy_Permissions (Src, Dst) then
            return False;
         end if;
      end if;

      if Preserve_Timestamps then
         if not Copy_Timestamps (Src, Dst) then
            return False;
         end if;
      end if;

      return True;
   end Copy_File;

   ---------------------
   -- Copy_Timestamps --
   ---------------------

   function Copy_Timestamps
     (Src : UTF8.UTF_8_String; Dst : UTF8.UTF_8_String)
      return Boolean is separate;

   ----------------------
   -- Copy_Permissions --
   ----------------------

   function Copy_Permissions
     (Src : UTF8.UTF_8_String; Dst : UTF8.UTF_8_String)
      return Boolean is separate;

   ----------------------
   -- Create_Directory --
   ----------------------

   function Create_Directory
     (Path : UTF8.UTF_8_String) return Boolean is separate;

   --------------------------
   -- Create_Symbolic_Link --
   --------------------------

   function Create_Symbolic_Link
     (Link_Path : UTF8.UTF_8_String; Target_Path : UTF8.UTF_8_String)
      return Boolean is separate;

   ----------------------
   -- Remove_Directory --
   ----------------------

   function Remove_Directory
     (Path : UTF8.UTF_8_String) return Boolean is separate;

   ------------------------
   -- Read_Symbolic_Link --
   ------------------------

   function Read_Symbolic_Link
     (Link_Path : UTF8.UTF_8_String; Target_Path : out Unbounded_String)
      return Boolean is separate;

   ----------------------------
   -- Set_SHA1_Initial_State --
   ----------------------------

   procedure Set_SHA1_Initial_State (S : in out GNAT.SHA1.Context) is
   begin
      S := GNAT.SHA1.Initial_Context;
   end Set_SHA1_Initial_State;

   ----------------------------
   -- Set_SHA256_Initial_State --
   ----------------------------

   procedure Set_SHA256_Initial_State (S : in out GNAT.SHA256.Context) is
   begin
      S := GNAT.SHA256.Initial_Context;
   end Set_SHA256_Initial_State;

   -------------------------------
   -- Symbolic_Link_Is_Internal --
   -------------------------------

   function Symbolic_Link_Is_Internal
     (Top_Dir_Path : UTF8.UTF_8_String; Link_Path : UTF8.UTF_8_String)
      return Boolean
   is
      Target_Path : Unbounded_String;

   begin

      if not Read_Symbolic_Link (Link_Path, Target_Path) then
         return False;
      end if;

      if GNAT.OS_Lib.Is_Absolute_Path (To_String (Target_Path)) then
         return False;
      end if;

      --  Concatenate Link_Path and Target_Path split by split, and see if
      --  it goes outside Top_Dir.

      --  Example top dir: /tmp/dir and target_path: dir1/../../dir/fileA
      --  In order:
      --  - /tmp/dir/dir1: OK
      --  - /tmp/dir/dir1/..: OK
      --  - /tmp/dir/dir1/../..: KO!

      declare
         use Ada.Characters.Handling;
         package Strings is new GNATCOLL.Strings_Impl.Strings
           (GNATCOLL.Strings_Impl.Optimal_String_Size, Character, String);
         use Strings;

         package Constants renames GNATCOLL.OS.Constants;

         function Normalize_Link_Pathname (Link_Path : String) return String;
         --  Obtain link normalized pathname without resolving the link itself

         function Normalize_Link_Pathname (Link_Path : String) return String is
            Normalized_Link_Path : constant String :=
              GNAT.OS_Lib.Normalize_Pathname
                (Link_Path, Resolve_Links => False);
            X                    : Strings.XString;
         begin
            X.Set (Normalized_Link_Path);

            declare
               X_Arr : constant Strings.XString_Array :=
                 X.Right_Split
                   (Sep        => Constants.Dir_Sep, Max_Split => 2,
                    Omit_Empty => True);
               --  Extract symbolic link basename, and base path
            begin

               if X_Arr'Length = 1 then

                  --  Can occur if the link is at the top of a file system.

                  return Constants.Dir_Sep & X_Arr (1).To_String;
               else

                  --  Resolve symbolic links if needed, and normalize path
                  --  to final link directory.

                  return
                    GNAT.OS_Lib.Normalize_Pathname (X_Arr (2).To_String) &
                    Constants.Dir_Sep & X_Arr (1).To_String;
               end if;
            end;
         end Normalize_Link_Pathname;

         Normalized_Top_Dir   : constant String :=
           GNAT.OS_Lib.Normalize_Pathname (Top_Dir_Path);
         Normalized_Link_Path : constant String :=
           Normalize_Link_Pathname (Link_Path);
         Link_Depth           : Integer         := 0;
         XS                   : Strings.XString;
      begin

         --  Check if the link is outside the top directory
         --  First case: Normalized link path is simply shorter than
         --  the top directory one.
         --  Second case: Normalized top directory path is not contained in
         --  normalized link path.

         if Normalized_Link_Path'Length < Normalized_Top_Dir'Length
           or else
             Normalized_Link_Path
               (Normalized_Link_Path'First ..
                    Normalized_Link_Path'First + Normalized_Top_Dir'Length -
                    1) /=
             Normalized_Top_Dir
         then
            return False;
         end if;

         --  Compute the link depth in the top directory

         XS.Set
           (Normalized_Link_Path
              (Normalized_Top_Dir'Last + 1 .. Normalized_Link_Path'Last));

         Link_Depth := 0;

         declare
            First_Item : Boolean := True;
         begin
            for Dir_Entry of XS.Split
              (GNATCOLL.OS.Constants.Dir_Sep, Omit_Empty => True)
            loop
               if First_Item then
                  First_Item := False;

                  --  The last XS.Split element is the link itself.
                  --  It shall not count in depth.

               else
                  Link_Depth := Link_Depth + 1;
               end if;
            end loop;
         end;

         --  Then, concatenate each subpart of the target path relative to the
         --  link, and see if depth becomes negative once. In this case, the
         --  target link went outside of the directory.

         XS.Set (To_String (Target_Path));
         for Dir_Entry of XS.Split
           (GNATCOLL.OS.Constants.Dir_Sep, Omit_Empty => True)
         loop
            if Dir_Entry = ".." then
               Link_Depth := Link_Depth - 1;
            elsif Dir_Entry /= "." then
               Link_Depth := Link_Depth + 1;
            end if;

            if Link_Depth < 0 then
               return False;
            end if;
         end loop;
      end;

      return True;
   end Symbolic_Link_Is_Internal;

   ------------------------
   -- Copy_Symbolic_Link --
   ------------------------

   function Copy_Symbolic_Link
     (Src_Path : UTF8.UTF_8_String; Dst_Path : UTF8.UTF_8_String)
      return Boolean
   is
      Target_Path : Unbounded_String;
   begin

      if not Read_Symbolic_Link (Src_Path, Target_Path) then
         return False;
      end if;

      return Create_Symbolic_Link
               (Link_Path   => Dst_Path,
                Target_Path => To_String (Target_Path));
   end Copy_Symbolic_Link;


   ----------------
   -- Sync_Trees --
   ----------------

   function Sync_Trees
     (Src          : UTF8.UTF_8_String;
      Dst          : UTF8.UTF_8_String;
      Mode         : Sync_Trees_Mode;
      Symlink_Mode : Sync_Trees_Symlink_Mode := SKIP_SYMLINKS)
      return Boolean
   is
   begin
      Sync_Trees_Internal (Src, Dst, Mode, Symlink_Mode);

      --  No exception detected

      return True;
   exception
      when E : Sync_Trees_Exception =>
         Ada.Text_IO.Put_Line
           ("Sync_Trees from " & Src & " to " & Dst & " failed:");
         Ada.Text_IO.Put_Line (Exception_Message (E));
         return False;
   end Sync_Trees;

   -------------------------
   -- Sync_Trees_Internal --
   -------------------------

   procedure Sync_Trees_Internal
     (Src          : UTF8.UTF_8_String;
      Dst          : UTF8.UTF_8_String;
      Mode         : Sync_Trees_Mode;
      Symlink_Mode : Sync_Trees_Symlink_Mode := SKIP_SYMLINKS)
   is

      use GNATCOLL.OS.Dir;
      use Ada.Calendar;

      Absolute_Src : Unbounded_String;
      Absolute_Dst : Unbounded_String;

      function Dir_Absolute_Path
        (Path : UTF8.UTF_8_String) return UTF8.UTF_8_String;
      --  Return directory absolute path.

      procedure Clean_Dst;
      --  Remove files which are in the destination tree, but not in the source
      --  one. Checks only for names, no matter the type of the file.

      procedure Sync_Trees_Src_To_Dst;
      --  Copy source tree content to the destination one

      function Dir_Absolute_Path
        (Path : UTF8.UTF_8_String) return UTF8.UTF_8_String
      is
         DH : Dir_Handle                 := GNATCOLL.OS.Dir.Open (Path);
         P  : constant UTF8.UTF_8_String := GNATCOLL.OS.Dir.Path (DH);
      begin
         Close (DH);
         return P;
      end Dir_Absolute_Path;

      procedure Clean_Dst is

         function Get_Src_Path
           (H : Dir_Handle; Element : Dir_Entry) return UTF8.UTF_8_String;
         --  Return directory entry path based on Sync_Trees source
         --  base directory.

         function Get_Src_Path
           (H : Dir_Handle; Element : Dir_Entry) return UTF8.UTF_8_String
         is
            Dir_Entry_Path : constant UTF8.UTF_8_String := Path (H, Element);

            --  Take the part of complete dir entry path which is not in
            --  the Sync_Trees top source path => the right part of the path,
            --  and concatenate it with the Sync_Trees top destination path.

            Result : constant UTF8.UTF_8_String :=
              To_String (Absolute_Src) &
              Dir_Entry_Path
                (To_String (Absolute_Dst)'Last + 1 .. Dir_Entry_Path'Last);
         begin
            return Result;
         end Get_Src_Path;

         function Handle_Dir
           (H : Dir_Handle; Element : Dir_Entry) return Boolean;

         function Handle_Dir
           (H : Dir_Handle; Element : Dir_Entry) return Boolean
         is
            Src_Path : constant UTF8.UTF_8_String := Get_Src_Path (H, Element);
            Dst_Path : constant UTF8.UTF_8_String := Path (H, Element);
            Src_FA   : constant Stat.File_Attributes :=
              Stat.Stat (Src_Path, Follow_Symlinks => False);
         begin

            --  If directory does not exist in the source path,
            --  then delete it in the destination path.

            if not Stat.Exists (Src_FA) then
               if not Remove_Directory (Dst_Path) then
                  raise Sync_Trees_Exception
                    with "Failed to remove the directory " & Dst_Path;
               end if;
            end if;
            return True;
         end Handle_Dir;

         procedure Handle_File (H : Dir_Handle; Element : Dir_Entry);

         procedure Handle_File (H : Dir_Handle; Element : Dir_Entry) is
            Src_Path : constant UTF8.UTF_8_String := Get_Src_Path (H, Element);
            Dst_Path : constant UTF8.UTF_8_String := Path (H, Element);
            Src_FA   : constant Stat.File_Attributes :=
              Stat.Stat (Src_Path, Follow_Symlinks => False);
         begin

            --  If file does not exist in the source path, then delete it from
            --  destination path.

            if not Stat.Exists (Src_FA) then
               if not Remove_File (Dst_Path) then
                  raise Sync_Trees_Exception
                    with "Failed to remove the file " & Dst_Path;
               end if;
            end if;
         end Handle_File;

      begin

         --  Do not follow symlinks, as we do not want to check the symbolic
         --  link targets.

         Walk
           (Path                 => Dst,
            File_Handler         => Handle_File'Unrestricted_Access,
            Dir_Handler          => Handle_Dir'Unrestricted_Access,
            Follow_Symlinks      => False,
            Propagate_Exceptions => True);
      end Clean_Dst;

      procedure Sync_Trees_Src_To_Dst is

         function Equals
           (First_Path  : UTF8.UTF_8_String;
            First_FA    : Stat.File_Attributes;
            Second_Path : UTF8.UTF_8_String;
            Second_FA   : Stat.File_Attributes)
            return Boolean;
         --  Compare two files or directories. Checksum comparison mode can be
         --  used only for regular files. Timestamps and length comparison
         --  is applied otherwise.
         --
         --  Return true if entities are equals.

         procedure Handle_File (H : Dir_Handle; Element : Dir_Entry);
         --  Ensure that the file currently handled is also present in the
         --  destination directory.

         function Handle_Dir
           (H : Dir_Handle; Element : Dir_Entry) return Boolean;
         --  Ensure that the directory currently handled is also present in
         --  the destination directory. The content directory is not processed,
         --  as it is processed by the Walk's call of Sync_Trees_Src_To_Dst.

         function Get_Dst_Path
           (H : Dir_Handle; Element : Dir_Entry) return UTF8.UTF_8_String;
         --  Return directory entry path based on Sync_Trees destination
         --  base directory.

         procedure Remove_If_Exists (Path : UTF8.UTF_8_String);
         --  Remove file or directory if it exists.
         --  Raise Sync_Trees_Exception on error.

         procedure Process_Symbolic_Link
           (Src_Path  :     UTF8.UTF_8_String; Dst_Path : UTF8.UTF_8_String;
            Processed : out Boolean);
         --   Copy symbolic link if the symlink mode and the symbolic link
         --   target location (internal / external) allows it.
         --   A symbolic link can be processed whithout being copied,
         --   this is for example the case if the link target is an absolute
         --   path and if symlink mode is set to copy_safe_symlinks.
         --   - The Processed boolean indicates if symbolic link has been
         --     processed. A False value means that the symbolic link target
         --     shall be processed instead of the symbolic link itself.
         --
         --   Raise Sync_Trees_Exception on error.

         function Equals
           (First_Path  : UTF8.UTF_8_String; First_FA : Stat.File_Attributes;
            Second_Path : UTF8.UTF_8_String; Second_FA : Stat.File_Attributes)
            return Boolean
         is
         begin
            if Stat.Length (First_FA) /= Stat.Length (Second_FA) then
               return False;
            end if;

            --  Checksum verification is viable only for files

            if Mode = CHECKSUM and Stat.Is_File (First_FA) and
              Stat.Is_File (Second_FA)
            then
               return SHA1 (First_Path) = SHA1 (Second_Path);
            end if;

            --  ??? Add permission checking

            return
              Stat.Modification_Time (First_FA) =
              Stat.Modification_Time (Second_FA);
         end Equals;

         function Get_Dst_Path
           (H : Dir_Handle; Element : Dir_Entry) return UTF8.UTF_8_String
         is
            Dir_Entry_Path : constant UTF8.UTF_8_String := Path (H, Element);

            Result : constant UTF8.UTF_8_String :=
              To_String (Absolute_Dst) &
              Dir_Entry_Path
                (To_String (Absolute_Src)'Last + 1 .. Dir_Entry_Path'Last);

            --  Take the part of complete dir entry path which is not in
            --  the Sync_Trees top source path => the right part of the path,
            --  and concatenate it with the Sync_Trees top destination path.

         begin
            return Result;
         end Get_Dst_Path;

         procedure Remove_If_Exists (Path : UTF8.UTF_8_String) is
            FA : constant Stat.File_Attributes :=
              Stat.Stat (Path, Follow_Symlinks => False);
         begin
            if Stat.Exists (FA) then
               if Stat.Is_Directory (FA) then
                  if not Remove_Directory (Path) then
                     raise Sync_Trees_Exception
                       with "Failed to remove the directory " & Path;
                  end if;
               else
                  if not Remove_File (Path) then
                     raise Sync_Trees_Exception
                       with "Failed to remove the file " & Path;
                  end if;
               end if;
            end if;
         end Remove_If_Exists;

         procedure Process_Symbolic_Link
           (Src_Path  : UTF8.UTF_8_String;
            Dst_Path  : UTF8.UTF_8_String;
            Processed : out Boolean)
         is
         begin
            case Symlink_Mode is
               when SKIP_SYMLINKS =>
                  Processed := True;

                  --  Do not process symlink at all. Destination directory
                  --  shall not have any symlink after cleaning. As cleaning
                  --  is done only based on name, we need to clean this link
                  --  manually.

                  Remove_If_Exists (Dst_Path);
               when COPY_SYMLINKS =>
                  Processed := True;

                  --  Copy symlink without target path modification

                  Remove_If_Exists (Dst_Path);

                  if not Copy_Symbolic_Link (Src_Path, Dst_Path) then
                     raise Sync_Trees_Exception with
                       "Failed to copy symbolic link from "
                       & Src_Path & " to " & Dst_Path;
                  end if;
               when COPY_SAFE_SYMLINKS =>
                  Processed := True;

                  --  If the link is external, then dst directory shall not
                  --  contain entity of the same name. If the link is internal,
                  --  then it is copied to dst.

                  Remove_If_Exists (Dst_Path);

                  if Symbolic_Link_Is_Internal
                       (Top_Dir_Path => To_String (Absolute_Src),
                        Link_Path    => Src_Path)
                  then
                     if not Copy_Symbolic_Link (Src_Path, Dst_Path) then
                        raise Sync_Trees_Exception with
                          "Failed to copy symbolic link from "
                          & Src_Path & " to " & Dst_Path;
                     end if;
                  end if;
               when COPY_UNSAFE_SYMLINKS =>

                  --  Only internal symbolic links should be processed
                  --  as symlinks. External symbolic links have
                  --  their target copied instead.

                  if Symbolic_Link_Is_Internal
                       (Top_Dir_Path => To_String (Absolute_Src),
                        Link_Path    => Src_Path)
                  then
                     Processed := True;

                     Remove_If_Exists (Dst_Path);
                     if not (Copy_Symbolic_Link (Src_Path, Dst_Path))
                     then
                        raise Sync_Trees_Exception with
                          "Failed to copy symbolic link from "
                          & Src_Path & " to " & Dst_Path;
                     end if;
                  else
                     Processed := False;
                  end if;
               when COPY_SYMLINKS_TARGET =>

                  --  Copy symlinks target instead of the symlink itself.
                  --  Should be recursive for symbolic link targeting a
                  --  directory.

                  Processed := False;
            end case;
         end Process_Symbolic_Link;

         function Handle_Dir
           (H : Dir_Handle; Element : Dir_Entry) return Boolean
         is
            Src_Path : constant UTF8.UTF_8_String := Path (H, Element);
            Dst_Path : constant UTF8.UTF_8_String := Get_Dst_Path (H, Element);
            Src_FA   : constant Stat.File_Attributes := Attributes (Element);

         begin
            declare
               Processed : Boolean;
               Src_LFA   : constant Stat.File_Attributes :=
                 Stat.Stat (Src_Path, Follow_Symlinks => False);
            begin
               if Stat.Is_Symbolic_Link (Src_LFA) then
                  Process_Symbolic_Link (Src_Path, Dst_Path, Processed);

                  if Processed then

                     --  Symbolic link has been processed. We do not browse
                     --  symbolic link, as either the link target is
                     --  internal and the target will be browsed with Walk,
                     --  or the link is external and it shall not be
                     --  processed at all.

                     return False;
                  end if;

                  --  In this case, symbolic link has not been processed,
                  --  and its target shall be processed instead.

               end if;
            end;

            --  At this stage of the code, source either is not a
            --  symbolic link or shall be processed as a regular directory.

            declare

               Dst_LFA : constant Stat.File_Attributes :=
                 Stat.Stat (Dst_Path, Follow_Symlinks => False);
            begin

               --  In contrary to Handle_File, a symbolic link target can not
               --  be invalid here. A symbolic link is seen as a directory only
               --  if the target is a directory. If not, a file is detected
               --  instead, so we would go through the Handle_File handler.

               if Stat.Is_Directory (Dst_LFA) then

                  --  If destination directory already exists, compare src
                  --  and dst to check if timestamp and permission copy
                  --  is required.

                  if not Equals (Src_Path, Src_FA, Dst_Path, Dst_LFA) then
                     if not Copy_Timestamps (Src_Path, Dst_Path) then
                        raise Sync_Trees_Exception with
                          "Failed to copy timestamp from directory " & Src_Path
                          & " to directory " & Dst_Path;
                     end if;
                  end if;
               else

                  --  If the destination already exists as a regular file,
                  --  the latter must be deleted, and replaced by the
                  --  directory.

                  if Stat.Exists (Dst_LFA) then

                     --  Remove symbolic link or regular file if it exists

                     if not Remove_File (Dst_Path) then
                        raise Sync_Trees_Exception with
                          "Failed to remove file " & Dst_Path;
                     end if;
                  end if;

                  if not Create_Directory (Dst_Path) then
                     raise Sync_Trees_Exception with
                          "Failed to create directory " & Dst_Path;
                  end if;

                  if not Copy_Timestamps (Src_Path, Dst_Path) then
                     raise Sync_Trees_Exception with
                          "Failed to copy timestamps from " & Src_Path & " to "
                          & Dst_Path;
                  end if;
               end if;
            end;

            return True;
         end Handle_Dir;

         procedure Handle_File (H : Dir_Handle; Element : Dir_Entry) is
            Src_Path : constant UTF8.UTF_8_String := Path (H, Element);
            Dst_Path : constant UTF8.UTF_8_String := Get_Dst_Path (H, Element);
            Src_FA   : constant Stat.File_Attributes := Attributes (Element);

         begin
            declare
               Src_LFA   : constant Stat.File_Attributes :=
                 Stat.Stat (Src_Path, Follow_Symlinks => False);
               Processed : Boolean;
            begin
               if Stat.Is_Symbolic_Link (Src_LFA) then
                  Process_Symbolic_Link (Src_Path, Dst_Path, Processed);

                  if Processed then
                     return;
                  end if;

                  --  In this case, symbolic link has not been processed,
                  --  and its target shall be processed instead.

               end if;
            end;

            --  At this stage of the code, source either is either not a
            --  symbolic link or its target should be processed instead.

            declare
               Dst_LFA : constant Stat.File_Attributes :=
                 Stat.Stat (Dst_Path, Follow_Symlinks => False);
            begin

               if not Stat.Exists (Src_FA) then

                  --  Can happen if a symbolic link has an invalid target

                  Ada.Assertions.Assert
                    (Symlink_Mode = COPY_UNSAFE_SYMLINKS or else
                     Symlink_Mode = COPY_SYMLINKS_TARGET);

                  --  Having an invalid target is not compatible with the
                  --  Sync_Trees modes COPY_UNSAFE_SYMLINKS and
                  --  COPY_SYMLINKS_TARGET, as the symbolic link's target needs
                  --  to be copied instead of the symbolic link."

                  raise Sync_Trees_Exception with
                    "Symbolic link " & Src_Path & " has an invalid target.";

               elsif Stat.Is_File (Dst_LFA) then
                  if not Equals (Src_Path, Src_FA, Dst_Path, Dst_LFA) then
                     if not Copy_File
                         (Src_Path, Dst_Path, Preserve_Timestamps => True,
                          Preserve_Permissions => False)
                     then
                        raise Sync_Trees_Exception
                          with "Failed to copy file from " & Src_Path
                            & " to " & Dst_Path;
                     end if;
                  end if;
               else
                  --  Remove dst symbolic link or directory if it exists

                  if Stat.Is_Directory (Dst_LFA) then
                     if not Remove_Directory (Dst_Path) then
                        raise Sync_Trees_Exception
                          with "Failed to remove the directory " & Dst_Path;
                     end if;
                  elsif Stat.Is_Symbolic_Link (Dst_LFA) then
                     if not Remove_File (Dst_Path) then
                        raise Sync_Trees_Exception
                          with "Failed to remove the file " & Dst_Path;
                     end if;
                  end if;

                  if not Copy_File
                      (Src_Path, Dst_Path, Preserve_Timestamps => True,
                       Preserve_Permissions => False)
                  then
                     raise Sync_Trees_Exception
                          with "Failed to copy the file " & Src_Path
                          & " to " & Dst_Path;
                  end if;
               end if;
            end;
         end Handle_File;

      begin

         --  We must follow symlinks. If a link targets a directory which
         --  should be copied because of the specified Sync_Trees symlink mode,
         --  then targeted directory must be also browsed by Walk. It could
         --  be done with Follow_Symlinks set to False with new call to Walk,
         --  but we would lose the initial Max_Depth Walk property, which
         --  prevents symlinks loops.

         Walk
           (Path                 => Src,
            File_Handler         => Handle_File'Unrestricted_Access,
            Dir_Handler          => Handle_Dir'Unrestricted_Access,
            Follow_Symlinks      => True,
            Propagate_Exceptions => True);
      end Sync_Trees_Src_To_Dst;

   begin
      declare
         Src_FA : constant File_Attributes :=
            Stat.Stat (Path => Src, Follow_Symlinks => True);
         Dst_FA : constant File_Attributes :=
                    Stat.Stat (Path => Dst, Follow_Symlinks => True);
      begin
         if not Stat.Exists (Src_FA) then
            raise Sync_Trees_Exception with
              "Source " & Src & " does not exist";
         elsif not Stat.Is_Directory (Src_FA) then
            raise Sync_Trees_Exception with
              "Source" & Src & " should be a directory";
         end if;

         if not Stat.Exists (Dst_FA) then
            declare

               --  Check that dst is not a symbolic link whose target does not
               --  exist.

               Dst_LFA : constant File_Attributes :=
                 Stat.Stat (Path => Dst, Follow_Symlinks => False);
            begin
               if Stat.Exists (Dst_LFA) and then
                  Stat.Is_Symbolic_Link (Dst_LFA)
               then
                  raise Sync_Trees_Exception with
                    Dst & " is an invalid symbolic link. Aborting the sync";
               end if;
            end;

            if not Create_Directory (Dst) then
               raise Sync_Trees_Exception with
                 "Failed to create the destination "
                 & "directory " & Dst;
            end if;
         elsif Stat.Is_File (Dst_FA) then
            raise Sync_Trees_Exception with
              Dst & " is a regular file. Only syncs between directories are "
              & "supported";
         end if;
      end;

      Absolute_Src := To_Unbounded_String (Dir_Absolute_Path (Src));
      Absolute_Dst := To_Unbounded_String (Dir_Absolute_Path (Dst));

      --  Remove file which are only in the destination tree.
      --  This is done before the synchronization, as the latter will
      --  do nothing in the best case, and will add new files otherwise.
      --  As cleaning implies tree browsing, it is better to do it on as few
      --  files as possible.

      Clean_Dst;

      --  Copy files from source to dest

      Sync_Trees_Src_To_Dst;
   end Sync_Trees_Internal;

end GNATCOLL.OS.FSUtil;