@@ -312,27 +312,35 @@ def save_example(cls, path: str = ".env_example") -> None:
312312 @classmethod
313313 def sync_env_file (cls , path : str = ".env" ) -> None :
314314 """
315- Merge existing .env file with missing expected keys.
315+ Merge existing .env file with missing expected keys
316+ while preserving definition order.
316317 """
317- expected_keys = set ( cls ._envfile ._get_all_keys () )
318+ expected_keys = cls ._envfile ._get_all_keys ()
318319
319320 existing : Dict [str , str ] = {}
320321 if os .path .exists (path ):
321322 with open (path ) as f :
322323 for line in f :
323324 if '=' in line and not line .strip ().startswith ('#' ):
324- key , value = line .strip ( ).split ('=' , 1 )
325+ key , value = line .rstrip ( ' \n ' ).split ('=' , 1 )
325326 existing [key .strip ()] = value .strip ()
326327
327- new_content = ''
328- all_keys = expected_keys . union ( existing . keys ())
328+ written_keys = set ()
329+ lines : List [ str ] = []
329330
330- for key in sorted (all_keys ):
331+ # 1. Write expected keys in definition order
332+ for key in expected_keys :
331333 value = existing .get (key , '' )
332- new_content += f"{ key } ={ value } \n "
334+ lines .append (f"{ key } ={ value } " )
335+ written_keys .add (key )
336+
337+ # 2. Append extra keys that were already in the file
338+ for key , value in existing .items ():
339+ if key not in written_keys :
340+ lines .append (f"{ key } ={ value } " )
333341
334342 with open (path , 'w' ) as f :
335- f .write (new_content )
343+ f .write (" \n " . join ( lines ) + " \n " )
336344
337345 @classmethod
338346 def add (
0 commit comments