@@ -366,7 +366,7 @@ def set_hostname(self, hostname: str, *args :str, **kwargs :str) -> None:
366366 with open (f'{ self .target } /etc/hostname' , 'w' ) as fh :
367367 fh .write (hostname + '\n ' )
368368
369- def set_locale (self , locale_config : LocaleConfiguration ):
369+ def set_locale (self , locale_config : LocaleConfiguration ) -> bool :
370370 modifier = ''
371371 lang = locale_config .sys_lang
372372 encoding = locale_config .sys_enc
@@ -386,15 +386,32 @@ def set_locale(self, locale_config: LocaleConfiguration):
386386 modifier = f"@{ modifier } "
387387 # - End patch
388388
389- with open ( f' { self .target } / etc/locale.gen', 'a' ) as fh :
390- fh . write ( f' { lang } . { encoding } { modifier } { encoding } \n ' )
389+ locale_gen = self .target / ' etc/locale.gen'
390+ locale_gen_lines = locale_gen . read_text (). splitlines ( True )
391391
392- (self .target / "etc" / "locale.conf" ).write_text (f'LANG={ lang } .{ encoding } { modifier } \n ' )
392+ # A locale entry in /etc/locale.gen may or may not contain the encoding
393+ # in the first column of the entry; check for both cases.
394+ entry_re = re .compile (rf'#{ lang } (\.{ encoding } )?{ modifier } { encoding } ' )
395+
396+ for index , line in enumerate (locale_gen_lines ):
397+ if entry_re .match (line ):
398+ uncommented_line = line .removeprefix ('#' )
399+ locale_gen_lines [index ] = uncommented_line
400+ locale_gen .write_text ('' .join (locale_gen_lines ))
401+ lang_value = uncommented_line .split ()[0 ]
402+ break
403+ else :
404+ error (f"Invalid locale: language '{ locale_config .sys_lang } ', encoding '{ locale_config .sys_enc } '" )
405+ return False
393406
394407 try :
395408 SysCommand (f'/usr/bin/arch-chroot { self .target } locale-gen' )
396409 except SysCallError as e :
397410 error (f'Failed to run locale-gen on target: { e } ' )
411+ return False
412+
413+ (self .target / 'etc/locale.conf' ).write_text (f'LANG={ lang_value } \n ' )
414+ return True
398415
399416 def set_timezone (self , zone :str , * args :str , ** kwargs :str ) -> bool :
400417 if not zone :
0 commit comments