1- from tomllib import load , TOMLDecodeError
1+ from tomllib import TOMLDecodeError , load
22
33from zenlib .logging import loggify
44from zenlib .util import pretty_print
55
66from ugrd .initramfs_dict import InitramfsConfigDict
7+
78from .generator_helpers import GeneratorHelpers
89
910
1011@loggify
1112class InitramfsGenerator (GeneratorHelpers ):
12- def __init__ (self , config = ' /etc/ugrd/config.toml' , * args , ** kwargs ):
13- self .config_dict = InitramfsConfigDict (NO_BASE = kwargs .pop (' NO_BASE' , False ), logger = self .logger , _log_init = False )
13+ def __init__ (self , config = " /etc/ugrd/config.toml" , * args , ** kwargs ):
14+ self .config_dict = InitramfsConfigDict (NO_BASE = kwargs .pop (" NO_BASE" , False ), logger = self .logger )
1415
1516 # Used for functions that are added to the bash source file
1617 self .included_functions = {}
1718
1819 # Used for functions that are run as part of the build process
19- self .build_tasks = [' build_pre' , ' build_tasks' , ' build_late' , ' build_deploy' , ' build_final' ]
20+ self .build_tasks = [" build_pre" , " build_tasks" , " build_late" , " build_deploy" , " build_final" ]
2021
2122 # init_pre and init_final are run as part of generate_initramfs_main
22- self .init_types = ['init_debug' , 'init_early' , 'init_main' , 'init_late' , 'init_premount' , 'init_mount' , 'init_mount_late' , 'init_cleanup' ]
23+ self .init_types = [
24+ "init_debug" ,
25+ "init_early" ,
26+ "init_main" ,
27+ "init_late" ,
28+ "init_premount" ,
29+ "init_mount" ,
30+ "init_mount_late" ,
31+ "init_cleanup" ,
32+ ]
2333
2434 # Passed kwargs must be imported early, so they will be processed against the base configuration
2535 self .config_dict .import_args (kwargs )
@@ -40,7 +50,7 @@ def load_config(self, config_filename) -> None:
4050 if not config_filename :
4151 raise FileNotFoundError ("Config file not specified." )
4252
43- with open (config_filename , 'rb' ) as config_file :
53+ with open (config_filename , "rb" ) as config_file :
4454 self .logger .info ("Loading config file: %s" % config_file .name )
4555 raw_config = load (config_file )
4656
@@ -64,14 +74,15 @@ def get(self, item, default=None):
6474 return self .config_dict .get (item , default )
6575
6676 def __getattr__ (self , item ):
67- """ Allows access to the config dict via the InitramfsGenerator object. """
68- if item not in self .__dict__ and item != ' config_dict' :
77+ """Allows access to the config dict via the InitramfsGenerator object."""
78+ if item not in self .__dict__ and item != " config_dict" :
6979 return self [item ]
7080 return super ().__getattr__ (item )
7181
7282 def build (self ) -> None :
73- """ Builds the initramfs image. """
83+ """Builds the initramfs image."""
7484 from importlib .metadata import version
85+
7586 self ._log_run (f"Running ugrd v{ version ('ugrd' )} " )
7687 self .run_build ()
7788 self .config_dict .validate () # Validate the config after the build tasks have been run
@@ -87,17 +98,19 @@ def run_func(self, function, force_include=False, force_exclude=False) -> list[s
8798 If force_include is set, forces the function to be included in the bash source file.
8899 if force_exclude is set, does not include the output of the function in the bash source file.
89100 """
90- self .logger .log (self [' _build_log_level' ], "Running function: %s" % function .__name__ )
101+ self .logger .log (self [" _build_log_level" ], "Running function: %s" % function .__name__ )
91102
92103 if function_output := function (self ):
93104 if isinstance (function_output , list ) and len (function_output ) == 1 :
94- self .logger .debug ("[%s] Function returned list with one element: %s" % (function .__name__ , function_output [0 ]))
105+ self .logger .debug (
106+ "[%s] Function returned list with one element: %s" % (function .__name__ , function_output [0 ])
107+ )
95108 function_output = function_output [0 ]
96109
97110 if function .__name__ in self .included_functions :
98111 raise ValueError ("Function '%s' has already been included in the bash source file" % function .__name__ )
99112
100- if function .__name__ in self [' binaries' ]:
113+ if function .__name__ in self [" binaries" ]:
101114 raise ValueError ("Function name collides with defined binary: %s" % (function .__name__ ))
102115 return function_output
103116
@@ -106,7 +119,9 @@ def run_func(self, function, force_include=False, force_exclude=False) -> list[s
106119 return function_output
107120
108121 if not force_exclude :
109- self .logger .debug ("[%s] Function returned output: %s" % (function .__name__ , pretty_print (function_output )))
122+ self .logger .debug (
123+ "[%s] Function returned output: %s" % (function .__name__ , pretty_print (function_output ))
124+ )
110125 self .included_functions [function .__name__ ] = function_output
111126 self .logger .debug ("Created function alias: %s" % function .__name__ )
112127 elif function_output :
@@ -116,26 +131,29 @@ def run_func(self, function, force_include=False, force_exclude=False) -> list[s
116131 self .logger .debug ("[%s] Function returned no output" % function .__name__ )
117132
118133 def run_hook (self , hook : str , * args , ** kwargs ) -> list [str ]:
119- """ Runs a hook for imported functions. """
134+ """Runs a hook for imported functions."""
120135 out = []
121- for function in self [' imports' ].get (hook , []):
136+ for function in self [" imports" ].get (hook , []):
122137 # Check that the function is not masked
123- if function .__name__ in self [' masks' ].get (hook , []):
138+ if function .__name__ in self [" masks" ].get (hook , []):
124139 self .logger .warning ("[%s] Skipping masked function: %s" % (hook , function .__name__ ))
125140 continue
126141 if function_output := self .run_func (function , * args , ** kwargs ):
127142 out .append (function_output )
128143 return out
129144
130145 def generate_profile (self ) -> list [str ]:
131- """ Generates the bash profile file based on self.included_functions. """
146+ """Generates the bash profile file based on self.included_functions."""
132147 from importlib .metadata import version
133- ver = version (__package__ ) or 9999 # Version won't be found unless the package is installed
134- out = [self ['shebang' ].split (' ' )[0 ], # Don't add arguments to the shebang (for the profile)
135- f"#\n # Generated by UGRD v{ ver } \n #" ]
148+
149+ ver = version (__package__ ) or 9999 # Version won't be found unless the package is installed
150+ out = [
151+ self ["shebang" ].split (" " )[0 ], # Don't add arguments to the shebang (for the profile)
152+ f"#\n # Generated by UGRD v{ ver } \n #" ,
153+ ]
136154
137155 # Add the library paths
138- library_paths = ":" .join (self [' library_paths' ])
156+ library_paths = ":" .join (self [" library_paths" ])
139157 self .logger .debug ("Library paths: %s" % library_paths )
140158 out .append (f"export LD_LIBRARY_PATH={ library_paths } " )
141159
@@ -166,76 +184,76 @@ def generate_init_main(self) -> list[str]:
166184 return out
167185
168186 def generate_init (self ) -> None :
169- """ Generates the init file. """
187+ """Generates the init file."""
170188 self ._log_run ("Generating init functions" )
171- init = [self [' shebang' ]] # Add the shebang to the top of the init file
189+ init = [self [" shebang" ]] # Add the shebang to the top of the init file
172190
173191 # Run all included functions, so they get included
174- self .run_hook (' functions' , force_include = True )
192+ self .run_hook (" functions" , force_include = True )
175193
176- init .extend (self .run_init_hook (' init_pre' )) # Always run init_pre first
194+ init .extend (self .run_init_hook (" init_pre" )) # Always run init_pre first
177195
178196 # If custom_init is used, create the init using that
179- if self [' imports' ].get (' custom_init' ) and self .get (' _custom_init_file' ):
197+ if self [" imports" ].get (" custom_init" ) and self .get (" _custom_init_file" ):
180198 init += ["\n # !!custom_init" ]
181- init_line , custom_init = self [' imports' ][ ' custom_init' ](self )
199+ init_line , custom_init = self [" imports" ][ " custom_init" ](self )
182200 if isinstance (init_line , str ):
183201 init .append (init_line )
184202 else :
185203 init .extend (init_line )
186204 else : # Otherwise, use the standard init generator
187205 init .extend (self .generate_init_main ())
188206
189- init .extend (self .run_init_hook (' init_final' )) # Always run init_final last
207+ init .extend (self .run_init_hook (" init_final" )) # Always run init_final last
190208 init += ["\n \n # END INIT" ]
191209
192210 if self .included_functions : # There should always be included functions, if the base config is used
193- self ._write (' /etc/profile' , self .generate_profile (), 0o755 )
194- self .logger .info ("Included functions: %s" % ', ' .join (list (self .included_functions .keys ())))
211+ self ._write (" /etc/profile" , self .generate_profile (), 0o755 )
212+ self .logger .info ("Included functions: %s" % ", " .join (list (self .included_functions .keys ())))
195213
196- if self .get (' _custom_init_file' ): # Write the custom init file if it exists
197- self ._write (self [' _custom_init_file' ], custom_init , 0o755 )
214+ if self .get (" _custom_init_file" ): # Write the custom init file if it exists
215+ self ._write (self [" _custom_init_file" ], custom_init , 0o755 )
198216
199- self ._write (' init' , init , 0o755 )
217+ self ._write (" init" , init , 0o755 )
200218 self .logger .debug ("Final config:\n %s" % self )
201219
202220 def run_build (self ) -> None :
203- """ Runs all build tasks. """
221+ """Runs all build tasks."""
204222 self ._log_run ("Running build tasks" )
205223 for task in self .build_tasks :
206224 self .logger .debug ("Running build task: %s" % task )
207225 self .run_hook (task , force_exclude = True )
208226
209227 def pack_build (self ) -> None :
210- """ Packs the initramfs based on self['imports']['pack']."""
228+ """Packs the initramfs based on self['imports']['pack']."""
211229 self ._log_run ("Packing build" )
212- if self [' imports' ].get (' pack' ):
213- self .run_hook (' pack' )
230+ if self [" imports" ].get (" pack" ):
231+ self .run_hook (" pack" )
214232 else :
215233 self .logger .warning ("No pack functions specified, the final build is present in: %s" % self .build_dir )
216234
217235 def run_init_hook (self , level : str ) -> list [str ]:
218- """ Runs the specified init hook, returning the output. """
236+ """Runs the specified init hook, returning the output."""
219237 if runlevel := self .run_hook (level ):
220- out = [' \n # Begin %s' % level ]
238+ out = [" \n # Begin %s" % level ]
221239 out += runlevel
222240 return out
223241 else :
224242 self .logger .debug ("No output for init level: %s" % level )
225243 return []
226244
227245 def run_checks (self ) -> None :
228- """ Runs checks if defined in self['imports']['checks']. """
246+ """Runs checks if defined in self['imports']['checks']."""
229247 self ._log_run ("Running checks" )
230- if check_output := self .run_hook (' checks' ):
248+ if check_output := self .run_hook (" checks" ):
231249 for check in check_output :
232250 self .logger .debug (check )
233251 else :
234252 self .logger .warning ("No checks executed." )
235253
236254 def run_tests (self ) -> None :
237- """ Runs tests if defined in self['imports']['tests']. """
238- if test_output := self .run_hook (' tests' ):
255+ """Runs tests if defined in self['imports']['tests']."""
256+ if test_output := self .run_hook (" tests" ):
239257 self ._log_run ("Running tests" )
240258 self .logger .info ("Completed tests:\n %s" , test_output )
241259 else :
@@ -246,4 +264,3 @@ def _log_run(self, logline) -> None:
246264
247265 def __str__ (self ) -> str :
248266 return str (self .config_dict )
249-
0 commit comments