config.adb
1 -- SPDX-License-Identifier: AGPL-3.0-or-later 2 3 with Ada.Environment_Variables; 4 with Ada.Directories; 5 with Ada.Text_IO; 6 with Ada.IO_Exceptions; 7 8 package body Config is 9 10 function Get_Config_Dir return String is 11 Home : constant String := Ada.Environment_Variables.Value ("HOME"); 12 begin 13 return Home & "/.config/bitfuckit"; 14 end Get_Config_Dir; 15 16 function Get_Config_File return String is 17 begin 18 return Get_Config_Dir & "/config"; 19 end Get_Config_File; 20 21 function Load_Credentials return Credentials is 22 File : Ada.Text_IO.File_Type; 23 Result : Credentials := No_Credentials; 24 begin 25 if not Ada.Directories.Exists (Get_Config_File) then 26 return No_Credentials; 27 end if; 28 29 Ada.Text_IO.Open (File, Ada.Text_IO.In_File, Get_Config_File); 30 31 if not Ada.Text_IO.End_Of_File (File) then 32 Result.Username := To_Unbounded_String (Ada.Text_IO.Get_Line (File)); 33 end if; 34 35 if not Ada.Text_IO.End_Of_File (File) then 36 Result.App_Password := To_Unbounded_String (Ada.Text_IO.Get_Line (File)); 37 end if; 38 39 if not Ada.Text_IO.End_Of_File (File) then 40 Result.Workspace := To_Unbounded_String (Ada.Text_IO.Get_Line (File)); 41 end if; 42 43 Ada.Text_IO.Close (File); 44 return Result; 45 46 exception 47 when Ada.IO_Exceptions.Name_Error => 48 return No_Credentials; 49 when others => 50 if Ada.Text_IO.Is_Open (File) then 51 Ada.Text_IO.Close (File); 52 end if; 53 return No_Credentials; 54 end Load_Credentials; 55 56 procedure Save_Credentials (Creds : Credentials) is 57 File : Ada.Text_IO.File_Type; 58 Dir : constant String := Get_Config_Dir; 59 begin 60 if not Ada.Directories.Exists (Dir) then 61 Ada.Directories.Create_Path (Dir); 62 end if; 63 64 Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, Get_Config_File); 65 Ada.Text_IO.Put_Line (File, To_String (Creds.Username)); 66 Ada.Text_IO.Put_Line (File, To_String (Creds.App_Password)); 67 Ada.Text_IO.Put_Line (File, To_String (Creds.Workspace)); 68 Ada.Text_IO.Close (File); 69 end Save_Credentials; 70 71 function Has_Credentials return Boolean is 72 Creds : constant Credentials := Load_Credentials; 73 begin 74 return Length (Creds.Username) > 0 75 and then Length (Creds.App_Password) > 0 76 and then Length (Creds.Workspace) > 0; 77 end Has_Credentials; 78 79 end Config;