Skip to content

Commit

Permalink
Ⓜ️ Keep track of venv freshness in init subcommand
Browse files Browse the repository at this point in the history
  • Loading branch information
jsnjack committed Mar 27, 2024
1 parent e71fa01 commit 443921a
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions cmd/script.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@ import (
"strings"
)

const VEnvInfoFilename = ".venv.version"

// Script represents a Python script
type Script struct {
AbsolutePath string // Full path to the script
EnvDir string // Full path to the virtual environment
PythonInterpreter string // Python interpreter to use
RequirementsPath string // Full path to the requirements file
venvID string // Unique identifier for the virtual environment
fromInitCommand bool // True if the script was created with init subcommand
}

// EnsureEnv ensures that the virtual environment for the script exists. It creates
Expand All @@ -31,6 +34,29 @@ func (s *Script) EnsureEnv(deleteOldEnv bool) error {
}
}

if s.fromInitCommand && readOperationOnly {
// If the script was created with init command, it doesn't have a unique
// environment ID as part of its path, so we can't rely on the presence of
// the environment directory to determine if it exists.
infoFilename := path.Join(s.EnvDir, VEnvInfoFilename)
data, err := os.ReadFile(infoFilename)
if err != nil {
readOperationOnly = false
if flagDebug {
loggerErr.Printf("Failed to read environment info file: %s\n", err)
}
} else {
if strings.TrimSpace(string(data)) != s.venvID {
// Environment ID mismatch, recreate the environment
readOperationOnly = false
deleteOldEnv = true
if flagDebug {
loggerErr.Printf("Environment ID mismatch: got %s, want %s\n", string(data), s.venvID)
}
}
}
}

err = waitUntilEnvIsUnlocked(s.EnvDir)
switch {
case err == nil:
Expand Down Expand Up @@ -68,6 +94,17 @@ func (s *Script) EnsureEnv(deleteOldEnv bool) error {
s.RemoveEnv()
return err
}
if s.fromInitCommand {
// Write the environment ID to the info file
infoFilename := path.Join(s.EnvDir, VEnvInfoFilename)
err = os.WriteFile(infoFilename, []byte(s.venvID), 0644)
if err != nil {
return err
}
if flagDebug {
loggerErr.Printf("Wrote environment ID to %s\n", infoFilename)
}
}
return nil
}
return nil
Expand Down Expand Up @@ -328,6 +365,7 @@ func NewInitCmd(interpreterOverride string, requirementsOverride string) (*Scrip
PythonInterpreter: pythonInterpreter,
RequirementsPath: requirementsFile,
venvID: envID,
fromInitCommand: true,
}
return script, nil
}

0 comments on commit 443921a

Please sign in to comment.