Skip to content

Commit d8c34d5

Browse files
committed
Ⓜ️ Remove stale environments
1 parent 7d4b612 commit d8c34d5

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

cmd/cmd_root.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,12 @@ invenv -r req.txt -- DEBUG=1 somepath/myscript.py`,
7272
return fmt.Errorf("no script name provided")
7373
}
7474

75+
printProgress("Removing stale environments...")
76+
err = clearStaleEnvs()
77+
if flagDebug && err != nil {
78+
loggerErr.Println(err)
79+
}
80+
7581
printProgress("Gathering information about script and environment...")
7682
script, err := NewScript(scriptName, pythonFlag, requirementsFileFlag)
7783
if err != nil {

cmd/utils.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ const LockAcquireAttempts = 300
2929
// LockStaleTime is the time after which the lock is considered stale
3030
const LockStaleTime = 15 * time.Minute
3131

32+
// StaleEnvironmentTime is the time after which the virtual environment is considered stale
33+
const StaleEnvironmentTime = 14 * 24 * time.Hour
34+
3235
// getFileHash calculates the SHA256 hash of the file
3336
func getFileHash(filename string) (string, error) {
3437
// Check that the file exists
@@ -361,3 +364,48 @@ func getRequirementsFileForScript(scriptPath string, requirementsOverride string
361364
}
362365
return "", nil
363366
}
367+
368+
// clearStaleEnvs removes stale virtual environments
369+
func clearStaleEnvs() error {
370+
homeDir, err := os.UserHomeDir()
371+
if err != nil {
372+
return err
373+
}
374+
375+
envsDir := path.Join(homeDir, EnvironmentsDir)
376+
377+
entries, err := os.ReadDir(envsDir)
378+
if err != nil {
379+
return err
380+
}
381+
382+
for _, entry := range entries {
383+
if entry.IsDir() {
384+
info, err := entry.Info()
385+
if err != nil {
386+
if flagDebug {
387+
loggerErr.Println(err)
388+
}
389+
continue
390+
}
391+
if time.Since(info.ModTime()) > StaleEnvironmentTime {
392+
staleEnvAbsPath := path.Join(envsDir, entry.Name())
393+
if !isEnvLocked(staleEnvAbsPath) {
394+
_, err := findProcessWithPrefix(staleEnvAbsPath)
395+
if err == ErrNoProcessFound {
396+
if flagDebug {
397+
loggerErr.Printf("Removing stale virtual environment %s...\n", staleEnvAbsPath)
398+
}
399+
err = removeDir(staleEnvAbsPath)
400+
if err != nil {
401+
if flagDebug {
402+
loggerErr.Println(err)
403+
}
404+
}
405+
}
406+
}
407+
}
408+
}
409+
}
410+
return err
411+
}

0 commit comments

Comments
 (0)