OSDN Git Service

2006-10-31 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / g-dirope.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --            G N A T . D I R E C T O R Y _ O P E R A T I O N S             --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --                     Copyright (C) 1998-2006, AdaCore                     --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT;  see file COPYING.  If not, write --
19 -- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
20 -- Boston, MA 02110-1301, USA.                                              --
21 --                                                                          --
22 -- As a special exception,  if other files  instantiate  generics from this --
23 -- unit, or you link  this unit with other files  to produce an executable, --
24 -- this  unit  does not  by itself cause  the resulting  executable  to  be --
25 -- covered  by the  GNU  General  Public  License.  This exception does not --
26 -- however invalidate  any other reasons why  the executable file  might be --
27 -- covered by the  GNU Public License.                                      --
28 --                                                                          --
29 -- GNAT was originally developed  by the GNAT team at  New York University. --
30 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
31 --                                                                          --
32 ------------------------------------------------------------------------------
33
34 with Ada.Characters.Handling;
35 with Ada.Strings.Fixed;
36
37 with Unchecked_Deallocation;
38 with Unchecked_Conversion;
39
40 with System;      use System;
41 with System.CRTL; use System.CRTL;
42
43 with GNAT.OS_Lib;
44
45 package body GNAT.Directory_Operations is
46
47    use Ada;
48
49    type Dir_Type_Value is new System.Address;
50    --  This is the low-level address directory structure as returned by the C
51    --  opendir routine.
52
53    Filename_Max : constant Integer := 1024;
54    --  1024 is the value of FILENAME_MAX in stdio.h
55
56    procedure Free is new
57      Unchecked_Deallocation (Dir_Type_Value, Dir_Type);
58
59    ---------------
60    -- Base_Name --
61    ---------------
62
63    function Base_Name
64      (Path   : Path_Name;
65       Suffix : String := "") return String
66    is
67       function Get_File_Names_Case_Sensitive return Integer;
68       pragma Import
69         (C, Get_File_Names_Case_Sensitive,
70          "__gnat_get_file_names_case_sensitive");
71
72       Case_Sensitive_File_Name : constant Boolean :=
73                                    Get_File_Names_Case_Sensitive = 1;
74
75       function Basename
76         (Path   : Path_Name;
77          Suffix : String := "") return String;
78       --  This function does the job. The only difference between Basename
79       --  and Base_Name (the parent function) is that the former is case
80       --  sensitive, while the latter is not. Path and Suffix are adjusted
81       --  appropriately before calling Basename under platforms where the
82       --  file system is not case sensitive.
83
84       --------------
85       -- Basename --
86       --------------
87
88       function Basename
89         (Path   : Path_Name;
90          Suffix : String    := "") return String
91       is
92          Cut_Start : Natural :=
93                        Strings.Fixed.Index
94                          (Path, Dir_Seps, Going => Strings.Backward);
95          Cut_End : Natural;
96
97       begin
98          --  Cut_Start point to the first basename character
99
100          if Cut_Start = 0 then
101             Cut_Start := Path'First;
102
103          else
104             Cut_Start := Cut_Start + 1;
105          end if;
106
107          --  Cut_End point to the last basename character
108
109          Cut_End := Path'Last;
110
111          --  If basename ends with Suffix, adjust Cut_End
112
113          if Suffix /= ""
114            and then Path (Path'Last - Suffix'Length + 1 .. Cut_End) = Suffix
115          then
116             Cut_End := Path'Last - Suffix'Length;
117          end if;
118
119          Check_For_Standard_Dirs : declare
120             Offset : constant Integer := Path'First - Base_Name.Path'First;
121             BN     : constant String  :=
122                        Base_Name.Path (Cut_Start - Offset .. Cut_End - Offset);
123             --  Here we use Base_Name.Path to keep the original casing
124
125             Has_Drive_Letter : constant Boolean :=
126                                  OS_Lib.Path_Separator /= ':';
127             --  If Path separator is not ':' then we are on a DOS based OS
128             --  where this character is used as a drive letter separator.
129
130          begin
131             if BN = "." or else BN = ".." then
132                return "";
133
134             elsif Has_Drive_Letter
135               and then BN'Length > 2
136               and then Characters.Handling.Is_Letter (BN (BN'First))
137               and then BN (BN'First + 1) = ':'
138             then
139                --  We have a DOS drive letter prefix, remove it
140
141                return BN (BN'First + 2 .. BN'Last);
142
143             else
144                return BN;
145             end if;
146          end Check_For_Standard_Dirs;
147       end Basename;
148
149    --  Start processing for Base_Name
150
151    begin
152       if Path'Length <= Suffix'Length then
153          return Path;
154       end if;
155
156       if Case_Sensitive_File_Name then
157          return Basename (Path, Suffix);
158       else
159          return Basename
160            (Characters.Handling.To_Lower (Path),
161             Characters.Handling.To_Lower (Suffix));
162       end if;
163    end Base_Name;
164
165    ----------------
166    -- Change_Dir --
167    ----------------
168
169    procedure Change_Dir (Dir_Name : Dir_Name_Str) is
170       C_Dir_Name : constant String := Dir_Name & ASCII.NUL;
171
172       function chdir (Dir_Name : String) return Integer;
173       pragma Import (C, chdir, "chdir");
174
175    begin
176       if chdir (C_Dir_Name) /= 0 then
177          raise Directory_Error;
178       end if;
179    end Change_Dir;
180
181    -----------
182    -- Close --
183    -----------
184
185    procedure Close (Dir : in out Dir_Type) is
186       Discard : Integer;
187       pragma Warnings (Off, Discard);
188
189       function closedir (directory : DIRs) return Integer;
190       pragma Import (C, closedir, "__gnat_closedir");
191
192    begin
193       if not Is_Open (Dir) then
194          raise Directory_Error;
195       end if;
196
197       Discard := closedir (DIRs (Dir.all));
198       Free (Dir);
199    end Close;
200
201    --------------
202    -- Dir_Name --
203    --------------
204
205    function Dir_Name (Path : Path_Name) return Dir_Name_Str is
206       Last_DS : constant Natural :=
207                   Strings.Fixed.Index
208                     (Path, Dir_Seps, Going => Strings.Backward);
209
210    begin
211       if Last_DS = 0 then
212
213          --  There is no directory separator, returns current working directory
214
215          return "." & Dir_Separator;
216
217       else
218          return Path (Path'First .. Last_DS);
219       end if;
220    end Dir_Name;
221
222    -----------------
223    -- Expand_Path --
224    -----------------
225
226    function Expand_Path
227      (Path : Path_Name;
228       Mode : Environment_Style := System_Default) return Path_Name
229    is
230       Environment_Variable_Char : Character;
231       pragma Import (C, Environment_Variable_Char, "__gnat_environment_char");
232
233       Result      : OS_Lib.String_Access := new String (1 .. 200);
234       Result_Last : Natural := 0;
235
236       procedure Append (C : Character);
237       procedure Append (S : String);
238       --  Append to Result
239
240       procedure Double_Result_Size;
241       --  Reallocate Result, doubling its size
242
243       function Is_Var_Prefix (C : Character) return Boolean;
244       pragma Inline (Is_Var_Prefix);
245
246       procedure Read (K : in out Positive);
247       --  Update Result while reading current Path starting at position K. If
248       --  a variable is found, call Var below.
249
250       procedure Var (K : in out Positive);
251       --  Translate variable name starting at position K with the associated
252       --  environment value.
253
254       ------------
255       -- Append --
256       ------------
257
258       procedure Append (C : Character) is
259       begin
260          if Result_Last = Result'Last then
261             Double_Result_Size;
262          end if;
263
264          Result_Last := Result_Last + 1;
265          Result (Result_Last) := C;
266       end Append;
267
268       procedure Append (S : String) is
269       begin
270          while Result_Last + S'Length - 1 > Result'Last loop
271             Double_Result_Size;
272          end loop;
273
274          Result (Result_Last + 1 .. Result_Last + S'Length) := S;
275          Result_Last := Result_Last + S'Length;
276       end Append;
277
278       ------------------------
279       -- Double_Result_Size --
280       ------------------------
281
282       procedure Double_Result_Size is
283          New_Result : constant OS_Lib.String_Access :=
284                         new String (1 .. 2 * Result'Last);
285       begin
286          New_Result (1 .. Result_Last) := Result (1 .. Result_Last);
287          OS_Lib.Free (Result);
288          Result := New_Result;
289       end Double_Result_Size;
290
291       -------------------
292       -- Is_Var_Prefix --
293       -------------------
294
295       function Is_Var_Prefix (C : Character) return Boolean is
296       begin
297          return (C = Environment_Variable_Char and then Mode = System_Default)
298            or else
299              (C = '$' and then (Mode = UNIX or else Mode = Both))
300            or else
301              (C = '%' and then (Mode = DOS or else Mode = Both));
302       end Is_Var_Prefix;
303
304       ----------
305       -- Read --
306       ----------
307
308       procedure Read (K : in out Positive) is
309          P : Character;
310
311       begin
312          For_All_Characters : loop
313             if Is_Var_Prefix (Path (K)) then
314                P := Path (K);
315
316                --  Could be a variable
317
318                if K < Path'Last then
319                   if Path (K + 1) = P then
320
321                      --  Not a variable after all, this is a double $ or %,
322                      --  just insert one in the result string.
323
324                      Append (P);
325                      K := K + 1;
326
327                   else
328                      --  Let's parse the variable
329
330                      Var (K);
331                   end if;
332
333                else
334                   --  We have an ending $ or % sign
335
336                   Append (P);
337                end if;
338
339             else
340                --  This is a standard character, just add it to the result
341
342                Append (Path (K));
343             end if;
344
345             --  Skip to next character
346
347             K := K + 1;
348
349             exit For_All_Characters when K > Path'Last;
350          end loop For_All_Characters;
351       end Read;
352
353       ---------
354       -- Var --
355       ---------
356
357       procedure Var (K : in out Positive) is
358          P : constant Character := Path (K);
359          T : Character;
360          E : Positive;
361
362       begin
363          K := K + 1;
364
365          if P = '%' or else Path (K) = '{' then
366
367             --  Set terminator character
368
369             if P = '%' then
370                T := '%';
371             else
372                T := '}';
373                K := K + 1;
374             end if;
375
376             --  Look for terminator character, k point to the first character
377             --  for the variable name.
378
379             E := K;
380
381             loop
382                E := E + 1;
383                exit when Path (E) = T or else E = Path'Last;
384             end loop;
385
386             if Path (E) = T then
387
388                --  OK found, translate with environment value
389
390                declare
391                   Env : OS_Lib.String_Access :=
392                           OS_Lib.Getenv (Path (K .. E - 1));
393
394                begin
395                   Append (Env.all);
396                   OS_Lib.Free (Env);
397                end;
398
399             else
400                --  No terminator character, not a variable after all or a
401                --  syntax error, ignore it, insert string as-is.
402
403                Append (P);       --  Add prefix character
404
405                if T = '}' then   --  If we were looking for curly bracket
406                   Append ('{');  --  terminator, add the curly bracket
407                end if;
408
409                Append (Path (K .. E));
410             end if;
411
412          else
413             --  The variable name is everything from current position to first
414             --  non letter/digit character.
415
416             E := K;
417
418             --  Check that first chartacter is a letter
419
420             if Characters.Handling.Is_Letter (Path (E)) then
421                E := E + 1;
422
423                Var_Name : loop
424                   exit Var_Name when E > Path'Last;
425
426                   if Characters.Handling.Is_Letter (Path (E))
427                     or else Characters.Handling.Is_Digit (Path (E))
428                   then
429                      E := E + 1;
430                   else
431                      exit Var_Name;
432                   end if;
433                end loop Var_Name;
434
435                E := E - 1;
436
437                declare
438                   Env : OS_Lib.String_Access := OS_Lib.Getenv (Path (K .. E));
439
440                begin
441                   Append (Env.all);
442                   OS_Lib.Free (Env);
443                end;
444
445             else
446                --  This is not a variable after all
447
448                Append ('$');
449                Append (Path (E));
450             end if;
451
452          end if;
453
454          K := E;
455       end Var;
456
457    --  Start of processing for Expand_Path
458
459    begin
460       declare
461          K : Positive := Path'First;
462
463       begin
464          Read (K);
465
466          declare
467             Returned_Value : constant String := Result (1 .. Result_Last);
468
469          begin
470             OS_Lib.Free (Result);
471             return Returned_Value;
472          end;
473       end;
474    end Expand_Path;
475
476    --------------------
477    -- File_Extension --
478    --------------------
479
480    function File_Extension (Path : Path_Name) return String is
481       First : Natural :=
482                 Strings.Fixed.Index
483                   (Path, Dir_Seps, Going => Strings.Backward);
484
485       Dot : Natural;
486
487    begin
488       if First = 0 then
489          First := Path'First;
490       end if;
491
492       Dot := Strings.Fixed.Index (Path (First .. Path'Last),
493                                   ".",
494                                   Going => Strings.Backward);
495
496       if Dot = 0 or else Dot = Path'Last then
497          return "";
498       else
499          return Path (Dot .. Path'Last);
500       end if;
501    end File_Extension;
502
503    ---------------
504    -- File_Name --
505    ---------------
506
507    function File_Name (Path : Path_Name) return String is
508    begin
509       return Base_Name (Path);
510    end File_Name;
511
512    ---------------------
513    -- Format_Pathname --
514    ---------------------
515
516    function Format_Pathname
517      (Path  : Path_Name;
518       Style : Path_Style := System_Default) return String
519    is
520       N_Path       : String   := Path;
521       K            : Positive := N_Path'First;
522       Prev_Dirsep  : Boolean  := False;
523
524    begin
525       if Dir_Separator = '\'
526         and then Path'Length > 1
527         and then Path (K .. K + 1) = "\\"
528       then
529          if Style = UNIX then
530             N_Path (K .. K + 1) := "//";
531          end if;
532
533          K := K + 2;
534       end if;
535
536       for J in K .. Path'Last loop
537          if Strings.Maps.Is_In (Path (J), Dir_Seps) then
538             if not Prev_Dirsep then
539                case Style is
540                   when UNIX           => N_Path (K) := '/';
541                   when DOS            => N_Path (K) := '\';
542                   when System_Default => N_Path (K) := Dir_Separator;
543                end case;
544
545                K := K + 1;
546             end if;
547
548             Prev_Dirsep := True;
549
550          else
551             N_Path (K) := Path (J);
552             K := K + 1;
553             Prev_Dirsep := False;
554          end if;
555       end loop;
556
557       return N_Path (N_Path'First .. K - 1);
558    end Format_Pathname;
559
560    ---------------------
561    -- Get_Current_Dir --
562    ---------------------
563
564    Max_Path : Integer;
565    pragma Import (C, Max_Path, "__gnat_max_path_len");
566
567    function Get_Current_Dir return Dir_Name_Str is
568       Current_Dir : String (1 .. Max_Path + 1);
569       Last        : Natural;
570    begin
571       Get_Current_Dir (Current_Dir, Last);
572       return Current_Dir (1 .. Last);
573    end Get_Current_Dir;
574
575    procedure Get_Current_Dir (Dir : out Dir_Name_Str; Last : out Natural) is
576       Path_Len : Natural := Max_Path;
577       Buffer   : String (Dir'First .. Dir'First + Max_Path + 1);
578
579       procedure Local_Get_Current_Dir
580         (Dir    : System.Address;
581          Length : System.Address);
582       pragma Import (C, Local_Get_Current_Dir, "__gnat_get_current_dir");
583
584    begin
585       Local_Get_Current_Dir (Buffer'Address, Path_Len'Address);
586
587       if Dir'Length > Path_Len then
588          Last := Dir'First + Path_Len - 1;
589       else
590          Last := Dir'Last;
591       end if;
592
593       Dir (Buffer'First .. Last) := Buffer (Buffer'First .. Last);
594    end Get_Current_Dir;
595
596    -------------
597    -- Is_Open --
598    -------------
599
600    function Is_Open (Dir : Dir_Type) return Boolean is
601    begin
602       return Dir /= Null_Dir
603         and then System.Address (Dir.all) /= System.Null_Address;
604    end Is_Open;
605
606    --------------
607    -- Make_Dir --
608    --------------
609
610    procedure Make_Dir (Dir_Name : Dir_Name_Str) is
611       C_Dir_Name : constant String := Dir_Name & ASCII.NUL;
612
613       function mkdir (Dir_Name : String) return Integer;
614       pragma Import (C, mkdir, "__gnat_mkdir");
615
616    begin
617       if mkdir (C_Dir_Name) /= 0 then
618          raise Directory_Error;
619       end if;
620    end Make_Dir;
621
622    ----------
623    -- Open --
624    ----------
625
626    procedure Open
627      (Dir      : out Dir_Type;
628       Dir_Name : Dir_Name_Str)
629    is
630       function opendir (file_name : String) return DIRs;
631       pragma Import (C, opendir, "__gnat_opendir");
632
633       C_File_Name : constant String := Dir_Name & ASCII.NUL;
634
635    begin
636       Dir := new Dir_Type_Value'(Dir_Type_Value (opendir (C_File_Name)));
637
638       if not Is_Open (Dir) then
639          Free (Dir);
640          Dir := Null_Dir;
641          raise Directory_Error;
642       end if;
643    end Open;
644
645    ----------
646    -- Read --
647    ----------
648
649    procedure Read
650      (Dir  : in out Dir_Type;
651       Str  : out String;
652       Last : out Natural)
653    is
654       Filename_Addr : Address;
655       Filename_Len  : aliased Integer;
656
657       Buffer : array (0 .. Filename_Max + 12) of Character;
658       --  12 is the size of the dirent structure (see dirent.h), without the
659       --  field for the filename.
660
661       function readdir_gnat
662         (Directory : System.Address;
663          Buffer    : System.Address;
664          Last      : access Integer) return System.Address;
665       pragma Import (C, readdir_gnat, "__gnat_readdir");
666
667    begin
668       if not Is_Open (Dir) then
669          raise Directory_Error;
670       end if;
671
672       Filename_Addr :=
673         readdir_gnat
674           (System.Address (Dir.all), Buffer'Address, Filename_Len'Access);
675
676       if Filename_Addr = System.Null_Address then
677          Last := 0;
678          return;
679       end if;
680
681       if Str'Length > Filename_Len then
682          Last := Str'First + Filename_Len - 1;
683       else
684          Last := Str'Last;
685       end if;
686
687       declare
688          subtype Path_String is String (1 .. Filename_Len);
689          type    Path_String_Access is access Path_String;
690
691          function Address_To_Access is new
692            Unchecked_Conversion
693              (Source => Address,
694               Target => Path_String_Access);
695
696          Path_Access : constant Path_String_Access :=
697                          Address_To_Access (Filename_Addr);
698
699       begin
700          for J in Str'First .. Last loop
701             Str (J) := Path_Access (J - Str'First + 1);
702          end loop;
703       end;
704    end Read;
705
706    -------------------------
707    -- Read_Is_Thread_Sage --
708    -------------------------
709
710    function Read_Is_Thread_Safe return Boolean is
711       function readdir_is_thread_safe return Integer;
712       pragma Import
713         (C, readdir_is_thread_safe, "__gnat_readdir_is_thread_safe");
714    begin
715       return (readdir_is_thread_safe /= 0);
716    end Read_Is_Thread_Safe;
717
718    ----------------
719    -- Remove_Dir --
720    ----------------
721
722    procedure Remove_Dir
723      (Dir_Name  : Dir_Name_Str;
724       Recursive : Boolean := False)
725    is
726       C_Dir_Name  : constant String := Dir_Name & ASCII.NUL;
727       Current_Dir : constant Dir_Name_Str := Get_Current_Dir;
728       Last        : Integer;
729       Str         : String (1 .. Filename_Max);
730       Success     : Boolean;
731       Working_Dir : Dir_Type;
732
733    begin
734       --  Remove the directory only if it is empty
735
736       if not Recursive then
737          rmdir (C_Dir_Name);
738
739          if GNAT.OS_Lib.Is_Directory (Dir_Name) then
740             raise Directory_Error;
741          end if;
742
743       --  Remove directory and all files and directories that it may contain
744
745       else
746          Change_Dir (Dir_Name);
747          Open (Working_Dir, ".");
748
749          loop
750             Read (Working_Dir, Str, Last);
751             exit when Last = 0;
752
753             if GNAT.OS_Lib.Is_Directory (Str (1 .. Last)) then
754                if Str (1 .. Last) /= "." and then Str (1 .. Last) /= ".." then
755                   Remove_Dir (Str (1 .. Last), True);
756                   Remove_Dir (Str (1 .. Last));
757                end if;
758
759             else
760                GNAT.OS_Lib.Delete_File (Str (1 .. Last), Success);
761
762                if not Success then
763                   Change_Dir (Current_Dir);
764                   raise Directory_Error;
765                end if;
766             end if;
767          end loop;
768
769          Change_Dir (Current_Dir);
770          Close (Working_Dir);
771          Remove_Dir (Dir_Name);
772       end if;
773    end Remove_Dir;
774
775 end GNAT.Directory_Operations;