@@ -401,7 +401,7 @@ def assert_bash_exec(
401
401
class bash_env_saved :
402
402
def __init__ (self , bash : pexpect .spawn , sendintr : bool = False ):
403
403
self .bash = bash
404
- self .cwd : Optional [ str ] = None
404
+ self .cwd_changed : bool = False
405
405
self .saved_shopt : Dict [str , int ] = {}
406
406
self .saved_variables : Dict [str , int ] = {}
407
407
self .sendintr = sendintr
@@ -429,8 +429,9 @@ def _unset_variable(self, varname: str):
429
429
assert_bash_exec (self .bash , "unset -v %s" % varname )
430
430
431
431
def _save_cwd (self ):
432
- if not self .cwd :
433
- self .cwd = self .bash .cwd
432
+ if not self .cwd_changed :
433
+ self .cwd_changed = True
434
+ self ._copy_variable ("PWD" , "_BASHCOMP_TEST_OLDPWD" )
434
435
435
436
def _check_shopt (self , name : str ):
436
437
assert_bash_exec (
@@ -457,11 +458,15 @@ def _protect_shopt(self, name: str):
457
458
)
458
459
459
460
def _check_variable (self , varname : str ):
460
- assert_bash_exec (
461
- self .bash ,
462
- '[[ ${%s-%s} == "${_BASHCOMP_TEST_NEWVAR_%s-%s}" ]]'
463
- % (varname , MAGIC_MARK2 , varname , MAGIC_MARK2 ),
464
- )
461
+ try :
462
+ assert_bash_exec (
463
+ self .bash ,
464
+ '[[ ${%s-%s} == "${_BASHCOMP_TEST_NEWVAR_%s-%s}" ]]'
465
+ % (varname , MAGIC_MARK2 , varname , MAGIC_MARK2 ),
466
+ )
467
+ except AssertionError :
468
+ self ._copy_variable ("_BASHCOMP_TEST_NEWVAR_" + varname , varname )
469
+ raise
465
470
466
471
def _unprotect_variable (self , varname : str ):
467
472
if varname not in self .saved_variables :
@@ -480,11 +485,12 @@ def _restore_env(self):
480
485
481
486
# We first go back to the original directory before restoring
482
487
# variables because "cd" affects "OLDPWD".
483
- if self .cwd :
488
+ if self .cwd_changed :
484
489
self ._unprotect_variable ("OLDPWD" )
485
- assert_bash_exec (self .bash , " cd %s" % shlex . quote ( str ( self . cwd )) )
490
+ assert_bash_exec (self .bash , ' cd "$_BASHCOMP_TEST_OLDPWD"' )
486
491
self ._protect_variable ("OLDPWD" )
487
- self .cwd = None
492
+ self ._unset_variable ("_BASHCOMP_TEST_OLDPWD" )
493
+ self .cwd_changed = False
488
494
489
495
for name in self .saved_shopt :
490
496
self ._check_shopt (name )
@@ -504,6 +510,7 @@ def _restore_env(self):
504
510
505
511
def chdir (self , path : str ):
506
512
self ._save_cwd ()
513
+ self .cwd_changed = True
507
514
self ._unprotect_variable ("OLDPWD" )
508
515
assert_bash_exec (self .bash , "cd %s" % shlex .quote (path ))
509
516
self ._protect_variable ("OLDPWD" )
0 commit comments