@@ -77,6 +77,15 @@ func (s *Script) EnsureEnv(deleteOldEnv bool) error {
7777
7878 if ! readOperationOnly {
7979 err = lockEnv (s .EnvDir )
80+ if errors .Is (err , ErrEnvAlreadyLocked ) {
81+ // Another process acquired the lock between our check and our
82+ // lock attempt. Wait for it to finish and use the environment.
83+ err = waitUntilEnvIsUnlocked (s .EnvDir )
84+ if err != nil {
85+ return err
86+ }
87+ return nil
88+ }
8089 if err != nil {
8190 return err
8291 }
@@ -195,16 +204,23 @@ func (s *Script) InstallRequirementsInEnv() error {
195204 return err
196205}
197206
198- // RemoveEnv removes the virtual environment for the script. Also removes the lockfile
207+ // RemoveEnv removes the virtual environment for the script. Also removes the lockfile.
208+ // The lockfile is only removed if the directory removal succeeds, so that a broken
209+ // environment is detected and recreated on the next run.
199210func (s * Script ) RemoveEnv () error {
200211 if flagDebug {
201212 loggerErr .Println ("Deleting virtual environment..." )
202213 }
203214
204215 // Remove the virtual environment directory
205- err1 := removeDir (s .EnvDir )
206- err2 := unlockEnv (s .EnvDir )
207- return errors .Join (err1 , err2 )
216+ err := removeDir (s .EnvDir )
217+ if err != nil {
218+ // Do not unlock the environment if the directory removal failed.
219+ // This ensures that the next run detects the stale lock and
220+ // recreates the environment instead of using a broken one.
221+ return err
222+ }
223+ return unlockEnv (s .EnvDir )
208224}
209225
210226// NewScript creates a new Script instance
0 commit comments